Skip to main content

byteflow/scheduler/
link.rs

1//! Bidirectional links (`A <──────────> B`).
2//!
3//! Distinct from monitors: a monitor delivers `DOWN` to the owner; a link
4//! **propagates abnormal exit** to the peer (BEAM: `normal` does not kill)
5//! unless the peer has `trap_exit` enabled — then every exit becomes a
6//! [`crate::TAG_SYS_EXIT`] hop. Propagation is cooperative — see
7//! [`super::finalize`].
8
9use std::collections::HashMap;
10use std::sync::atomic::{AtomicU64, Ordering};
11
12use super::error::{LifecycleError, RuntimeError};
13use super::process::FlowId;
14use super::sync_lock;
15
16/// Opaque link identifier returned by [`LinkTable::link`].
17///
18/// Inner id is runtime-minted (`pub(crate)`), same rule as [`crate::CapId`].
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20pub struct LinkId(pub(crate) u64);
21
22static NEXT_LINK: AtomicU64 = AtomicU64::new(1);
23
24impl LinkId {
25    #[inline]
26    pub fn as_u64(self) -> u64 {
27        self.0
28    }
29
30    #[inline]
31    pub(crate) fn from_u64(raw: u64) -> Self {
32        Self(raw)
33    }
34}
35
36impl std::fmt::Display for LinkId {
37    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38        write!(f, "link#{}", self.0)
39    }
40}
41
42#[derive(Debug, Clone, Copy)]
43struct Link {
44    a: FlowId,
45    b: FlowId,
46}
47
48/// Bidirectional flow links. Lives on [`super::runtime::Shared`].
49pub struct LinkTable {
50    links: HashMap<LinkId, Link>,
51}
52
53impl LinkTable {
54    pub fn new() -> Self {
55        Self {
56            links: HashMap::new(),
57        }
58    }
59
60    #[inline]
61    pub fn len(&self) -> usize {
62        self.links.len()
63    }
64
65    pub fn link(&mut self, a: FlowId, b: FlowId) -> Result<LinkId, LifecycleError> {
66        if a == b {
67            return Err(LifecycleError::SelfRelation);
68        }
69        if self
70            .links
71            .values()
72            .any(|link| (link.a == a && link.b == b) || (link.a == b && link.b == a))
73        {
74            return Err(LifecycleError::AlreadyLinked);
75        }
76        let id = LinkId(NEXT_LINK.fetch_add(1, Ordering::Relaxed));
77        self.links.insert(id, Link { a, b });
78        Ok(id)
79    }
80
81    pub fn unlink_owned(&mut self, owner: FlowId, id: LinkId) -> Result<(), LifecycleError> {
82        match self.links.get(&id) {
83            Some(link) if link.a == owner || link.b == owner => {
84                self.links.remove(&id);
85                Ok(())
86            }
87            Some(_) => Err(LifecycleError::NotOwner),
88            None => Err(LifecycleError::InvalidLink),
89        }
90    }
91
92    /// Peers of `target` and the link ids, then drop those links.
93    pub fn remove_links_of(&mut self, target: FlowId) -> Vec<(LinkId, FlowId)> {
94        let mut result = Vec::new();
95        self.links.retain(|id, link| {
96            if link.a == target {
97                result.push((*id, link.b));
98                false
99            } else if link.b == target {
100                result.push((*id, link.a));
101                false
102            } else {
103                true
104            }
105        });
106        result
107    }
108}
109
110impl Default for LinkTable {
111    fn default() -> Self {
112        Self::new()
113    }
114}
115
116/// Fail-closed wrapper; process-wide link quota lives here (`table.len()`).
117pub struct LinkStore {
118    inner: std::sync::Mutex<LinkTable>,
119    max_links: u32,
120}
121
122impl LinkStore {
123    /// `max_links == 0` → unlimited.
124    pub fn new(max_links: u32) -> Self {
125        Self {
126            inner: std::sync::Mutex::new(LinkTable::new()),
127            max_links,
128        }
129    }
130
131    pub fn link(
132        &self,
133        a: FlowId,
134        b: FlowId,
135    ) -> Result<Result<LinkId, LifecycleError>, RuntimeError> {
136        let mut table = sync_lock::lock(&self.inner, "LinkStore::link")?;
137        // Validate before the quota check so LimitReached never masks
138        // SelfRelation / AlreadyLinked (same discipline as registry).
139        if a == b {
140            return Ok(Err(LifecycleError::SelfRelation));
141        }
142        if table
143            .links
144            .values()
145            .any(|link| (link.a == a && link.b == b) || (link.a == b && link.b == a))
146        {
147            return Ok(Err(LifecycleError::AlreadyLinked));
148        }
149        if self.max_links != 0 && table.len() as u32 >= self.max_links {
150            return Ok(Err(LifecycleError::LinkLimitReached {
151                limit: self.max_links,
152            }));
153        }
154        Ok(table.link(a, b))
155    }
156
157    pub fn unlink_owned(
158        &self,
159        owner: FlowId,
160        id: LinkId,
161    ) -> Result<Result<(), LifecycleError>, RuntimeError> {
162        Ok(sync_lock::lock(&self.inner, "LinkStore::unlink_owned")?.unlink_owned(owner, id))
163    }
164
165    pub fn remove_links_of(&self, target: FlowId) -> Result<Vec<(LinkId, FlowId)>, RuntimeError> {
166        Ok(sync_lock::lock(&self.inner, "LinkStore::remove_links_of")?.remove_links_of(target))
167    }
168}
169
170impl Default for LinkStore {
171    fn default() -> Self {
172        Self::new(0)
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179    use crate::scheduler::process::next_flow_id;
180
181    #[test]
182    fn remove_links_returns_both_directions() -> Result<(), String> {
183        let mut table = LinkTable::new();
184        let a = next_flow_id();
185        let b = next_flow_id();
186        let c = next_flow_id();
187        table.link(a, b).map_err(|e| e.to_string())?;
188        table.link(c, a).map_err(|e| e.to_string())?;
189        let peers: Vec<FlowId> = table
190            .remove_links_of(a)
191            .into_iter()
192            .map(|(_, p)| p)
193            .collect();
194        assert_eq!(peers.len(), 2);
195        assert!(peers.contains(&b));
196        assert!(peers.contains(&c));
197        assert!(table.remove_links_of(a).is_empty());
198        Ok(())
199    }
200
201    #[test]
202    fn rejects_self_and_duplicate() {
203        let mut table = LinkTable::new();
204        let a = next_flow_id();
205        let b = next_flow_id();
206        assert_eq!(table.link(a, a), Err(LifecycleError::SelfRelation));
207        assert!(table.link(a, b).is_ok());
208        assert_eq!(table.link(b, a), Err(LifecycleError::AlreadyLinked));
209    }
210
211    #[test]
212    fn link_limit_is_process_wide_and_released() -> Result<(), Box<dyn std::error::Error>> {
213        let store = LinkStore::new(1);
214        let a = next_flow_id();
215        let b = next_flow_id();
216        let c = next_flow_id();
217        let first = store.link(a, b)??;
218        let second = store.link(b, c)?;
219        assert!(matches!(
220            second,
221            Err(LifecycleError::LinkLimitReached { limit: 1 })
222        ));
223        store.unlink_owned(a, first)??;
224        store.link(b, c)??;
225        Ok(())
226    }
227
228    #[test]
229    fn link_limit_does_not_mask_self_or_duplicate() -> Result<(), Box<dyn std::error::Error>> {
230        let store = LinkStore::new(1);
231        let a = next_flow_id();
232        let b = next_flow_id();
233        store.link(a, b)??;
234        // At capacity: self / duplicate must still win over LimitReached.
235        let self_err = store.link(a, a)?;
236        assert!(matches!(self_err, Err(LifecycleError::SelfRelation)));
237        let dup = store.link(b, a)?;
238        assert!(matches!(dup, Err(LifecycleError::AlreadyLinked)));
239        let other = store.link(a, next_flow_id())?;
240        assert!(matches!(
241            other,
242            Err(LifecycleError::LinkLimitReached { limit: 1 })
243        ));
244        Ok(())
245    }
246}