1#![allow(missing_docs)]
15
16use std::collections::HashMap;
17use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
18
19use super::error::{LifecycleError, RuntimeError};
20use super::process::FlowId;
21use super::sync_lock;
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
28pub struct MonitorRef(pub(crate) u64);
29
30const MAX_MONITOR_ID: u64 = i64::MAX as u64;
32
33static NEXT_MONITOR: AtomicU64 = AtomicU64::new(1);
34static MONITOR_IDS_EXHAUSTED: AtomicBool = AtomicBool::new(false);
35
36fn try_next_monitor_id() -> Result<MonitorRef, RuntimeError> {
37 if MONITOR_IDS_EXHAUSTED.load(Ordering::Relaxed) {
38 return Err(RuntimeError::MonitorIdExhausted);
39 }
40 let id = NEXT_MONITOR.fetch_add(1, Ordering::Relaxed);
41 if id == 0 || id > MAX_MONITOR_ID {
42 MONITOR_IDS_EXHAUSTED.store(true, Ordering::Relaxed);
43 return Err(RuntimeError::MonitorIdExhausted);
44 }
45 Ok(MonitorRef(id))
46}
47
48impl MonitorRef {
49 #[inline]
50 pub fn as_u64(self) -> u64 {
51 self.0
52 }
53
54 #[inline]
55 pub(crate) fn from_u64(raw: u64) -> Self {
56 Self(raw)
57 }
58}
59
60impl std::fmt::Display for MonitorRef {
61 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62 write!(f, "monitor#{}", self.0)
63 }
64}
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71#[repr(u8)]
72pub enum FlowExitReason {
73 Normal = 0,
74 Shutdown = 1,
76 Killed = 2,
77 Fault = 3,
78 MailboxOverflow = 4,
80 Supervisor = 5,
81 Link = 6,
82}
83
84impl FlowExitReason {
85 pub fn from_u64(raw: u64) -> Option<Self> {
86 Some(match raw {
87 0 => Self::Normal,
88 1 => Self::Shutdown,
89 2 => Self::Killed,
90 3 => Self::Fault,
91 4 => Self::MailboxOverflow,
92 5 => Self::Supervisor,
93 6 => Self::Link,
94 _ => return None,
95 })
96 }
97
98 #[inline]
99 pub fn as_u64(self) -> u64 {
100 self as u64
101 }
102
103 #[inline]
109 pub fn is_abnormal(self) -> bool {
110 !matches!(self, Self::Normal)
111 }
112}
113
114impl std::fmt::Display for FlowExitReason {
115 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116 let name = match self {
117 Self::Normal => "normal",
118 Self::Shutdown => "shutdown",
119 Self::Killed => "killed",
120 Self::Fault => "fault",
121 Self::MailboxOverflow => "mailbox-overflow",
122 Self::Supervisor => "supervisor",
123 Self::Link => "link",
124 };
125 f.write_str(name)
126 }
127}
128
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131pub struct DownEvent {
132 pub monitor: MonitorRef,
133 pub owner: FlowId,
134 pub target: FlowId,
135 pub reason: FlowExitReason,
136}
137
138#[derive(Debug, Clone, Copy)]
139struct MonitorEntry {
140 owner: FlowId,
141 target: FlowId,
142}
143
144pub(super) struct MonitorTable {
149 monitors: HashMap<MonitorRef, MonitorEntry>,
150 by_owner: HashMap<FlowId, Vec<MonitorRef>>,
151 by_target: HashMap<FlowId, Vec<MonitorRef>>,
152}
153
154impl MonitorTable {
155 pub(super) fn new() -> Self {
156 Self {
157 monitors: HashMap::new(),
158 by_owner: HashMap::new(),
159 by_target: HashMap::new(),
160 }
161 }
162
163 #[inline]
164 pub(super) fn len(&self) -> usize {
165 self.monitors.len()
166 }
167
168 fn index_add(map: &mut HashMap<FlowId, Vec<MonitorRef>>, flow: FlowId, id: MonitorRef) {
169 map.entry(flow).or_default().push(id);
170 }
171
172 fn index_remove(map: &mut HashMap<FlowId, Vec<MonitorRef>>, flow: FlowId, id: MonitorRef) {
173 if let Some(ids) = map.get_mut(&flow) {
174 ids.retain(|existing| *existing != id);
175 if ids.is_empty() {
176 map.remove(&flow);
177 }
178 }
179 }
180
181 fn insert(&mut self, monitor: MonitorRef, owner: FlowId, target: FlowId) {
182 self.monitors
183 .insert(monitor, MonitorEntry { owner, target });
184 Self::index_add(&mut self.by_owner, owner, monitor);
185 Self::index_add(&mut self.by_target, target, monitor);
186 }
187
188 fn take(&mut self, monitor: MonitorRef) -> Option<MonitorEntry> {
189 let entry = self.monitors.remove(&monitor)?;
190 Self::index_remove(&mut self.by_owner, entry.owner, monitor);
191 Self::index_remove(&mut self.by_target, entry.target, monitor);
192 Some(entry)
193 }
194
195 #[cfg(test)]
196 pub(crate) fn create(
197 &mut self,
198 owner: FlowId,
199 target: FlowId,
200 ) -> Result<MonitorRef, RuntimeError> {
201 let monitor = try_next_monitor_id()?;
202 self.insert(monitor, owner, target);
203 Ok(monitor)
204 }
205
206 pub(super) fn remove_owned(
208 &mut self,
209 owner: FlowId,
210 monitor: MonitorRef,
211 ) -> Result<(), LifecycleError> {
212 match self.monitors.get(&monitor) {
213 Some(entry) if entry.owner == owner => {
214 let _ = self.take(monitor);
215 Ok(())
216 }
217 Some(_) => Err(LifecycleError::NotOwner),
218 None => Err(LifecycleError::InvalidMonitor),
219 }
220 }
221
222 pub(super) fn remove_owned_by(&mut self, owner: FlowId) {
224 let Some(ids) = self.by_owner.remove(&owner) else {
225 return;
226 };
227 for id in ids {
228 if let Some(entry) = self.monitors.remove(&id) {
229 Self::index_remove(&mut self.by_target, entry.target, id);
230 }
231 }
232 }
233
234 pub(super) fn notify_target_exit(
236 &mut self,
237 target: FlowId,
238 reason: FlowExitReason,
239 ) -> Vec<DownEvent> {
240 let Some(ids) = self.by_target.remove(&target) else {
241 return Vec::new();
242 };
243 let mut events = Vec::with_capacity(ids.len());
244 for monitor in ids {
245 let Some(entry) = self.monitors.remove(&monitor) else {
246 continue;
247 };
248 Self::index_remove(&mut self.by_owner, entry.owner, monitor);
249 events.push(DownEvent {
250 monitor,
251 owner: entry.owner,
252 target,
253 reason,
254 });
255 }
256 events.sort_unstable_by_key(|event| event.monitor.0);
257 events
258 }
259}
260
261impl Default for MonitorTable {
262 fn default() -> Self {
263 Self::new()
264 }
265}
266
267pub(crate) struct MonitorStore {
271 inner: std::sync::Mutex<MonitorTable>,
272 max_monitors: u32,
273}
274
275impl MonitorStore {
276 pub(crate) fn new(max_monitors: u32) -> Self {
278 Self {
279 inner: std::sync::Mutex::new(MonitorTable::new()),
280 max_monitors,
281 }
282 }
283
284 pub(crate) fn create(
285 &self,
286 owner: FlowId,
287 target: FlowId,
288 ) -> Result<Result<MonitorRef, LifecycleError>, RuntimeError> {
289 let mut table = sync_lock::lock(&self.inner, "MonitorStore::create")?;
290 if self.max_monitors != 0 && table.len() >= self.max_monitors as usize {
291 return Ok(Err(LifecycleError::MonitorLimitReached {
292 limit: self.max_monitors,
293 }));
294 }
295 let monitor = try_next_monitor_id()?;
296 table.insert(monitor, owner, target);
297 Ok(Ok(monitor))
298 }
299
300 pub(crate) fn remove_owned(
301 &self,
302 owner: FlowId,
303 monitor: MonitorRef,
304 ) -> Result<Result<(), LifecycleError>, RuntimeError> {
305 Ok(
306 sync_lock::lock(&self.inner, "MonitorStore::remove_owned")?
307 .remove_owned(owner, monitor),
308 )
309 }
310
311 pub(crate) fn remove_owned_by(&self, owner: FlowId) -> Result<(), RuntimeError> {
312 sync_lock::lock(&self.inner, "MonitorStore::remove_owned_by")?.remove_owned_by(owner);
313 Ok(())
314 }
315
316 pub(crate) fn notify_target_exit(
317 &self,
318 target: FlowId,
319 reason: FlowExitReason,
320 ) -> Result<Vec<DownEvent>, RuntimeError> {
321 Ok(
322 sync_lock::lock(&self.inner, "MonitorStore::notify_target_exit")?
323 .notify_target_exit(target, reason),
324 )
325 }
326}
327
328impl Default for MonitorStore {
329 fn default() -> Self {
330 Self::new(0)
331 }
332}
333
334#[cfg(test)]
335mod tests {
336 use super::*;
337 use crate::scheduler::process::next_flow_id;
338
339 #[test]
340 fn notify_removes_and_sorts() -> Result<(), RuntimeError> {
341 let mut table = MonitorTable::new();
342 let owner = next_flow_id();
343 let target = next_flow_id();
344 let a = table.create(owner, target)?;
345 let b = table.create(owner, target)?;
346 let events = table.notify_target_exit(target, FlowExitReason::Fault);
347 assert_eq!(events.len(), 2);
348 assert_eq!(events[0].monitor, a);
349 assert_eq!(events[1].monitor, b);
350 assert!(table
351 .notify_target_exit(target, FlowExitReason::Fault)
352 .is_empty());
353 Ok(())
354 }
355
356 #[test]
357 fn remove_owned_rejects_other_flow() -> Result<(), RuntimeError> {
358 let mut table = MonitorTable::new();
359 let owner = next_flow_id();
360 let other = next_flow_id();
361 let target = next_flow_id();
362 let mon = table.create(owner, target)?;
363 assert_eq!(
364 table.remove_owned(other, mon),
365 Err(LifecycleError::NotOwner)
366 );
367 assert!(table.remove_owned(owner, mon).is_ok());
368 Ok(())
369 }
370
371 #[test]
372 fn monitor_limit_is_process_wide_and_released() -> Result<(), Box<dyn std::error::Error>> {
373 let store = MonitorStore::new(1);
374 let owner = next_flow_id();
375 let t1 = next_flow_id();
376 let t2 = next_flow_id();
377 let first = store.create(owner, t1)??;
378 let second = store.create(owner, t2)?;
379 assert!(matches!(
380 second,
381 Err(LifecycleError::MonitorLimitReached { limit: 1 })
382 ));
383 store.remove_owned(owner, first)??;
384 match store.create(owner, t2)? {
385 Ok(_) => Ok(()),
386 Err(e) => Err(e.into()),
387 }
388 }
389}