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    pub fn link(&mut self, a: FlowId, b: FlowId) -> Result<LinkId, LifecycleError> {
61        if a == b {
62            return Err(LifecycleError::SelfRelation);
63        }
64        if self
65            .links
66            .values()
67            .any(|link| (link.a == a && link.b == b) || (link.a == b && link.b == a))
68        {
69            return Err(LifecycleError::AlreadyLinked);
70        }
71        let id = LinkId(NEXT_LINK.fetch_add(1, Ordering::Relaxed));
72        self.links.insert(id, Link { a, b });
73        Ok(id)
74    }
75
76    pub fn unlink_owned(&mut self, owner: FlowId, id: LinkId) -> Result<(), LifecycleError> {
77        match self.links.get(&id) {
78            Some(link) if link.a == owner || link.b == owner => {
79                self.links.remove(&id);
80                Ok(())
81            }
82            Some(_) => Err(LifecycleError::NotOwner),
83            None => Err(LifecycleError::InvalidLink),
84        }
85    }
86
87    /// Peers of `target` and the link ids, then drop those links.
88    pub fn remove_links_of(&mut self, target: FlowId) -> Vec<(LinkId, FlowId)> {
89        let mut result = Vec::new();
90        self.links.retain(|id, link| {
91            if link.a == target {
92                result.push((*id, link.b));
93                false
94            } else if link.b == target {
95                result.push((*id, link.a));
96                false
97            } else {
98                true
99            }
100        });
101        result
102    }
103}
104
105impl Default for LinkTable {
106    fn default() -> Self {
107        Self::new()
108    }
109}
110
111pub struct LinkStore {
112    inner: std::sync::Mutex<LinkTable>,
113}
114
115impl LinkStore {
116    pub fn new() -> Self {
117        Self {
118            inner: std::sync::Mutex::new(LinkTable::new()),
119        }
120    }
121
122    pub fn link(
123        &self,
124        a: FlowId,
125        b: FlowId,
126    ) -> Result<Result<LinkId, LifecycleError>, RuntimeError> {
127        Ok(sync_lock::lock(&self.inner, "LinkStore::link")?.link(a, b))
128    }
129
130    pub fn unlink_owned(
131        &self,
132        owner: FlowId,
133        id: LinkId,
134    ) -> Result<Result<(), LifecycleError>, RuntimeError> {
135        Ok(sync_lock::lock(&self.inner, "LinkStore::unlink_owned")?.unlink_owned(owner, id))
136    }
137
138    pub fn remove_links_of(&self, target: FlowId) -> Result<Vec<(LinkId, FlowId)>, RuntimeError> {
139        Ok(sync_lock::lock(&self.inner, "LinkStore::remove_links_of")?.remove_links_of(target))
140    }
141}
142
143impl Default for LinkStore {
144    fn default() -> Self {
145        Self::new()
146    }
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152    use crate::scheduler::process::next_flow_id;
153
154    #[test]
155    fn remove_links_returns_both_directions() -> Result<(), String> {
156        let mut table = LinkTable::new();
157        let a = next_flow_id();
158        let b = next_flow_id();
159        let c = next_flow_id();
160        table.link(a, b).map_err(|e| e.to_string())?;
161        table.link(c, a).map_err(|e| e.to_string())?;
162        let peers: Vec<FlowId> = table
163            .remove_links_of(a)
164            .into_iter()
165            .map(|(_, p)| p)
166            .collect();
167        assert_eq!(peers.len(), 2);
168        assert!(peers.contains(&b));
169        assert!(peers.contains(&c));
170        assert!(table.remove_links_of(a).is_empty());
171        Ok(())
172    }
173
174    #[test]
175    fn rejects_self_and_duplicate() {
176        let mut table = LinkTable::new();
177        let a = next_flow_id();
178        let b = next_flow_id();
179        assert_eq!(table.link(a, a), Err(LifecycleError::SelfRelation));
180        assert!(table.link(a, b).is_ok());
181        assert_eq!(table.link(b, a), Err(LifecycleError::AlreadyLinked));
182    }
183}