byteflow-actors 0.9.28

Embeddable flow runtime: M:N scheduler, Atomic Hop (Message+Cap), supervisor — use byteflow::
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
//! Bidirectional links (`A <──────────> B`).
//!
//! Distinct from monitors: a monitor delivers `DOWN` to the owner; a link
//! **propagates abnormal exit** to the peer (BEAM: `normal` does not kill)
//! unless the peer has `trap_exit` enabled — then every exit becomes a
//! [`crate::TAG_SYS_EXIT`] hop. Propagation is cooperative — see
//! [`super::finalize`].

// Docs ratchet: public items here predate `missing_docs`. Delete this
// allow once they are documented; new files get the lint by default.
#![allow(missing_docs)]

use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};

use super::error::{LifecycleError, RuntimeError};
use super::process::FlowId;
use super::sync_lock;

/// Opaque link identifier returned by `LinkTable::link`.
///
/// Inner id is runtime-minted (`pub(crate)`), same rule as [`crate::CapId`].
/// Values fit in `i64` so bytecode can store them as [`crate::Value::Int`].
/// `0` is never minted. Bytecode writes `0` when finalize already consumed
/// the row, and `Unlink` of that sentinel does nothing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct LinkId(pub(crate) u64);

/// Bytecode sentinel: the peer exited while the link was being armed and
/// finalize already propagated that exit. Not a row in [`LinkTable`].
pub(super) const CONSUMED_LINK_ID: u64 = 0;

/// Bytecode stores [`LinkId`] as [`crate::Value::Int`]; never mint past this.
const MAX_LINK_ID: u64 = i64::MAX as u64;

static NEXT_LINK: AtomicU64 = AtomicU64::new(1);
static LINK_IDS_EXHAUSTED: AtomicBool = AtomicBool::new(false);

impl LinkId {
    #[inline]
    pub fn as_u64(self) -> u64 {
        self.0
    }

    #[inline]
    pub(crate) fn from_u64(raw: u64) -> Self {
        Self(raw)
    }
}

impl std::fmt::Display for LinkId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "link#{}", self.0)
    }
}

fn try_next_link_id() -> Result<LinkId, RuntimeError> {
    if LINK_IDS_EXHAUSTED.load(Ordering::Relaxed) {
        return Err(RuntimeError::LinkIdExhausted);
    }
    let id = NEXT_LINK.fetch_add(1, Ordering::Relaxed);
    if id == 0 || id > MAX_LINK_ID {
        LINK_IDS_EXHAUSTED.store(true, Ordering::Relaxed);
        return Err(RuntimeError::LinkIdExhausted);
    }
    Ok(LinkId(id))
}

#[derive(Debug, Clone, Copy)]
struct Link {
    a: FlowId,
    b: FlowId,
}

/// Bidirectional flow links. Lives on [`super::runtime::Shared`].
///
/// Three maps stay in lockstep: `links` is the record, `pairs` is the
/// uniqueness index (canonical `(min, max)`), `by_flow` is adjacency so
/// finalize is O(degree) instead of a full-table scan.
pub(super) struct LinkTable {
    links: HashMap<LinkId, Link>,
    pairs: HashMap<(FlowId, FlowId), LinkId>,
    by_flow: HashMap<FlowId, Vec<LinkId>>,
}

impl LinkTable {
    pub(super) fn new() -> Self {
        Self {
            links: HashMap::new(),
            pairs: HashMap::new(),
            by_flow: HashMap::new(),
        }
    }

    #[inline]
    pub(super) fn len(&self) -> usize {
        self.links.len()
    }

    #[inline]
    fn pair_key(a: FlowId, b: FlowId) -> (FlowId, FlowId) {
        if a <= b {
            (a, b)
        } else {
            (b, a)
        }
    }

    #[inline]
    pub(super) fn has_pair(&self, a: FlowId, b: FlowId) -> bool {
        a != b && self.pairs.contains_key(&Self::pair_key(a, b))
    }

    fn drop_index(&mut self, flow: FlowId, id: LinkId) {
        if let Some(ids) = self.by_flow.get_mut(&flow) {
            ids.retain(|existing| *existing != id);
            if ids.is_empty() {
                self.by_flow.remove(&flow);
            }
        }
    }

    fn index_flow(&mut self, flow: FlowId, id: LinkId) {
        self.by_flow.entry(flow).or_default().push(id);
    }

