Skip to main content

khive_capability/
actor.rs

1//! Actor registry — maps session/process identifiers to lion-core PluginIds.
2//!
3//! Each connected client gets a
4//! unique PluginId for the duration of its connection. The registry tracks
5//! active actors and their associated metadata.
6
7use std::collections::HashMap;
8use std::sync::atomic::{AtomicU64, Ordering};
9
10use lion_core::PluginId;
11
12#[derive(Debug, Clone)]
13pub struct ActorInfo {
14    pub plugin_id: PluginId,
15    pub session_id: String,
16    pub namespace: String,
17    pub tenant: String,
18}
19
20#[derive(Debug)]
21pub struct ActorRegistry {
22    actors: HashMap<String, ActorInfo>,
23    next_id: AtomicU64,
24}
25
26impl ActorRegistry {
27    pub fn new() -> Self {
28        Self {
29            actors: HashMap::new(),
30            next_id: AtomicU64::new(1),
31        }
32    }
33
34    pub fn register(&mut self, session_id: String, namespace: String, tenant: String) -> ActorInfo {
35        let plugin_id = self.next_id.fetch_add(1, Ordering::Relaxed) as u128;
36        let info = ActorInfo {
37            plugin_id,
38            session_id: session_id.clone(),
39            namespace,
40            tenant,
41        };
42        self.actors.insert(session_id, info.clone());
43        info
44    }
45
46    pub fn get(&self, session_id: &str) -> Option<&ActorInfo> {
47        self.actors.get(session_id)
48    }
49
50    pub fn remove(&mut self, session_id: &str) -> Option<ActorInfo> {
51        self.actors.remove(session_id)
52    }
53
54    pub fn active_count(&self) -> usize {
55        self.actors.len()
56    }
57}
58
59impl Default for ActorRegistry {
60    fn default() -> Self {
61        Self::new()
62    }
63}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68
69    #[test]
70    fn register_and_lookup() {
71        let mut reg = ActorRegistry::new();
72        let info = reg.register("sess-abc".into(), "team:docs".into(), "tenant-a".into());
73        assert_eq!(info.plugin_id, 1);
74        assert_eq!(reg.get("sess-abc").unwrap().namespace, "team:docs");
75    }
76
77    #[test]
78    fn sequential_ids() {
79        let mut reg = ActorRegistry::new();
80        let a = reg.register("s1".into(), "ns1".into(), "t1".into());
81        let b = reg.register("s2".into(), "ns2".into(), "t1".into());
82        assert_eq!(a.plugin_id, 1);
83        assert_eq!(b.plugin_id, 2);
84    }
85
86    #[test]
87    fn remove_actor() {
88        let mut reg = ActorRegistry::new();
89        reg.register("sess-abc".into(), "team:docs".into(), "t".into());
90        assert_eq!(reg.active_count(), 1);
91        reg.remove("sess-abc");
92        assert_eq!(reg.active_count(), 0);
93        assert!(reg.get("sess-abc").is_none());
94    }
95}