microsandbox_server/
state.rs

1//! Application state management for the microsandbox server.
2//!
3//! This module handles:
4//! - Global application state
5//! - Configuration state management
6//! - Thread-safe state sharing
7//!
8//! The module provides:
9//! - Thread-safe application state container
10//! - State initialization and access methods
11//! - Configuration state management
12
13use std::sync::Arc;
14use tokio::sync::RwLock;
15
16use getset::Getters;
17
18use crate::{
19    config::Config,
20    port::{PortManager, LOCALHOST_IP},
21    ServerError, ServerResult,
22};
23
24//--------------------------------------------------------------------------------------------------
25// Types
26//--------------------------------------------------------------------------------------------------
27
28/// Application state structure
29#[derive(Clone, Getters)]
30#[getset(get = "pub with_prefix")]
31pub struct AppState {
32    /// The application configuration
33    config: Arc<Config>,
34
35    /// The port manager for handling sandbox port assignments
36    port_manager: Arc<RwLock<PortManager>>,
37}
38
39//--------------------------------------------------------------------------------------------------
40// Methods
41//--------------------------------------------------------------------------------------------------
42
43impl AppState {
44    /// Create a new application state instance
45    pub fn new(config: Arc<Config>, port_manager: Arc<RwLock<PortManager>>) -> Self {
46        Self {
47            config,
48            port_manager,
49        }
50    }
51
52    /// Get a sandbox's portal URL
53    ///
54    /// Returns an error if no port is assigned for the given sandbox
55    pub async fn get_portal_url_for_sandbox(
56        &self,
57        namespace: &str,
58        sandbox_name: &str,
59    ) -> ServerResult<String> {
60        let port_manager = self.port_manager.read().await;
61        let key = format!("{}/{}", namespace, sandbox_name);
62
63        if let Some(port) = port_manager.get_port(&key) {
64            Ok(format!("http://{}:{}", LOCALHOST_IP, port))
65        } else {
66            Err(ServerError::InternalError(format!(
67                "No portal port assigned for sandbox {}",
68                key
69            )))
70        }
71    }
72}