    /// Caller already checked self / duplicate. `id` must be unique.
    fn insert(&mut self, id: LinkId, a: FlowId, b: FlowId) {
        self.links.insert(id, Link { a, b });
        self.pairs.insert(Self::pair_key(a, b), id);
        self.index_flow(a, id);
        self.index_flow(b, id);
    }

    /// Drop `id` from every index. `None` if it was already gone.
    fn unlink_id(&mut self, id: LinkId) -> Option<Link> {
        let link = self.links.remove(&id)?;
        self.pairs.remove(&Self::pair_key(link.a, link.b));
        self.drop_index(link.a, id);
        self.drop_index(link.b, id);
        Some(link)
    }

    #[cfg(test)]
    pub(crate) fn link(&mut self, a: FlowId, b: FlowId) -> Result<LinkId, LifecycleError> {
        if a == b {
            return Err(LifecycleError::SelfRelation);
        }
        if self.has_pair(a, b) {
            return Err(LifecycleError::AlreadyLinked);
        }
        let id = match try_next_link_id() {
            Ok(id) => id,
            Err(_) => return Err(LifecycleError::Unavailable),
        };
        self.insert(id, a, b);
        Ok(id)
    }

    pub(super) fn unlink_owned(&mut self, owner: FlowId, id: LinkId) -> Result<(), LifecycleError> {
        match self.links.get(&id) {
            Some(link) if link.a == owner || link.b == owner => {
                let _ = self.unlink_id(id);
                Ok(())
            }
            Some(_) => Err(LifecycleError::NotOwner),
            None => Err(LifecycleError::InvalidLink),
        }
    }

    /// Peers of `target` and the link ids, then drop those links.
    ///
    /// Order is by [`LinkId`] so finalize propagation is deterministic
    /// (same discipline as [`super::monitor::MonitorTable::notify_target_exit`]).
    pub(super) fn remove_links_of(&mut self, target: FlowId) -> Vec<(LinkId, FlowId)> {
        let Some(ids) = self.by_flow.remove(&target) else {
            return Vec::new();
        };
        let mut result = Vec::with_capacity(ids.len());
        for id in ids {
            let Some(link) = self.links.remove(&id) else {
                continue;
            };
            self.pairs.remove(&Self::pair_key(link.a, link.b));
            let peer = if link.a == target { link.b } else { link.a };
            self.drop_index(peer, id);
            result.push((id, peer));
        }
        result.sort_unstable_by_key(|(id, _)| id.0);
        result
    }
}

impl Default for LinkTable {
    fn default() -> Self {
        Self::new()
    }
}

/// What [`LinkStore::link_if_live`] observed after the insert.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum LinkOutcome {
    /// Both endpoints were live and the row is still in the table.
    Linked(LinkId),
    /// Finalize already removed the row and propagated the exit. The id
    /// must not be published: a later unlink would fail the survivor.
    Consumed { dead: FlowId },
}

/// Fail-closed wrapper; process-wide link quota lives here (`table.len()`).
pub(crate) struct LinkStore {
    inner: std::sync::Mutex<LinkTable>,
    max_links: u32,
}

impl LinkStore {
    /// `max_links == 0` → unlimited.
    pub(crate) fn new(max_links: u32) -> Self {
        Self {
            inner: std::sync::Mutex::new(LinkTable::new()),
            max_links,
        }
    }

    /// Insert without a liveness check (unit tests).
    #[cfg(test)]
    pub(crate) fn link(
        &self,
        a: FlowId,
        b: FlowId,
    ) -> Result<Result<LinkId, LifecycleError>, RuntimeError> {
        match self.link_if_live(a, b, |_| Ok(true))? {
            Ok(LinkOutcome::Linked(id)) => Ok(Ok(id)),
            Ok(LinkOutcome::Consumed { dead }) => Ok(Err(LifecycleError::NoSuchFlow(dead))),
            Err(error) => Ok(Err(error)),
        }
    }

