Skip to main content

byteflow/scheduler/
monitor.rs

1//! Monitor table: one-way lifecycle watches (`A ──monitor──> B`).
2//!
3//! A monitor is a **runtime relation**, not a field on [`crate::Message`].
4//! When the target exits, [`MonitorTable::notify_target_exit`] yields
5//! [`DownEvent`]s that [`super::finalize`] delivers as Atomic Hop
6//! [`crate::TAG_SYS_DOWN`] messages.
7//!
8//! Relations are keyed by [`FlowId`] (identity). Bytecode addresses the
9//! target through a Cap; the worker resolves Cap → FlowId before calling
10//! here. Caps are revoked on exit; FlowIds are never reused.
11
12use std::collections::HashMap;
13use std::sync::atomic::{AtomicU64, Ordering};
14
15use super::error::{LifecycleError, RuntimeError};
16use super::process::FlowId;
17use super::sync_lock;
18
19/// Opaque monitor reference, echoed on the `DOWN` hop as `request_id`.
20///
21/// The inner id is runtime-minted (`pub(crate)`): bytecode only ever sees
22/// it as `Value::Int` after `Monitor`, never as a host-constructed token.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
24pub struct MonitorRef(pub(crate) u64);
25
26static NEXT_MONITOR: AtomicU64 = AtomicU64::new(1);
27
28impl MonitorRef {
29    #[inline]
30    pub fn as_u64(self) -> u64 {
31        self.0
32    }
33
34    #[inline]
35    pub(crate) fn from_u64(raw: u64) -> Self {
36        Self(raw)
37    }
38}
39
40impl std::fmt::Display for MonitorRef {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        write!(f, "monitor#{}", self.0)
43    }
44}
45
46/// Why a flow left the directory. Encoded as `Message.payload` on system hops.
47///
48/// Named [`FlowExitReason`] so it does not collide with the JIT
49/// `ExitReason` (trace-compiler control flow).
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51#[repr(u8)]
52pub enum FlowExitReason {
53    Normal = 0,
54    /// Reserved: host-wide runtime teardown (not produced today).
55    Shutdown = 1,
56    Killed = 2,
57    Fault = 3,
58    /// Reserved: overflow-kill policy (today overflow is `MailboxFull` / park).
59    MailboxOverflow = 4,
60    Supervisor = 5,
61    Link = 6,
62}
63
64impl FlowExitReason {
65    pub fn from_u64(raw: u64) -> Option<Self> {
66        Some(match raw {
67            0 => Self::Normal,
68            1 => Self::Shutdown,
69            2 => Self::Killed,
70            3 => Self::Fault,
71            4 => Self::MailboxOverflow,
72            5 => Self::Supervisor,
73            6 => Self::Link,
74            _ => return None,
75        })
76    }
77
78    #[inline]
79    pub fn as_u64(self) -> u64 {
80        self as u64
81    }
82
83    /// Abnormal exits propagate through links (BEAM: `normal` does not).
84    ///
85    /// `Shutdown` / `Killed` / `Supervisor` are host-policy reasons;
86    /// they still count as abnormal so a supervisor abort is not
87    /// silently swallowed by links.
88    #[inline]
89    pub fn is_abnormal(self) -> bool {
90        !matches!(self, Self::Normal)
91    }
92}
93
94impl std::fmt::Display for FlowExitReason {
95    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96        let name = match self {
97            Self::Normal => "normal",
98            Self::Shutdown => "shutdown",
99            Self::Killed => "killed",
100            Self::Fault => "fault",
101            Self::MailboxOverflow => "mailbox-overflow",
102            Self::Supervisor => "supervisor",
103            Self::Link => "link",
104        };
105        f.write_str(name)
106    }
107}
108
109/// One monitor firing after the target left the runtime.
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111pub struct DownEvent {
112    pub monitor: MonitorRef,
113    pub owner: FlowId,
114    pub target: FlowId,
115    pub reason: FlowExitReason,
116}
117
118#[derive(Debug, Clone, Copy)]
119struct MonitorEntry {
120    owner: FlowId,
121    target: FlowId,
122}
123
124/// `MonitorRef → { owner, target }`. Lives on [`super::runtime::Shared`].
125pub struct MonitorTable {
126    monitors: HashMap<MonitorRef, MonitorEntry>,
127}
128
129impl MonitorTable {
130    pub fn new() -> Self {
131        Self {
132            monitors: HashMap::new(),
133        }
134    }
135
136    pub fn create(&mut self, owner: FlowId, target: FlowId) -> MonitorRef {
137        let monitor = MonitorRef(NEXT_MONITOR.fetch_add(1, Ordering::Relaxed));
138        self.monitors
139            .insert(monitor, MonitorEntry { owner, target });
140        monitor
141    }
142
143    /// Remove `monitor` only if `owner` still owns it.
144    pub fn remove_owned(
145        &mut self,
146        owner: FlowId,
147        monitor: MonitorRef,
148    ) -> Result<(), LifecycleError> {
149        match self.monitors.get(&monitor) {
150            Some(entry) if entry.owner == owner => {
151                self.monitors.remove(&monitor);
152                Ok(())
153            }
154            Some(_) => Err(LifecycleError::NotOwner),
155            None => Err(LifecycleError::InvalidMonitor),
156        }
157    }
158
159    /// Drop every monitor whose **owner** is `flow` (owner exited).
160    pub fn remove_owned_by(&mut self, owner: FlowId) {
161        self.monitors.retain(|_, entry| entry.owner != owner);
162    }
163
164    /// Collect `DOWN` events for monitors watching `target`, then drop them.
165    pub fn notify_target_exit(&mut self, target: FlowId, reason: FlowExitReason) -> Vec<DownEvent> {
166        let mut events = Vec::new();
167        self.monitors.retain(|monitor, entry| {
168            if entry.target != target {
169                return true;
170            }
171            events.push(DownEvent {
172                monitor: *monitor,
173                owner: entry.owner,
174                target,
175                reason,
176            });
177            false
178        });
179        events.sort_unstable_by_key(|event| event.monitor.0);
180        events
181    }
182}
183
184impl Default for MonitorTable {
185    fn default() -> Self {
186        Self::new()
187    }
188}
189
190/// Fail-closed wrapper around [`MonitorTable`].
191pub struct MonitorStore {
192    inner: std::sync::Mutex<MonitorTable>,
193}
194
195impl MonitorStore {
196    pub fn new() -> Self {
197        Self {
198            inner: std::sync::Mutex::new(MonitorTable::new()),
199        }
200    }
201
202    pub fn create(&self, owner: FlowId, target: FlowId) -> Result<MonitorRef, RuntimeError> {
203        Ok(sync_lock::lock(&self.inner, "MonitorStore::create")?.create(owner, target))
204    }
205
206    pub fn remove_owned(
207        &self,
208        owner: FlowId,
209        monitor: MonitorRef,
210    ) -> Result<Result<(), LifecycleError>, RuntimeError> {
211        Ok(
212            sync_lock::lock(&self.inner, "MonitorStore::remove_owned")?
213                .remove_owned(owner, monitor),
214        )
215    }
216
217    pub fn remove_owned_by(&self, owner: FlowId) -> Result<(), RuntimeError> {
218        sync_lock::lock(&self.inner, "MonitorStore::remove_owned_by")?.remove_owned_by(owner);
219        Ok(())
220    }
221
222    pub fn notify_target_exit(
223        &self,
224        target: FlowId,
225        reason: FlowExitReason,
226    ) -> Result<Vec<DownEvent>, RuntimeError> {
227        Ok(
228            sync_lock::lock(&self.inner, "MonitorStore::notify_target_exit")?
229                .notify_target_exit(target, reason),
230        )
231    }
232}
233
234impl Default for MonitorStore {
235    fn default() -> Self {
236        Self::new()
237    }
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243    use crate::scheduler::process::next_flow_id;
244
245    #[test]
246    fn notify_removes_and_sorts() {
247        let mut table = MonitorTable::new();
248        let owner = next_flow_id();
249        let target = next_flow_id();
250        let a = table.create(owner, target);
251        let b = table.create(owner, target);
252        let events = table.notify_target_exit(target, FlowExitReason::Fault);
253        assert_eq!(events.len(), 2);
254        assert_eq!(events[0].monitor, a);
255        assert_eq!(events[1].monitor, b);
256        assert!(table
257            .notify_target_exit(target, FlowExitReason::Fault)
258            .is_empty());
259    }
260
261    #[test]
262    fn remove_owned_rejects_other_flow() {
263        let mut table = MonitorTable::new();
264        let owner = next_flow_id();
265        let other = next_flow_id();
266        let target = next_flow_id();
267        let mon = table.create(owner, target);
268        assert_eq!(
269            table.remove_owned(other, mon),
270            Err(LifecycleError::NotOwner)
271        );
272        assert!(table.remove_owned(owner, mon).is_ok());
273    }
274}