Mountain/Vine/Server/
Initialize.rs

1//! # Initialize (Vine Server)
2//!
3//! Contains the logic to initialize and start the Mountain gRPC server.
4
5#![allow(non_snake_case, non_camel_case_types)]
6
7use std::{net::SocketAddr, sync::Arc};
8
9use log::{error, info};
10use tauri::{AppHandle, Manager};
11use tonic::transport::Server;
12
13use super::MountainVinegRPCService::MountainVinegRPCService;
14use crate::{
15	RunTime::ApplicationRunTime::ApplicationRunTime,
16	Vine::{Error::VineError, Generated::mountain_service_server::MountainServiceServer},
17};
18
19/// Initializes and starts the gRPC server on a background task.
20///
21/// This function retrieves the core `ApplicationRunTime` from Tauri's managed
22/// state, instantiates the gRPC service implementation
23/// (`MountainVinegRPCService`), and uses `tonic` to serve it at the specified
24/// address.
25///
26/// # Parameters
27/// * `ApplicationHandle`: The Tauri application handle.
28/// * `AddressString`: The address and port to bind the server to (e.g.,
29///   `"[::1]:50051"`).
30///
31/// # Returns
32/// A `Result` indicating if the server setup was successful. The server itself
33/// runs on a separate spawned task.
34pub fn Initialize(ApplicationHandle:AppHandle, AddressString:String) -> Result<(), VineError> {
35	let Address:SocketAddr = AddressString.parse()?;
36
37	let RunTime = ApplicationHandle
38		.try_state::<Arc<ApplicationRunTime>>()
39		.ok_or_else(|| {
40			let msg = "[VineServer] CRITICAL: ApplicationRunTime not found in Tauri state. Server cannot start.";
41
42			error!("{}", msg);
43
44			VineError::ClientNotConnected(msg.to_string())
45		})?
46		.inner()
47		.clone();
48
49	let MountainService = MountainVinegRPCService::Create(ApplicationHandle.clone(), RunTime);
50
51	// Spawn the server to run in the background.
52	tokio::spawn(async move {
53		info!("[VineServer] Starting gRPC server on {}", Address);
54
55		if let Err(e) = Server::builder()
56			.add_service(MountainServiceServer::new(MountainService))
57			.serve(Address)
58			.await
59		{
60			error!("[VineServer] gRPC server failed to run: {}", e);
61		}
62	});
63
64	Ok(())
65}