    /// Insert, then confirm both endpoints are still live.
    ///
    /// `is_live` runs **after** the link mutex is released so this never
    /// nests `LinkStore` → `Directory` (finalize takes those locks separately,
    /// never together). If a peer finalized in the window:
    ///
    /// - the link is still here → rollback and [`LifecycleError::NoSuchFlow`]
    ///   (zombie we created after `remove_links_of`)
    /// - the link is already gone → [`LinkOutcome::Consumed`]. Finalize
    ///   delivered the exit; the caller must not fail the survivor again
    ///   and must not hand out the removed id.
    pub(crate) fn link_if_live<F>(
        &self,
        a: FlowId,
        b: FlowId,
        is_live: F,
    ) -> Result<Result<LinkOutcome, LifecycleError>, RuntimeError>
    where
        F: Fn(FlowId) -> Result<bool, RuntimeError>,
    {
        let id = {
            let mut table = sync_lock::lock(&self.inner, "LinkStore::link")?;
            // Validate before the quota check so LimitReached never masks
            // SelfRelation / AlreadyLinked (same discipline as registry).
            if a == b {
                return Ok(Err(LifecycleError::SelfRelation));
            }
            if table.has_pair(a, b) {
                return Ok(Err(LifecycleError::AlreadyLinked));
            }
            if self.max_links != 0 && table.len() >= self.max_links as usize {
                return Ok(Err(LifecycleError::LinkLimitReached {
                    limit: self.max_links,
                }));
            }
            let id = try_next_link_id()?;
            table.insert(id, a, b);
            id
        };
        self.confirm_live(id, a, b, is_live)
    }

    fn confirm_live<F>(
        &self,
        id: LinkId,
        a: FlowId,
        b: FlowId,
        is_live: F,
    ) -> Result<Result<LinkOutcome, LifecycleError>, RuntimeError>
    where
        F: Fn(FlowId) -> Result<bool, RuntimeError>,
    {
        let a_live = match is_live(a) {
            Ok(v) => v,
            Err(e) => {
                let _ = self.force_remove(id);
                return Err(e);
            }
        };
        let b_live = match is_live(b) {
            Ok(v) => v,
            Err(e) => {
                let _ = self.force_remove(id);
                return Err(e);
            }
        };
        if a_live && b_live {
            return Ok(Ok(LinkOutcome::Linked(id)));
        }
        let dead = if a_live { b } else { a };
        match self.force_remove(id) {
            Ok(true) => Ok(Err(LifecycleError::NoSuchFlow(dead))),
            Ok(false) => Ok(Ok(LinkOutcome::Consumed { dead })),
            Err(e) => Err(e),
        }
    }

    fn force_remove(&self, id: LinkId) -> Result<bool, RuntimeError> {
        Ok(sync_lock::lock(&self.inner, "LinkStore::confirm_live")?
            .unlink_id(id)
            .is_some())
    }

    pub(crate) fn unlink_owned(
        &self,
        owner: FlowId,
        id: LinkId,
    ) -> Result<Result<(), LifecycleError>, RuntimeError> {
        Ok(sync_lock::lock(&self.inner, "LinkStore::unlink_owned")?.unlink_owned(owner, id))
    }

    pub(crate) fn remove_links_of(
        &self,
        target: FlowId,
    ) -> Result<Vec<(LinkId, FlowId)>, RuntimeError> {
        Ok(sync_lock::lock(&self.inner, "LinkStore::remove_links_of")?.remove_links_of(target))
    }
}

