Skip to main content

kernel/networking/
connection_engine.rs

1use std::collections::HashMap;
2use std::sync::{LazyLock, RwLock};
3use std::sync::atomic::AtomicU64;
4use std::sync::mpsc::Sender;
5use common::logging::LogLevel::*;
6use common::networking::messages::{TcpServerMessage, UserRole, SessionID};
7use common::networking::messages::TcpServerMessage::ShutdownAnnouncement;
8use common::networking::subscription_objects::{SubscribeTopic, UpdateMode};
9use common::r_log;
10
11/// Unique identifier for an active physical TCP connection.
12///
13/// **Note:** If this type is changed (e.g., to `u32`), [`NEXT_CONNECTION_ID`]
14/// must be updated to the corresponding atomic type (e.g., `AtomicU32`).
15pub(super) type ConnectionID = u64;
16/// Thread-safe atomic counter used to generate unique [`ConnectionID`]s for incoming clients.
17pub(super) static NEXT_CONNECTION_ID: AtomicU64 = AtomicU64::new(1);
18
19/// The central, globally accessible repository of all authenticated client sessions.
20/// Maps a unique [`SessionID`] to its corresponding [`ClientSession`].
21pub(super) static SERVER_STATE: LazyLock<RwLock<HashMap<SessionID, ClientSession>>> =
22    LazyLock::new(|| RwLock::new(HashMap::new()));
23
24/// Represents an authenticated user session within the server.
25///
26/// A session persists even if the physical connection drops, allowing clients to
27/// seamlessly reconnect and resume their subscriptions and privileges without logging in again.
28pub(super) struct ClientSession {
29    /// The display name of the authenticated user.
30    pub _user_name: String,
31    /// The permission level and operational scope assigned to this user.
32    pub _user_role: UserRole,
33
34    /// The active communication channel to the client, if currently connected.
35    /// Stores the `mpsc::Sender` for dispatching network messages and the physical [`ConnectionID`].
36    pub active_connection: Option<(Sender<TcpServerMessage>, ConnectionID)>,
37    /// A list of engine state topics this session is currently subscribed to.
38    pub subscriptions: Vec<(SubscribeTopic, UpdateMode)>,
39    
40}
41
42/// Broadcasts a graceful shutdown announcement to all currently connected clients.
43///
44/// Iterates through the global [`SERVER_STATE`] and attempts to dispatch a
45/// `ShutdownAnnouncement` message via every active connection channel.
46pub fn announce_shutdown() {
47    let server_state = SERVER_STATE.read().unwrap();
48    for connection in server_state.values() {
49        if let Some((channel,connection_id)) = connection.active_connection.as_ref() {
50            if let Err(e) = channel.send(ShutdownAnnouncement) {
51                r_log!(Error,"[Conn {}] Error sending Shutdown-Announcement to channel: {}", connection_id, e);
52            }
53        }
54    }
55}