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