From dc74c19be4c49edf956fef15869b76e653cb98f3 Mon Sep 17 00:00:00 2001 From: huangping Date: Fri, 1 May 2026 14:05:16 +0800 Subject: [PATCH] feat(native): add session management with global handle registry --- native/craft-core/Cargo.toml | 1 + native/craft-core/src/lib.rs | 1 + native/craft-core/src/session.rs | 42 ++++++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+) create mode 100644 native/craft-core/src/session.rs diff --git a/native/craft-core/Cargo.toml b/native/craft-core/Cargo.toml index 10e9838..351b2a9 100644 --- a/native/craft-core/Cargo.toml +++ b/native/craft-core/Cargo.toml @@ -12,6 +12,7 @@ name = "craftlabs_auth_bitanswer" obfstr = "0.4" sha2 = "0.10" libloading = "0.8" +once_cell = "1" [target.'cfg(target_os = "windows")'.dependencies] windows-sys = { version = "0.52", features = ["Win32_System_Diagnostics_Debug"], optional = true } diff --git a/native/craft-core/src/lib.rs b/native/craft-core/src/lib.rs index 6364877..5bf352e 100644 --- a/native/craft-core/src/lib.rs +++ b/native/craft-core/src/lib.rs @@ -11,6 +11,7 @@ mod heartbeat; mod license; mod security; mod error; +mod session; pub struct CraftContext { dummy: i32, diff --git a/native/craft-core/src/session.rs b/native/craft-core/src/session.rs new file mode 100644 index 0000000..c3655b9 --- /dev/null +++ b/native/craft-core/src/session.rs @@ -0,0 +1,42 @@ +use std::collections::HashMap; +use std::sync::Mutex; +use once_cell::sync::Lazy; + +pub struct SessionState { + pub config_json: String, + pub bit_handle: Option, + pub application_data: Vec, + pub logged_in: bool, +} + +pub static SESSIONS: Lazy>> = + Lazy::new(|| Mutex::new(HashMap::new())); + +static NEXT_SESSION_ID: Lazy> = Lazy::new(|| Mutex::new(1)); + +pub fn register_session(config_json: String, application_data: Vec) -> i64 { + let mut next_id = NEXT_SESSION_ID.lock().unwrap(); + let id = *next_id; + *next_id += 1; + let mut sessions = SESSIONS.lock().unwrap(); + sessions.insert(id, SessionState { + config_json, + bit_handle: None, + application_data, + logged_in: false, + }); + id +} + +pub fn with_session(session_id: i64, f: F) -> Option +where + F: FnOnce(&mut SessionState) -> R, +{ + let mut sessions = SESSIONS.lock().unwrap(); + sessions.get_mut(&session_id).map(f) +} + +pub fn remove_session(session_id: i64) { + let mut sessions = SESSIONS.lock().unwrap(); + sessions.remove(&session_id); +}