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
9// Docs ratchet: public items here predate `missing_docs`. Delete this
10// allow once they are documented; new files get the lint by default.
11#![allow(missing_docs)]
12
13use std::collections::HashMap;
14use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
15
16use super::error::{LifecycleError, RuntimeError};
17use super::process::FlowId;
18use super::sync_lock;
19
20/// Opaque link identifier returned by `LinkTable::link`.
21///
22/// Inner id is runtime-minted (`pub(crate)`), same rule as [`crate::CapId`].
23/// Values fit in `i64` so bytecode can store them as [`crate::Value::Int`].
24/// `0` is never minted. Bytecode writes `0` when finalize already consumed
25/// the row, and `Unlink` of that sentinel does nothing.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
27pub struct LinkId(pub(crate) u64);
28
29/// Bytecode sentinel: the peer exited while the link was being armed and
30/// finalize already propagated that exit. Not a row in [`LinkTable`].
31pub(super) const CONSUMED_LINK_ID: u64 = 0;
32
33/// Bytecode stores [`LinkId`] as [`crate::Value::Int`]; never mint past this.
34const MAX_LINK_ID: u64 = i64::MAX as u64;
35
36static NEXT_LINK: AtomicU64 = AtomicU64::new(1);
37static LINK_IDS_EXHAUSTED: AtomicBool = AtomicBool::new(false);
38
39impl LinkId {
40    #[inline]
41    pub fn as_u64(self) -> u64 {
42        self.0
43    }
44
45    #[inline]
46    pub(crate) fn from_u64(raw: u64) -> Self {
47        Self(raw)
48    }
49}
50
51impl std::fmt::Display for LinkId {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        write!(f, "link#{}", self.0)
54    }
55}
56
57fn try_next_link_id() -> Result<LinkId, RuntimeError> {
58    if LINK_IDS_EXHAUSTED.load(Ordering::Relaxed) {
59        return Err(RuntimeError::LinkIdExhausted);
60    }
61    let id = NEXT_LINK.fetch_add(1, Ordering::Relaxed);
62    if id == 0 || id > MAX_LINK_ID {
63        LINK_IDS_EXHAUSTED.store(true, Ordering::Relaxed);
64        return Err(RuntimeError::LinkIdExhausted);
65    }
66    Ok(LinkId(id))
67}
68
69#[derive(Debug, Clone, Copy)]
70struct Link {
71    a: FlowId,
72    b: FlowId,
73}
74
75/// Bidirectional flow links. Lives on [`super::runtime::Shared`].
76///
77/// Three maps stay in lockstep: `links` is the record, `pairs` is the
78/// uniqueness index (canonical `(min, max)`), `by_flow` is adjacency so
79/// finalize is O(degree) instead of a full-table scan.
80pub(super) struct LinkTable {
81    links: HashMap<LinkId, Link>,
82    pairs: HashMap<(FlowId, FlowId), LinkId>,
83    by_flow: HashMap<FlowId, Vec<LinkId>>,
84}
85
86impl LinkTable {
87    pub(super) fn new() -> Self {
88        Self {
89            links: HashMap::new(),
90            pairs: HashMap::new(),
91            by_flow: HashMap::new(),
92        }
93    }
94
95    #[inline]
96    pub(super) fn len(&self) -> usize {
97        self.links.len()
98    }
99
100    #[inline]
101    fn pair_key(a: FlowId, b: FlowId) -> (FlowId, FlowId) {
102        if a <= b {
103            (a, b)
104        } else {
105            (b, a)
106        }
107    }
108
109    #[inline]
110    pub(super) fn has_pair(&self, a: FlowId, b: FlowId) -> bool {
111        a != b && self.pairs.contains_key(&Self::pair_key(a, b))
112    }
113
114    fn drop_index(&mut self, flow: FlowId, id: LinkId) {
115        if let Some(ids) = self.by_flow.get_mut(&flow) {
116            ids.retain(|existing| *existing != id);
117            if ids.is_empty() {
118                self.by_flow.remove(&flow);
119            }
120        }
121    }
122
123    fn index_flow(&mut self, flow: FlowId, id: LinkId) {
124        self.by_flow.entry(flow).or_default().push(id);
125    }
126
127    /// Caller already checked self / duplicate. `id` must be unique.
128    fn insert(&mut self, id: LinkId, a: FlowId, b: FlowId) {
129        self.links.insert(id, Link { a, b });
130        self.pairs.insert(Self::pair_key(a, b), id);
131        self.index_flow(a, id);
132        self.index_flow(b, id);
133    }
134
135    /// Drop `id` from every index. `None` if it was already gone.
136    fn unlink_id(&mut self, id: LinkId) -> Option<Link> {
137        let link = self.links.remove(&id)?;
138        self.pairs.remove(&Self::pair_key(link.a, link.b));
139        self.drop_index(link.a, id);
140        self.drop_index(link.b, id);
141        Some(link)
142    }
143
144    #[cfg(test)]
145    pub(crate) fn link(&mut self, a: FlowId, b: FlowId) -> Result<LinkId, LifecycleError> {
146        if a == b {
147            return Err(LifecycleError::SelfRelation);
148        }
149        if self.has_pair(a, b) {
150            return Err(LifecycleError::AlreadyLinked);
151        }
152        let id = match try_next_link_id() {
153            Ok(id) => id,
154            Err(_) => return Err(LifecycleError::Unavailable),
155        };
156        self.insert(id, a, b);
157        Ok(id)
158    }
159
160    pub(super) fn unlink_owned(&mut self, owner: FlowId, id: LinkId) -> Result<(), LifecycleError> {
161        match self.links.get(&id) {
162            Some(link) if link.a == owner || link.b == owner => {
163                let _ = self.unlink_id(id);
164                Ok(())
165            }
166            Some(_) => Err(LifecycleError::NotOwner),
167            None => Err(LifecycleError::InvalidLink),
168        }
169    }
170
171    /// Peers of `target` and the link ids, then drop those links.
172    ///
173    /// Order is by [`LinkId`] so finalize propagation is deterministic
174    /// (same discipline as [`super::monitor::MonitorTable::notify_target_exit`]).
175    pub(super) fn remove_links_of(&mut self, target: FlowId) -> Vec<(LinkId, FlowId)> {
176        let Some(ids) = self.by_flow.remove(&target) else {
177            return Vec::new();
178        };
179        let mut result = Vec::with_capacity(ids.len());
180        for id in ids {
181            let Some(link) = self.links.remove(&id) else {
182                continue;
183            };
184            self.pairs.remove(&Self::pair_key(link.a, link.b));
185            let peer = if link.a == target { link.b } else { link.a };
186            self.drop_index(peer, id);
187            result.push((id, peer));
188        }
189        result.sort_unstable_by_key(|(id, _)| id.0);
190        result
191    }
192}
193
194impl Default for LinkTable {
195    fn default() -> Self {
196        Self::new()
197    }
198}
199
200/// What [`LinkStore::link_if_live`] observed after the insert.
201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
202pub(crate) enum LinkOutcome {
203    /// Both endpoints were live and the row is still in the table.
204    Linked(LinkId),
205    /// Finalize already removed the row and propagated the exit. The id
206    /// must not be published: a later unlink would fail the survivor.
207    Consumed { dead: FlowId },
208}
209
210/// Fail-closed wrapper; process-wide link quota lives here (`table.len()`).
211pub(crate) struct LinkStore {
212    inner: std::sync::Mutex<LinkTable>,
213    max_links: u32,
214}
215
216impl LinkStore {
217    /// `max_links == 0` → unlimited.
218    pub(crate) fn new(max_links: u32) -> Self {
219        Self {
220            inner: std::sync::Mutex::new(LinkTable::new()),
221            max_links,
222        }
223    }
224
225    /// Insert without a liveness check (unit tests).
226    #[cfg(test)]
227    pub(crate) fn link(
228        &self,
229        a: FlowId,
230        b: FlowId,
231    ) -> Result<Result<LinkId, LifecycleError>, RuntimeError> {
232        match self.link_if_live(a, b, |_| Ok(true))? {
233            Ok(LinkOutcome::Linked(id)) => Ok(Ok(id)),
234            Ok(LinkOutcome::Consumed { dead }) => Ok(Err(LifecycleError::NoSuchFlow(dead))),
235            Err(error) => Ok(Err(error)),
236        }
237    }
238
239    /// Insert, then confirm both endpoints are still live.
240    ///
241    /// `is_live` runs **after** the link mutex is released so this never
242    /// nests `LinkStore` → `Directory` (finalize takes those locks separately,
243    /// never together). If a peer finalized in the window:
244    ///
245    /// - the link is still here → rollback and [`LifecycleError::NoSuchFlow`]
246    ///   (zombie we created after `remove_links_of`)
247    /// - the link is already gone → [`LinkOutcome::Consumed`]. Finalize
248    ///   delivered the exit; the caller must not fail the survivor again
249    ///   and must not hand out the removed id.
250    pub(crate) fn link_if_live<F>(
251        &self,
252        a: FlowId,
253        b: FlowId,
254        is_live: F,
255    ) -> Result<Result<LinkOutcome, LifecycleError>, RuntimeError>
256    where
257        F: Fn(FlowId) -> Result<bool, RuntimeError>,
258    {
259        let id = {
260            let mut table = sync_lock::lock(&self.inner, "LinkStore::link")?;
261            // Validate before the quota check so LimitReached never masks
262            // SelfRelation / AlreadyLinked (same discipline as registry).
263            if a == b {
264                return Ok(Err(LifecycleError::SelfRelation));
265            }
266            if table.has_pair(a, b) {
267                return Ok(Err(LifecycleError::AlreadyLinked));
268            }
269            if self.max_links != 0 && table.len() >= self.max_links as usize {
270                return Ok(Err(LifecycleError::LinkLimitReached {
271                    limit: self.max_links,
272                }));
273            }
274            let id = try_next_link_id()?;
275            table.insert(id, a, b);
276            id
277        };
278        self.confirm_live(id, a, b, is_live)
279    }
280
281    fn confirm_live<F>(
282        &self,
283        id: LinkId,
284        a: FlowId,
285        b: FlowId,
286        is_live: F,
287    ) -> Result<Result<LinkOutcome, LifecycleError>, RuntimeError>
288    where
289        F: Fn(FlowId) -> Result<bool, RuntimeError>,
290    {
291        let a_live = match is_live(a) {
292            Ok(v) => v,
293            Err(e) => {
294                let _ = self.force_remove(id);
295                return Err(e);
296            }
297        };
298        let b_live = match is_live(b) {
299            Ok(v) => v,
300            Err(e) => {
301                let _ = self.force_remove(id);
302                return Err(e);
303            }
304        };
305        if a_live && b_live {
306            return Ok(Ok(LinkOutcome::Linked(id)));
307        }
308        let dead = if a_live { b } else { a };
309        match self.force_remove(id) {
310            Ok(true) => Ok(Err(LifecycleError::NoSuchFlow(dead))),
311            Ok(false) => Ok(Ok(LinkOutcome::Consumed { dead })),
312            Err(e) => Err(e),
313        }
314    }
315
316    fn force_remove(&self, id: LinkId) -> Result<bool, RuntimeError> {
317        Ok(sync_lock::lock(&self.inner, "LinkStore::confirm_live")?
318            .unlink_id(id)
319            .is_some())
320    }
321
322    pub(crate) fn unlink_owned(
323        &self,
324        owner: FlowId,
325        id: LinkId,
326    ) -> Result<Result<(), LifecycleError>, RuntimeError> {
327        Ok(sync_lock::lock(&self.inner, "LinkStore::unlink_owned")?.unlink_owned(owner, id))
328    }
329
330    pub(crate) fn remove_links_of(
331        &self,
332        target: FlowId,
333    ) -> Result<Vec<(LinkId, FlowId)>, RuntimeError> {
334        Ok(sync_lock::lock(&self.inner, "LinkStore::remove_links_of")?.remove_links_of(target))
335    }
336}
337
338impl Default for LinkStore {
339    fn default() -> Self {
340        Self::new(0)
341    }
342}
343
344#[cfg(test)]
345mod tests {
346    use super::*;
347    use crate::scheduler::process::next_flow_id;
348
349    #[test]
350    fn remove_links_returns_both_directions() -> Result<(), String> {
351        let mut table = LinkTable::new();
352        let a = next_flow_id();
353        let b = next_flow_id();
354        let c = next_flow_id();
355        table.link(a, b).map_err(|e| e.to_string())?;
356        table.link(c, a).map_err(|e| e.to_string())?;
357        let removed = table.remove_links_of(a);
358        let peers: Vec<FlowId> = removed.iter().map(|(_, p)| *p).collect();
359        assert_eq!(peers.len(), 2);
360        assert!(peers.contains(&b));
361        assert!(peers.contains(&c));
362        assert!(removed[0].0 < removed[1].0);
363        assert!(table.remove_links_of(a).is_empty());
364        assert!(table.remove_links_of(b).is_empty());
365        assert!(table.remove_links_of(c).is_empty());
366        assert_eq!(table.len(), 0);
367        Ok(())
368    }
369
370    #[test]
371    fn rejects_self_and_duplicate() {
372        let mut table = LinkTable::new();
373        let a = next_flow_id();
374        let b = next_flow_id();
375        assert_eq!(table.link(a, a), Err(LifecycleError::SelfRelation));
376        assert!(table.link(a, b).is_ok());
377        assert_eq!(table.link(b, a), Err(LifecycleError::AlreadyLinked));
378        assert!(table.has_pair(a, b));
379        assert!(table.has_pair(b, a));
380    }
381
382    #[test]
383    fn unlink_owned_rejects_stranger_and_unknown() -> Result<(), String> {
384        let mut table = LinkTable::new();
385        let a = next_flow_id();
386        let b = next_flow_id();
387        let stranger = next_flow_id();
388        let id = table.link(a, b).map_err(|e| e.to_string())?;
389        assert_eq!(
390            table.unlink_owned(stranger, id),
391            Err(LifecycleError::NotOwner)
392        );
393        assert_eq!(
394            table.unlink_owned(a, LinkId::from_u64(0)),
395            Err(LifecycleError::InvalidLink)
396        );
397        table.unlink_owned(b, id).map_err(|e| e.to_string())?;
398        assert_eq!(table.unlink_owned(a, id), Err(LifecycleError::InvalidLink));
399        assert_eq!(table.len(), 0);
400        assert!(!table.has_pair(a, b));
401        Ok(())
402    }
403
404    #[test]
405    fn unlink_after_remove_is_invalid() -> Result<(), String> {
406        let mut table = LinkTable::new();
407        let a = next_flow_id();
408        let b = next_flow_id();
409        let id = table.link(a, b).map_err(|e| e.to_string())?;
410        assert_eq!(table.remove_links_of(a), vec![(id, b)]);
411        assert_eq!(table.unlink_owned(b, id), Err(LifecycleError::InvalidLink));
412        Ok(())
413    }
414
415    #[test]
416    fn link_limit_is_process_wide_and_released() -> Result<(), Box<dyn std::error::Error>> {
417        let store = LinkStore::new(1);
418        let a = next_flow_id();
419        let b = next_flow_id();
420        let c = next_flow_id();
421        let first = store.link(a, b)??;
422        let second = store.link(b, c)?;
423        assert!(matches!(
424            second,
425            Err(LifecycleError::LinkLimitReached { limit: 1 })
426        ));
427        store.unlink_owned(a, first)??;
428        store.link(b, c)??;
429        Ok(())
430    }
431
432    #[test]
433    fn link_limit_does_not_mask_self_or_duplicate() -> Result<(), Box<dyn std::error::Error>> {
434        let store = LinkStore::new(1);
435        let a = next_flow_id();
436        let b = next_flow_id();
437        store.link(a, b)??;
438        // At capacity: self / duplicate must still win over LimitReached.
439        let self_err = store.link(a, a)?;
440        assert!(matches!(self_err, Err(LifecycleError::SelfRelation)));
441        let dup = store.link(b, a)?;
442        assert!(matches!(dup, Err(LifecycleError::AlreadyLinked)));
443        let other = store.link(a, next_flow_id())?;
444        assert!(matches!(
445            other,
446            Err(LifecycleError::LinkLimitReached { limit: 1 })
447        ));
448        Ok(())
449    }
450
451    #[test]
452    fn unlimited_store_accepts_many() -> Result<(), Box<dyn std::error::Error>> {
453        let store = LinkStore::new(0);
454        let a = next_flow_id();
455        store.link(a, next_flow_id())??;
456        store.link(a, next_flow_id())??;
457        store.link(a, next_flow_id())??;
458        Ok(())
459    }
460
461    #[test]
462    fn dead_peer_rolls_back_and_releases_quota() -> Result<(), Box<dyn std::error::Error>> {
463        let store = LinkStore::new(1);
464        let a = next_flow_id();
465        let b = next_flow_id();
466        let result = store.link_if_live(a, b, |id| Ok(id != b))?;
467        assert!(matches!(result, Err(LifecycleError::NoSuchFlow(dead)) if dead == b));
468        // Quota released: a fresh pair must fit.
469        store.link_if_live(a, next_flow_id(), |_| Ok(true))??;
470        Ok(())
471    }
472
473    #[test]
474    fn finalize_already_removed_is_not_a_second_fault() -> Result<(), Box<dyn std::error::Error>> {
475        let store = LinkStore::new(0);
476        let a = next_flow_id();
477        let b = next_flow_id();
478        // Insert as live, tear down as finalize would, then confirm sees a
479        // dead peer and a missing row. The removed id is not returned.
480        let id = {
481            let mut table = sync_lock::lock(&store.inner, "test")?;
482            if table.has_pair(a, b) {
483                return Err("pair should be free".into());
484            }
485            let id = try_next_link_id()?;
486            table.insert(id, a, b);
487            id
488        };
489        let _ = store.remove_links_of(b)?;
490        let confirmed = store.confirm_live(id, a, b, |id| Ok(id != b))?;
491        assert_eq!(confirmed, Ok(LinkOutcome::Consumed { dead: b }));
492        Ok(())
493    }
494}