byteflow/scheduler/mailbox/capacity.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/// Logical hop bound for one flow's inbox.
6///
7/// # Why not `usize`
8///
9/// A raw `capacity: usize` lets a 64-bit host pass an absurd value and
10/// pretend it is a memory contract. An embeddable M:N runtime must pick
11/// deliberate bounds: enough hops for request/reply bursts, not enough to
12/// grow RSS until OOM when a slow consumer sits under a fast producer.
13///
14/// `MIN = 1` (a mailbox that cannot hold a hop is not a mailbox).
15/// `MAX = 1 << 20` (~1M hops) is a hard ceiling, not a recommendation —
16/// the default is [`MailboxCapacity::DEFAULT`] (256).
17#[repr(transparent)]
18#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
19pub struct MailboxCapacity(u32);
20
21impl MailboxCapacity {
22 pub const MIN: u32 = 1;
23 pub const MAX: u32 = 1 << 20;
24 /// Default logical bound used by [`super::MailboxConfig::DEFAULT`].
25 pub const DEFAULT: MailboxCapacity = MailboxCapacity(256);
26
27 /// `Some` iff `value` is in `MIN..=MAX`.
28 pub const fn new(value: u32) -> Option<Self> {
29 if value < Self::MIN || value > Self::MAX {
30 None
31 } else {
32 Some(Self(value))
33 }
34 }
35
36 #[inline]
37 pub const fn get(self) -> usize {
38 self.0 as usize
39 }
40
41 #[inline]
42 pub const fn get_u32(self) -> u32 {
43 self.0
44 }
45}
46
47impl Default for MailboxCapacity {
48 fn default() -> Self {
49 Self::DEFAULT
50 }
51}
52
53/// Byte budget for one flow's inbox, enforced alongside
54/// [`MailboxCapacity`].
55///
56/// # Why a hop count is not a memory bound
57///
58/// [`MailboxCapacity`] bounds *how many* hops an inbox holds. Since ABI v4
59/// a hop may carry [`crate::Value::Str`] / [`crate::Value::Bytes`], and the
60/// `.bf` decoder accepts blobs up to 1 MiB, so "256 hops" is anywhere from
61/// ~12 KiB of scalars to ~256 MiB of blobs. A count alone therefore does
62/// not bound RSS — which is the whole point of bounding the mailbox.
63///
64/// Cost per hop comes from [`crate::Value::memory_size`]; read its doc for
65/// why `Arc`-shared payloads are deliberately over-charged.
66///
67/// # Choosing the default
68///
69/// `DEFAULT` is 4 MiB, which must stay **strictly greater** than the
70/// largest single hop the `.bf` decoder will produce (`MAX_BLOB` in
71/// [`crate::decode`]'s module, 1 MiB) plus its envelope. A budget equal to
72/// the maximum payload size would make a legal, decodable constant
73/// permanently undeliverable under the default config — a bound should
74/// refuse abuse, not valid inputs. `byte_budget_default_fits_one_max_hop`
75/// guards that relationship.
76///
77/// `MIN = 1 KiB` (an inbox that cannot hold a handful of scalar hops is
78/// not an inbox). `MAX = 1 GiB` is a hard ceiling, not a recommendation.
79#[repr(transparent)]
80#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
81pub struct MailboxBytes(usize);
82
83impl MailboxBytes {
84 pub const MIN: usize = 1 << 10;
85 pub const MAX: usize = 1 << 30;
86 /// Default byte budget used by [`super::MailboxConfig::DEFAULT`]:
87 /// 4 MiB. See the type doc for why it is not 1 MiB.
88 pub const DEFAULT: MailboxBytes = MailboxBytes(1 << 22);
89
90 /// `Some` iff `value` is in `MIN..=MAX`.
91 pub const fn new(value: usize) -> Option<Self> {
92 if value < Self::MIN || value > Self::MAX {
93 None
94 } else {
95 Some(Self(value))
96 }
97 }
98
99 #[inline]
100 pub const fn get(self) -> usize {
101 self.0
102 }
103}
104
105impl Default for MailboxBytes {
106 fn default() -> Self {
107 Self::DEFAULT
108 }
109}
110
111#[cfg(test)]
112mod tests {
113 use super::*;
114
115 #[test]
116 fn rejects_zero_and_over_max() -> Result<(), &'static str> {
117 assert!(MailboxCapacity::new(0).is_none());
118 assert!(MailboxCapacity::new(MailboxCapacity::MAX + 1).is_none());
119 let min = MailboxCapacity::new(1).ok_or("min capacity")?;
120 assert_eq!(min.get(), 1);
121 let max = MailboxCapacity::new(MailboxCapacity::MAX).ok_or("max capacity")?;
122 assert_eq!(max.get_u32(), MailboxCapacity::MAX);
123 Ok(())
124 }
125
126 #[test]
127 fn default_is_compile_time_valid() {
128 assert_eq!(MailboxCapacity::DEFAULT.get(), 256);
129 assert!(MailboxCapacity::new(256).is_some());
130 }
131
132 #[test]
133 fn byte_budget_rejects_out_of_range() -> Result<(), &'static str> {
134 assert!(MailboxBytes::new(0).is_none());
135 assert!(MailboxBytes::new(MailboxBytes::MIN - 1).is_none());
136 assert!(MailboxBytes::new(MailboxBytes::MAX + 1).is_none());
137 let min = MailboxBytes::new(MailboxBytes::MIN).ok_or("min bytes")?;
138 assert_eq!(min.get(), MailboxBytes::MIN);
139 Ok(())
140 }
141
142 #[test]
143 fn byte_budget_default_holds_a_full_scalar_inbox() {
144 // DEFAULT must not reject a mailbox filled to DEFAULT capacity with
145 // scalar hops, or the byte bound would shadow the hop bound.
146 let worst = MailboxCapacity::DEFAULT.get() * std::mem::size_of::<crate::Value>();
147 assert!(MailboxBytes::DEFAULT.get() > worst);
148 }
149
150 #[test]
151 fn byte_budget_default_fits_one_max_hop() {
152 // `MAX_BLOB` in `bytecode::format` (private) caps a decoded
153 // `Str`/`Bytes` constant at 1 MiB. The default budget must fit one
154 // of those *plus* its envelope, or the decoder would happily accept
155 // a constant that no mailbox could ever receive.
156 const MAX_BLOB: usize = 1_048_576;
157 let biggest = crate::Value::bytes(vec![0u8; MAX_BLOB]);
158 assert!(biggest.memory_size() <= MailboxBytes::DEFAULT.get());
159 }
160}