Skip to main content

byteflow/scheduler/
registry.rs

1//! Named registry: `name → CapId` (address), never `name → FlowId`.
2//!
3//! Host `whereis` returns the **stored** Cap (the token passed to
4//! `register_name`). Bytecode `Whereis` remints a SEND Cap for the
5//! *caller* (`CapTable::mint_or_reuse`) so knowing a name is not an
6//! ambient grant of the registered token.
7//!
8//! Entries are swept when the **target** flow exits ([`Registry::unregister_flow`]).
9//! A revoked Cap cannot be registered; lookup after exit returns `None`.
10
11use std::collections::HashMap;
12
13use super::error::{LifecycleError, RuntimeError};
14use super::process::FlowId;
15use super::sync_lock;
16use crate::bytecode::CapId;
17
18/// Registry key. Interned as `Box<str>` so lookups do not allocate a `String`
19/// on the happy path when the caller already has a `&str`.
20#[derive(Debug, Clone, PartialEq, Eq, Hash)]
21pub struct RegistryName(Box<str>);
22
23impl RegistryName {
24    pub fn new(name: impl Into<Box<str>>) -> Self {
25        Self(name.into())
26    }
27
28    pub fn as_str(&self) -> &str {
29        &self.0
30    }
31}
32
33impl From<&str> for RegistryName {
34    fn from(name: &str) -> Self {
35        Self(name.into())
36    }
37}
38
39struct Entry {
40    cap: CapId,
41    flow: FlowId,
42}
43
44pub struct Registry {
45    by_name: HashMap<RegistryName, Entry>,
46    by_flow: HashMap<FlowId, Vec<RegistryName>>,
47}
48
49impl Registry {
50    pub fn new() -> Self {
51        Self {
52            by_name: HashMap::new(),
53            by_flow: HashMap::new(),
54        }
55    }
56
57    pub fn register(
58        &mut self,
59        name: RegistryName,
60        cap: CapId,
61        flow: FlowId,
62    ) -> Result<(), LifecycleError> {
63        if name.as_str().is_empty() {
64            return Err(LifecycleError::EmptyName);
65        }
66        if self.by_name.contains_key(&name) {
67            return Err(LifecycleError::AlreadyRegistered);
68        }
69        self.by_flow.entry(flow).or_default().push(name.clone());
70        self.by_name.insert(name, Entry { cap, flow });
71        Ok(())
72    }
73
74    #[inline]
75    pub fn len(&self) -> usize {
76        self.by_name.len()
77    }
78
79    pub fn whereis(&self, name: &str) -> Option<CapId> {
80        self.by_name.get(&RegistryName::from(name)).map(|e| e.cap)
81    }
82
83    pub fn target(&self, name: &str) -> Option<FlowId> {
84        self.by_name.get(&RegistryName::from(name)).map(|e| e.flow)
85    }
86
87    pub fn unregister(&mut self, name: &str) -> bool {
88        let key = RegistryName::from(name);
89        match self.by_name.remove(&key) {
90            Some(entry) => {
91                if let Some(names) = self.by_flow.get_mut(&entry.flow) {
92                    names.retain(|n| n != &key);
93                    if names.is_empty() {
94                        self.by_flow.remove(&entry.flow);
95                    }
96                }
97                true
98            }
99            None => false,
100        }
101    }
102
103    /// Drop every name that pointed at `flow` (called from finalize).
104    pub fn unregister_flow(&mut self, flow: FlowId) {
105        if let Some(names) = self.by_flow.remove(&flow) {
106            for name in names {
107                self.by_name.remove(&name);
108            }
109        }
110    }
111}
112
113impl Default for Registry {
114    fn default() -> Self {
115        Self::new()
116    }
117}
118
119pub struct RegistryStore {
120    inner: std::sync::Mutex<Registry>,
121    max_names: u32,
122}
123
124impl RegistryStore {
125    /// `max_registry_names == 0` → unlimited.
126    pub fn new(max_registry_names: u32) -> Self {
127        Self {
128            inner: std::sync::Mutex::new(Registry::new()),
129            max_names: max_registry_names,
130        }
131    }
132
133    pub fn register(
134        &self,
135        name: RegistryName,
136        cap: CapId,
137        flow: FlowId,
138    ) -> Result<Result<(), LifecycleError>, RuntimeError> {
139        let mut table = sync_lock::lock(&self.inner, "RegistryStore::register")?;
140        if name.as_str().is_empty() {
141            return Ok(Err(LifecycleError::EmptyName));
142        }
143        if table.by_name.contains_key(&name) {
144            return Ok(Err(LifecycleError::AlreadyRegistered));
145        }
146        if self.max_names != 0 && table.len() as u32 >= self.max_names {
147            return Ok(Err(LifecycleError::RegistryLimitReached {
148                limit: self.max_names,
149            }));
150        }
151        Ok(table.register(name, cap, flow))
152    }
153
154    pub fn whereis(&self, name: &str) -> Result<Option<CapId>, RuntimeError> {
155        Ok(sync_lock::lock(&self.inner, "RegistryStore::whereis")?.whereis(name))
156    }
157
158    pub fn target(&self, name: &str) -> Result<Option<FlowId>, RuntimeError> {
159        Ok(sync_lock::lock(&self.inner, "RegistryStore::target")?.target(name))
160    }
161
162    pub fn unregister(&self, name: &str) -> Result<bool, RuntimeError> {
163        Ok(sync_lock::lock(&self.inner, "RegistryStore::unregister")?.unregister(name))
164    }
165
166    pub fn unregister_flow(&self, flow: FlowId) -> Result<(), RuntimeError> {
167        sync_lock::lock(&self.inner, "RegistryStore::unregister_flow")?.unregister_flow(flow);
168        Ok(())
169    }
170}
171
172impl Default for RegistryStore {
173    fn default() -> Self {
174        Self::new(0)
175    }
176}
177
178#[cfg(test)]
179mod tests {
180    use super::*;
181    use crate::bytecode::CapId;
182    use crate::scheduler::process::next_flow_id;
183
184    #[test]
185    fn unregister_flow_clears_names() {
186        let mut reg = Registry::new();
187        let flow = next_flow_id();
188        let cap = CapId::from_raw(42);
189        assert!(reg.register(RegistryName::from("svc"), cap, flow).is_ok());
190        assert_eq!(reg.whereis("svc"), Some(cap));
191        reg.unregister_flow(flow);
192        assert_eq!(reg.whereis("svc"), None);
193    }
194
195    #[test]
196    fn duplicate_name_is_rejected() {
197        let mut reg = Registry::new();
198        let flow = next_flow_id();
199        assert!(reg
200            .register(RegistryName::from("svc"), CapId::from_raw(1), flow)
201            .is_ok());
202        assert_eq!(
203            reg.register(RegistryName::from("svc"), CapId::from_raw(2), flow),
204            Err(LifecycleError::AlreadyRegistered)
205        );
206    }
207
208    #[test]
209    fn empty_name_is_rejected() {
210        let mut reg = Registry::new();
211        let flow = next_flow_id();
212        assert_eq!(
213            reg.register(RegistryName::from(""), CapId::from_raw(1), flow),
214            Err(LifecycleError::EmptyName)
215        );
216    }
217
218    #[test]
219    fn registry_limit_distinct_from_already_registered() -> Result<(), Box<dyn std::error::Error>> {
220        let store = RegistryStore::new(1);
221        let a = next_flow_id();
222        let b = next_flow_id();
223        store.register(RegistryName::from("a"), CapId::from_raw(1), a)??;
224        let dup = store.register(RegistryName::from("a"), CapId::from_raw(2), b)?;
225        assert!(matches!(dup, Err(LifecycleError::AlreadyRegistered)));
226        let limited = store.register(RegistryName::from("b"), CapId::from_raw(3), b)?;
227        assert!(matches!(
228            limited,
229            Err(LifecycleError::RegistryLimitReached { limit: 1 })
230        ));
231        store.unregister("a")?;
232        store.register(RegistryName::from("b"), CapId::from_raw(3), b)??;
233        Ok(())
234    }
235}