Skip to main content

Mountain/Vine/Server/
Initialize.rs

1//! # Initialize (Vine Server)
2//!
3//! Contains the logic to initialize and start the Mountain gRPC server.
4//!
5//! This module provides the entry point for starting Vine's gRPC servers:
6//! - **MountainServiceServer**: Listens for connections from Cocoon sidecar
7//! - **CocoonServiceServer**: Listens for connections from Mountain
8//!   (bidirectional)
9//!
10//! ## Initialization Process
11//!
12//! 1. Validates socket addresses
13//! 2. Retrieves ApplicationRunTime from Tauri state
14//! 3. Creates service implementations with runtime dependencies
15//! 4. Spawns server tasks as background tokio tasks
16//! 5. Servers begin listening on specified ports
17//!
18//! ## Server Configuration
19//!
20//! - **Mountaln Service**: Typically on port 50051 (configurable)
21//! - **Cocoon Service**: Typically on port 50052 (configurable)
22//! - Both servers support compression and message size limits
23//!
24//! ## Error Handling
25//!
26//! Initialization failures are logged and returned to the caller.
27//! Once started, servers run independently and log their own errors.
28//!
29//! ## Lifecycle
30//!
31//! Servers run as detached tokio tasks. They will:
32//! - Start immediately when spawned
33//! - Continue until process termination or tokio runtime shutdown
34//! - Log errors to the logging system
35//! - Not automatically restart on failure (caller should implement retry logic
36//!   if needed)
37
38use std::{net::SocketAddr, sync::Arc};
39
40use tauri::{AppHandle, Manager};
41use tonic::transport::Server;
42
43use super::MountainVinegRPCService::MountainVinegRPCService;
44use crate::{
45	RPC::CocoonService::CocoonServiceImpl,
46	RunTime::ApplicationRunTime::ApplicationRunTime,
47	Vine::{
48		Error::VineError,
49		Generated::{cocoon_service_server::CocoonServiceServer, mountain_service_server::MountainServiceServer},
50	},
51	dev_log,
52};
53
54/// Server configuration constants
55mod ServerConfig {
56	use std::time::Duration;
57
58	/// Default port for MountainService server
59	pub const DEFAULT_MOUNTAIN_PORT:u16 = 50051;
60
61	/// Default port for CocoonService server
62	pub const DEFAULT_COCOON_PORT:u16 = 50052;
63
64	/// Maximum concurrent connections per server
65	pub const MAX_CONNECTIONS:usize = 100;
66
67	/// Connection timeout duration
68	pub const CONNECTION_TIMEOUT:Duration = Duration::from_secs(30);
69
70	/// Default message size limit (4MB)
71	pub const MAX_MESSAGE_SIZE:usize = 4 * 1024 * 1024;
72}
73
74/// Validates a socket address string before parsing.
75///
76/// # Parameters
77/// - `AddressString`: The address string to validate
78/// - `ServerName`: Name of the server for error messages
79///
80/// # Returns
81/// - `Ok(SocketAddr)`: Validated and parsed socket address
82/// - `Err(VineError)`: Invalid address format
83fn ValidateSocketAddress(AddressString:&str, ServerName:&str) -> Result<SocketAddr, VineError> {
84	if AddressString.is_empty() {
85		return Err(VineError::InvalidMessageFormat(format!(
86			"{} address cannot be empty",
87			ServerName
88		)));
89	}
90
91	if AddressString.len() > 256 {
92		return Err(VineError::InvalidMessageFormat(format!(
93			"{} address exceeds maximum length (256 characters)",
94			ServerName
95		)));
96	}
97
98	match AddressString.parse::<SocketAddr>() {
99		Ok(addr) => {
100			// Validate port is within valid range
101			if addr.port() < 1024 {
102				dev_log!(
103					"grpc",
104					"warn: [VineServer] {} using privileged port {}, this may require elevated privileges",
105					ServerName,
106					addr.port()
107				);
108			}
109
110			Ok(addr)
111		},
112		Err(e) => Err(VineError::AddressParseError(e)),
113	}
114}
115
116/// Initializes and starts the gRPC servers on background tasks.
117///
118/// This function retrieves the core `ApplicationRunTime` from Tauri's managed
119/// state, instantiates the gRPC service implementations
120/// (`MountainVinegRPCService` and `CocoonServiceServer`), and uses `tonic` to
121/// serve them at the specified addresses.
122///
123/// # Parameters
124/// - `ApplicationHandle`: The Tauri application handle
125/// - `MountainAddressString`: The address and port to bind the Mountain server
126///   to (e.g., `"[::1]:50051"`)
127/// - `CocoonAddressString`: The address and port to bind the Cocoon server to
128///   (e.g., `"[::1]:50052"`)
129///
130/// # Returns
131/// - `Ok(())`: Successfully initialized and started both servers
132/// - `Err(VineError)`: Initialization failed (invalid address, missing runtime,
133///   etc.)
134///
135/// # Errors
136///
137/// This function will return an error if:
138/// - Either socket address string is invalid or unparseable
139/// - ApplicationRunTime is not available in Tauri state
140/// - Server task spawning fails (rare)
141///
142/// # Example
143///
144/// ```rust,no_run
145/// # use Vine::Server::Initialize::Initialize;
146/// # use tauri::AppHandle;
147/// # async fn example(handle: AppHandle) -> Result<(), Box<dyn std::error::Error>> {
148/// Initialize(handle, "[::1]:50051".to_string(), "[::1]:50052".to_string())?;
149/// # Ok(())
150/// # }
151/// ```
152///
153/// # Notes
154///
155/// - Servers run as detached tokio tasks
156/// - Initialization is async-safe but function is synchronous
157/// - Servers log errors independently after startup
158/// - Use `Default` addresses for development (localhost with default ports)
159pub fn Initialize(
160	ApplicationHandle:AppHandle,
161	MountainAddressString:String,
162	CocoonAddressString:String,
163) -> Result<(), VineError> {
164	dev_log!("grpc", "[VineServer] Initializing Vine gRPC servers...");
165	crate::dev_log!("grpc", "initializing Vine gRPC servers");
166
167	// Validate and parse socket addresses
168	let MountainAddress = ValidateSocketAddress(&MountainAddressString, "MountainService")?;
169	let CocoonAddress = ValidateSocketAddress(&CocoonAddressString, "CocoonService")?;
170
171	dev_log!("grpc", "[VineServer] MountainService will bind to: {}", MountainAddress);
172	dev_log!(
173		"grpc",
174		"[VineServer] Cocoon expected on: {} (started by Cocoon process)",
175		CocoonAddress
176	);
177	crate::dev_log!("grpc", "Mountain={} Cocoon(remote)={}", MountainAddress, CocoonAddress);
178
179	// Retrieve ApplicationRunTime from Tauri managed state
180	let RunTime = ApplicationHandle
181		.try_state::<Arc<ApplicationRunTime>>()
182		.ok_or_else(|| {
183			let msg = "[VineServer] CRITICAL: ApplicationRunTime not found in Tauri state. Server cannot start.";
184
185			dev_log!("grpc", "error: {}", msg);
186
187			VineError::InternalLockError(msg.to_string())
188		})?
189		.inner()
190		.clone();
191
192	dev_log!("grpc", "[VineServer] ApplicationRunTime retrieved successfully");
193
194	// Create MountainService implementation (handles calls from Cocoon to Mountain)
195	let MountainService = MountainVinegRPCService::Create(ApplicationHandle.clone(), RunTime.clone());
196
197	// Create CocoonService implementation (handles calls from Mountain to Cocoon)
198	let cocoon_service_impl = CocoonServiceImpl::new(RunTime.Environment.clone());
199
200	dev_log!("grpc", "[VineServer] Service implementations created");
201
202	// Spawn Mountain server to run in the background
203	let MountainServerName = MountainAddress.to_string();
204	tokio::spawn(async move {
205		dev_log!(
206			"grpc",
207			"[VineServer] Starting MountainService gRPC server on {}",
208			MountainServerName
209		);
210
211		let ServerResult = Server::builder()
212			.add_service(
213				MountainServiceServer::new(MountainService)
214					.max_decoding_message_size(ServerConfig::MAX_MESSAGE_SIZE)
215					.max_encoding_message_size(ServerConfig::MAX_MESSAGE_SIZE),
216			)
217			.serve(MountainAddress)
218			.await;
219
220		match ServerResult {
221			Ok(_) => {
222				dev_log!("grpc", "[VineServer] MountainService server shut down gracefully");
223			},
224			Err(e) => {
225				dev_log!("grpc", "error: [VineServer] MountainService gRPC server error: {}", e);
226			},
227		}
228	});
229
230	// NOTE: CocoonService gRPC server is NOT started by Mountain.
231	// Port 50052 is reserved for Cocoon's own gRPC server (started by
232	// Cocoon's Effect-TS bootstrap, Stage 5). Mountain connects to Cocoon
233	// as a CLIENT on 50052 via Vine::Client::ConnectToSideCar.
234	// Starting CocoonServiceServer here would cause EADDRINUSE when Cocoon
235	// tries to bind the same port.
236	let _ = cocoon_service_impl; // suppress unused variable warning
237
238	dev_log!(
239		"grpc",
240		"[VineServer] MountainService gRPC server initialized on {}",
241		MountainAddress
242	);
243
244	Ok(())
245}