impl Default for LinkStore {
    fn default() -> Self {
        Self::new(0)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::scheduler::process::next_flow_id;

    #[test]
    fn remove_links_returns_both_directions() -> Result<(), String> {
        let mut table = LinkTable::new();
        let a = next_flow_id();
        let b = next_flow_id();
        let c = next_flow_id();
        table.link(a, b).map_err(|e| e.to_string())?;
        table.link(c, a).map_err(|e| e.to_string())?;
        let removed = table.remove_links_of(a);
        let peers: Vec<FlowId> = removed.iter().map(|(_, p)| *p).collect();
        assert_eq!(peers.len(), 2);
        assert!(peers.contains(&b));
        assert!(peers.contains(&c));
        assert!(removed[0].0 < removed[1].0);
        assert!(table.remove_links_of(a).is_empty());
        assert!(table.remove_links_of(b).is_empty());
        assert!(table.remove_links_of(c).is_empty());
        assert_eq!(table.len(), 0);
        Ok(())
    }

    #[test]
    fn rejects_self_and_duplicate() {
        let mut table = LinkTable::new();
        let a = next_flow_id();
        let b = next_flow_id();
        assert_eq!(table.link(a, a), Err(LifecycleError::SelfRelation));
        assert!(table.link(a, b).is_ok());
        assert_eq!(table.link(b, a), Err(LifecycleError::AlreadyLinked));
        assert!(table.has_pair(a, b));
        assert!(table.has_pair(b, a));
    }

    #[test]
    fn unlink_owned_rejects_stranger_and_unknown() -> Result<(), String> {
        let mut table = LinkTable::new();
        let a = next_flow_id();
        let b = next_flow_id();
        let stranger = next_flow_id();
        let id = table.link(a, b).map_err(|e| e.to_string())?;
        assert_eq!(
            table.unlink_owned(stranger, id),
            Err(LifecycleError::NotOwner)
        );
        assert_eq!(
            table.unlink_owned(a, LinkId::from_u64(0)),
            Err(LifecycleError::InvalidLink)
        );
        table.unlink_owned(b, id).map_err(|e| e.to_string())?;
        assert_eq!(table.unlink_owned(a, id), Err(LifecycleError::InvalidLink));
        assert_eq!(table.len(), 0);
        assert!(!table.has_pair(a, b));
        Ok(())
    }

    #[test]
    fn unlink_after_remove_is_invalid() -> Result<(), String> {
        let mut table = LinkTable::new();
        let a = next_flow_id();
        let b = next_flow_id();
        let id = table.link(a, b).map_err(|e| e.to_string())?;
        assert_eq!(table.remove_links_of(a), vec![(id, b)]);
        assert_eq!(table.unlink_owned(b, id), Err(LifecycleError::InvalidLink));
        Ok(())
    }

    #[test]
    fn link_limit_is_process_wide_and_released() -> Result<(), Box<dyn std::error::Error>> {
        let store = LinkStore::new(1);
        let a = next_flow_id();
        let b = next_flow_id();
        let c = next_flow_id();
        let first = store.link(a, b)??;
        let second = store.link(b, c)?;
        assert!(matches!(
            second,
            Err(LifecycleError::LinkLimitReached { limit: 1 })
        ));
        store.unlink_owned(a, first)??;
        store.link(b, c)??;
        Ok(())
    }

    #[test]
    fn link_limit_does_not_mask_self_or_duplicate() -> Result<(), Box<dyn std::error::Error>> {
        let store = LinkStore::new(1);
        let a = next_flow_id();
        let b = next_flow_id();
        store.link(a, b)??;
        // At capacity: self / duplicate must still win over LimitReached.
        let self_err = store.link(a, a)?;
        assert!(matches!(self_err, Err(LifecycleError::SelfRelation)));
        let dup = store.link(b, a)?;
        assert!(matches!(dup, Err(LifecycleError::AlreadyLinked)));
        let other = store.link(a, next_flow_id())?;
        assert!(matches!(
            other,
            Err(LifecycleError::LinkLimitReached { limit: 1 })
        ));
        Ok(())
    }

    #[test]
    fn unlimited_store_accepts_many() -> Result<(), Box<dyn std::error::Error>> {
        let store = LinkStore::new(0);
        let a = next_flow_id();
        store.link(a, next_flow_id())??;
        store.link(a, next_flow_id())??;
        store.link(a, next_flow_id())??;
        Ok(())
    }

    #[test]
    fn dead_peer_rolls_back_and_releases_quota() -> Result<(), Box<dyn std::error::Error>> {
        let store = LinkStore::new(1);
        let a = next_flow_id();
        let b = next_flow_id();
        let result = store.link_if_live(a, b, |id| Ok(id != b))?;
        assert!(matches!(result, Err(LifecycleError::NoSuchFlow(dead)) if dead == b));
        // Quota released: a fresh pair must fit.
        store.link_if_live(a, next_flow_id(), |_| Ok(true))??;
        Ok(())
    }

    #[test]
    fn finalize_already_removed_is_not_a_second_fault() -> Result<(), Box<dyn std::error::Error>> {
        let store = LinkStore::new(0);
        let a = next_flow_id();
        let b = next_flow_id();
        // Insert as live, tear down as finalize would, then confirm sees a
        // dead peer and a missing row. The removed id is not returned.
        let id = {
            let mut table = sync_lock::lock(&store.inner, "test")?;
            if table.has_pair(a, b) {
                return Err("pair should be free".into());
            }
            let id = try_next_link_id()?;
            table.insert(id, a, b);
            id
        };
        let _ = store.remove_links_of(b)?;
        let confirmed = store.confirm_live(id, a, b, |id| Ok(id != b))?;
        assert_eq!(confirmed, Ok(LinkOutcome::Consumed { dead: b }));
        Ok(())
    }
}