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    /// Host-wide runtime teardown (parked HostAwait drain, etc.).
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    #[inline]
137    pub fn len(&self) -> usize {
138        self.monitors.len()
139    }
140
141    pub fn create(&mut self, owner: FlowId, target: FlowId) -> MonitorRef {
142        let monitor = MonitorRef(NEXT_MONITOR.fetch_add(1, Ordering::Relaxed));
143        self.monitors
144            .insert(monitor, MonitorEntry { owner, target });
145        monitor
146    }
147
148    /// Remove `monitor` only if `owner` still owns it.
149    pub fn remove_owned(
150        &mut self,
151        owner: FlowId,
152        monitor: MonitorRef,
153    ) -> Result<(), LifecycleError> {
154        match self.monitors.get(&monitor) {
155            Some(entry) if entry.owner == owner => {
156                self.monitors.remove(&monitor);
157                Ok(())
158            }
159            Some(_) => Err(LifecycleError::NotOwner),
160            None => Err(LifecycleError::InvalidMonitor),
161        }
162    }
163
164    /// Drop every monitor whose **owner** is `flow` (owner exited).
165    pub fn remove_owned_by(&mut self, owner: FlowId) {
166        self.monitors.retain(|_, entry| entry.owner != owner);
167    }
168
169    /// Collect `DOWN` events for monitors watching `target`, then drop them.
170    pub fn notify_target_exit(&mut self, target: FlowId, reason: FlowExitReason) -> Vec<DownEvent> {
171        let mut events = Vec::new();
172        self.monitors.retain(|monitor, entry| {
173            if entry.target != target {
174                return true;
175            }
176            events.push(DownEvent {
177                monitor: *monitor,
178                owner: entry.owner,
179                target,
180                reason,
181            });
182            false
183        });
184        events.sort_unstable_by_key(|event| event.monitor.0);
185        events
186    }
187}
188
189impl Default for MonitorTable {
190    fn default() -> Self {
191        Self::new()
192    }
193}
194
195/// Fail-closed wrapper around [`MonitorTable`].
196///
197/// Process-wide monitor quota lives here (`table.len()` under the same lock).
198pub struct MonitorStore {
199    inner: std::sync::Mutex<MonitorTable>,
200    max_monitors: u32,
201}
202
203impl MonitorStore {
204    /// `max_monitors == 0` → unlimited.
205    pub fn new(max_monitors: u32) -> Self {
206        Self {
207            inner: std::sync::Mutex::new(MonitorTable::new()),
208            max_monitors,
209        }
210    }
211
212    pub fn create(
213        &self,
214        owner: FlowId,
215        target: FlowId,
216    ) -> Result<Result<MonitorRef, LifecycleError>, RuntimeError> {
217        let mut table = sync_lock::lock(&self.inner, "MonitorStore::create")?;
218        if self.max_monitors != 0 && table.len() as u32 >= self.max_monitors {
219            return Ok(Err(LifecycleError::MonitorLimitReached {
220                limit: self.max_monitors,
221            }));
222        }
223        Ok(Ok(table.create(owner, target)))
224    }
225
226    pub fn remove_owned(
227        &self,
228        owner: FlowId,
229        monitor: MonitorRef,
230    ) -> Result<Result<(), LifecycleError>, RuntimeError> {
231        Ok(
232            sync_lock::lock(&self.inner, "MonitorStore::remove_owned")?
233                .remove_owned(owner, monitor),
234        )
235    }
236
237    pub fn remove_owned_by(&self, owner: FlowId) -> Result<(), RuntimeError> {
238        sync_lock::lock(&self.inner, "MonitorStore::remove_owned_by")?.remove_owned_by(owner);
239        Ok(())
240    }
241
242    pub fn notify_target_exit(
243        &self,
244        target: FlowId,
245        reason: FlowExitReason,
246    ) -> Result<Vec<DownEvent>, RuntimeError> {
247        Ok(
248            sync_lock::lock(&self.inner, "MonitorStore::notify_target_exit")?
249                .notify_target_exit(target, reason),
250        )
251    }
252}
253
254impl Default for MonitorStore {
255    fn default() -> Self {
256        Self::new(0)
257    }
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263    use crate::scheduler::process::next_flow_id;
264
265    #[test]
266    fn notify_removes_and_sorts() {
267        let mut table = MonitorTable::new();
268        let owner = next_flow_id();
269        let target = next_flow_id();
270        let a = table.create(owner, target);
271        let b = table.create(owner, target);
272        let events = table.notify_target_exit(target, FlowExitReason::Fault);
273        assert_eq!(events.len(), 2);
274        assert_eq!(events[0].monitor, a);
275        assert_eq!(events[1].monitor, b);
276        assert!(table
277            .notify_target_exit(target, FlowExitReason::Fault)
278            .is_empty());
279    }
280
281    #[test]
282    fn remove_owned_rejects_other_flow() {
283        let mut table = MonitorTable::new();
284        let owner = next_flow_id();
285        let other = next_flow_id();
286        let target = next_flow_id();
287        let mon = table.create(owner, target);
288        assert_eq!(
289            table.remove_owned(other, mon),
290            Err(LifecycleError::NotOwner)
291        );
292        assert!(table.remove_owned(owner, mon).is_ok());
293    }
294
295    #[test]
296    fn monitor_limit_is_process_wide_and_released() -> Result<(), Box<dyn std::error::Error>> {
297        let store = MonitorStore::new(1);
298        let owner = next_flow_id();
299        let t1 = next_flow_id();
300        let t2 = next_flow_id();
301        let first = match store.create(owner, t1)? {
302            Ok(id) => id,
303            Err(e) => return Err(e.into()),
304        };
305        let second = store.create(owner, t2)?;
306        assert!(matches!(
307            second,
308            Err(LifecycleError::MonitorLimitReached { limit: 1 })
309        ));
310        store.remove_owned(owner, first)??;
311        match store.create(owner, t2)? {
312            Ok(_) => Ok(()),
313            Err(e) => Err(e.into()),
314        }
315    }
316}