Skip to main content

byteflow/scheduler/mailbox/
policy.rs

1// Docs ratchet: public items here predate `missing_docs`. Delete this
2// allow once they are documented; new files get the lint by default.
3#![allow(missing_docs)]
4
5/// What happens when a hop would exceed the mailbox's **logical** capacity.
6///
7/// # Why there is no `Block`
8///
9/// Parking the **OS worker** on a full mailbox would stall every other flow
10/// on that thread — the opposite of an M:N scheduler. Backpressure that
11/// waits belongs to scheduler-level `WAITING_SEND` (one parked sender
12/// woken per freed slot), not to a queue method that holds a worker.
13///
14/// This revision therefore only offers **non-blocking** overflow:
15///
16/// | Policy | Effect |
17/// |--------|--------|
18/// | [`Reject`](Self::Reject) | Hop is not accepted; caller sees [`super::MailboxFull`] / [`crate::SendError::MailboxFull`] |
19/// | [`DropNewest`](Self::DropNewest) | Incoming hop discarded; queue unchanged |
20/// | [`DropOldest`](Self::DropOldest) | Oldest queued hop dropped, incoming enqueued (still FIFO among survivors) |
21///
22/// Default is [`Reject`](Self::Reject): fail-closed. Silent drop is an
23/// explicit embedder choice.
24#[repr(u8)]
25#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
26pub enum OverflowPolicy {
27    #[default]
28    Reject = 0,
29    DropNewest = 1,
30    DropOldest = 2,
31}
32
33/// Memory + overflow contract for every mailbox spawned by a [`crate::Runtime`].
34///
35/// Fields are private so an out-of-range capacity or byte budget cannot
36/// sneak in. Construct with [`MailboxConfig::new`] or
37/// [`MailboxConfig::DEFAULT`], then narrow the byte budget with
38/// [`MailboxConfig::with_bytes`].
39///
40/// Both bounds apply; the first one reached refuses the hop. See
41/// [`super::MailboxBytes`] for why the hop count alone is not a memory
42/// bound.
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44pub struct MailboxConfig {
45    capacity: super::MailboxCapacity,
46    bytes: super::MailboxBytes,
47    overflow: OverflowPolicy,
48}
49
50impl MailboxConfig {
51    /// Compile-time-valid default: 256 hops, 4 MiB, reject on overflow.
52    pub const DEFAULT: MailboxConfig = MailboxConfig {
53        capacity: super::MailboxCapacity::DEFAULT,
54        bytes: super::MailboxBytes::DEFAULT,
55        overflow: OverflowPolicy::Reject,
56    };
57
58    /// Capacity + policy, with the default byte budget.
59    ///
60    /// The byte budget is a separate builder step rather than a third
61    /// parameter so embedders that only care about hop count are not
62    /// forced to reason about bytes to keep compiling.
63    pub const fn new(capacity: super::MailboxCapacity, overflow: OverflowPolicy) -> Self {
64        Self {
65            capacity,
66            bytes: super::MailboxBytes::DEFAULT,
67            overflow,
68        }
69    }
70
71    /// Replace the byte budget.
72    pub const fn with_bytes(self, bytes: super::MailboxBytes) -> Self {
73        Self { bytes, ..self }
74    }
75
76    #[inline]
77    pub const fn capacity(&self) -> super::MailboxCapacity {
78        self.capacity
79    }
80
81    #[inline]
82    pub const fn bytes(&self) -> super::MailboxBytes {
83        self.bytes
84    }
85
86    #[inline]
87    pub const fn overflow(&self) -> OverflowPolicy {
88        self.overflow
89    }
90}
91
92impl Default for MailboxConfig {
93    fn default() -> Self {
94        Self::DEFAULT
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    use crate::scheduler::mailbox::{MailboxBytes, MailboxCapacity};
102
103    #[test]
104    fn default_is_reject_256() {
105        let c = MailboxConfig::DEFAULT;
106        assert_eq!(c.capacity().get(), 256);
107        assert_eq!(c.bytes().get(), MailboxBytes::DEFAULT.get());
108        assert_eq!(c.overflow(), OverflowPolicy::Reject);
109    }
110
111    #[test]
112    fn new_preserves_parts() -> Result<(), &'static str> {
113        let cap = MailboxCapacity::new(4).ok_or("cap")?;
114        let c = MailboxConfig::new(cap, OverflowPolicy::DropOldest);
115        assert_eq!(c.capacity().get(), 4);
116        assert_eq!(c.overflow(), OverflowPolicy::DropOldest);
117        assert_eq!(c.bytes().get(), MailboxBytes::DEFAULT.get());
118        Ok(())
119    }
120
121    #[test]
122    fn with_bytes_narrows_only_the_budget() -> Result<(), &'static str> {
123        let cap = MailboxCapacity::new(4).ok_or("cap")?;
124        let budget = MailboxBytes::new(8192).ok_or("bytes")?;
125        let c = MailboxConfig::new(cap, OverflowPolicy::DropOldest).with_bytes(budget);
126        assert_eq!(c.bytes().get(), 8192);
127        assert_eq!(c.capacity().get(), 4);
128        assert_eq!(c.overflow(), OverflowPolicy::DropOldest);
129        Ok(())
130    }
131}