Skip to main content

printobserver_core/
inbox.rs

1//! What reaches a turn while it is running.
2//!
3//! One agent per print at a time. An event that arrives for a print whose turn
4//! is still running does not start a second turn: it is written down like any
5//! other and then handed to the turn already running, which takes it the next
6//! time it looks at the print. Whatever that turn never took is handed, when it
7//! returns, to one more turn in the same session — so nothing that arrived is
8//! lost and no two agents ever disagree about one machine.
9//!
10//! This is a blocking structure on purpose. A look waits on it for up to a
11//! minute and a half, and the caller is expected to wait on a thread of its
12//! own rather than on an asynchronous worker, exactly as the harness itself is
13//! driven.
14
15use std::collections::BTreeMap;
16use std::sync::{Condvar, Mutex, MutexGuard};
17use std::time::{Duration, Instant};
18
19use printobserver_types::{EventRecord, ImageRef, PrintId};
20use printobserver_vision_api::Detection;
21
22/// One event waiting for a running turn, with what the detector did about it.
23#[derive(Debug, Clone, PartialEq)]
24pub struct Arrival {
25    /// When the frame an alert brought was captured; the event's own payload says
26    /// it for a check or a look, whose frame it was written down with.
27    pub frame_captured_at: Option<printobserver_types::Timestamp>,
28    /// The event, as it was written down, carrying its image.
29    pub event: EventRecord,
30    /// What the detector did, when the event is one of its detections.
31    pub detection: Option<Detection>,
32    /// What came of asking the server's own camera for a frame as a detector's
33    /// alert arrived, which its check is composed from where it can be.
34    pub camera_frame: AlertCameraFrame,
35}
36
37/// What came of asking the server's own camera for a frame as a detector's
38/// alert arrived.
39#[derive(Debug, Clone, PartialEq, Eq, Default)]
40pub enum AlertCameraFrame {
41    /// Nothing was asked: the event is no detector's alert, or its check could
42    /// not be composed whatever frame it had.
43    #[default]
44    NotAsked,
45    /// The camera's frame, stored against the alert, and when it was captured.
46    Had {
47        /// The stored frame.
48        image: ImageRef,
49        /// When it was captured.
50        captured_at: printobserver_types::Timestamp,
51    },
52    /// The camera gave no frame, or it could not be stored, and why.
53    Missing(String),
54}
55
56/// One print's inbox.
57#[derive(Debug, Default)]
58struct Inbox {
59    /// Whether a turn is running for this print.
60    busy: bool,
61    /// What arrived while it was running and it has not taken, oldest first.
62    pending: Vec<Arrival>,
63}
64
65/// Every print's inbox, and how many of its turns have ended.
66#[derive(Debug, Default)]
67struct State {
68    /// One inbox per print that has a turn running.
69    inboxes: BTreeMap<PrintId, Inbox>,
70    /// How many times each print's turn has been released, ever.
71    ended: BTreeMap<PrintId, u64>,
72}
73
74impl State {
75    /// Count one release of the print's turn.
76    fn ended_one(&mut self, print_id: PrintId) {
77        let ended = self.ended.entry(print_id).or_default();
78        *ended = ended.wrapping_add(1);
79    }
80}
81
82/// Every print's inbox, and the signal an arrival raises.
83#[derive(Debug, Default)]
84pub struct Inboxes {
85    /// Every inbox, and how many turns each print has ended.
86    state: Mutex<State>,
87    /// Raised whenever something is handed to a running turn.
88    arrived: Condvar,
89}
90
91impl Inboxes {
92    /// Every inbox, held.
93    fn held(&self) -> MutexGuard<'_, State> {
94        self.state
95            .lock()
96            .unwrap_or_else(std::sync::PoisonError::into_inner)
97    }
98
99    /// How many times the print's turn has been released so far: what
100    /// [`Inboxes::claim_if_idle_since`] is handed, read before the caller
101    /// waits on anything a turn's end may start.
102    pub fn turns_ended(&self, print_id: PrintId) -> u64 {
103        self.held().ended.get(&print_id).copied().unwrap_or(0)
104    }
105
106    /// Claim the print's turn for this arrival, or hand it to the turn already
107    /// running.
108    ///
109    /// Answers `true` when the caller now holds the print's turn and must run
110    /// it, and `false` when the arrival was handed to a turn already running.
111    pub fn claim_or_hand_over(&self, print_id: PrintId, arrival: Arrival) -> bool {
112        let mut state = self.held();
113        let inbox = state.inboxes.entry(print_id).or_default();
114        if inbox.busy {
115            inbox.pending.push(arrival);
116            drop(state);
117            self.arrived.notify_all();
118            return false;
119        }
120        inbox.busy = true;
121        true
122    }
123
124    /// Claim the print's turn only when nothing holds it.
125    ///
126    /// Answers `true` when the caller now holds the print's turn and must run
127    /// it, and `false` — handing nothing over — when a turn is already running
128    /// for it. What the periodic observation claims with: an observation is
129    /// owed to a print nobody is watching, and one queued behind a running turn
130    /// would only pile up beside what that turn is already looking at.
131    pub fn claim_if_idle(&self, print_id: PrintId) -> bool {
132        let mut state = self.held();
133        let inbox = state.inboxes.entry(print_id).or_default();
134        if inbox.busy {
135            return false;
136        }
137        inbox.busy = true;
138        true
139    }
140
141    /// [`Inboxes::claim_if_idle`], refused too when a turn of the print has
142    /// ended since [`Inboxes::turns_ended`] answered `seen`.
143    ///
144    /// What the periodic observation claims with: it waits for the port's idle
145    /// work before it claims, and a turn that ended after that wait may have
146    /// started idle work the wait never saw, which the observation's own turn
147    /// would then cancel. Refused, it is the next round's, which waits for it.
148    pub fn claim_if_idle_since(&self, print_id: PrintId, seen: u64) -> bool {
149        let mut state = self.held();
150        if state.ended.get(&print_id).copied().unwrap_or(0) != seen {
151            return false;
152        }
153        let inbox = state.inboxes.entry(print_id).or_default();
154        if inbox.busy {
155            return false;
156        }
157        inbox.busy = true;
158        true
159    }
160
161    /// What the turn that just returned never took, oldest first, or — when it
162    /// took everything — nothing, with the print's turn released.
163    pub fn next_or_release(&self, print_id: PrintId) -> Option<Vec<Arrival>> {
164        let mut state = self.held();
165        let taken = state
166            .inboxes
167            .get_mut(&print_id)
168            .map(|inbox| core::mem::take(&mut inbox.pending))
169            .filter(|left| !left.is_empty());
170        if taken.is_none() && state.inboxes.remove(&print_id).is_some() {
171            state.ended_one(print_id);
172        }
173        taken
174    }
175
176    /// Hand what a look took back to the print's running turn, ahead of
177    /// anything that arrived since, because the look that took it delivered
178    /// nothing.
179    ///
180    /// A print with no turn running any more has nothing to hand it to: its
181    /// turn released it, and what was waiting went with it.
182    pub fn put_back(&self, print_id: PrintId, taken: Vec<Arrival>) {
183        if taken.is_empty() {
184            return;
185        }
186        let mut state = self.held();
187        if let Some(inbox) = state.inboxes.get_mut(&print_id) {
188            let since = core::mem::replace(&mut inbox.pending, taken);
189            inbox.pending.extend(since);
190            drop(state);
191            self.arrived.notify_all();
192        }
193    }
194
195    /// Release the print's turn, dropping anything still waiting for it.
196    ///
197    /// For a print that has ended: nothing waiting for it can be acted on.
198    pub fn release(&self, print_id: PrintId) {
199        let mut state = self.held();
200        if state.inboxes.remove(&print_id).is_some() {
201            state.ended_one(print_id);
202        }
203    }
204
205    /// Wait up to `wait` for anything to be handed to the print's running
206    /// turn, and take it.
207    ///
208    /// Answers at once when something is already waiting, and answers nothing
209    /// after the whole wait when nothing arrives. A print with no turn running
210    /// has nothing handed to it, because an event for it claims a turn of its
211    /// own instead; a look at it simply waits.
212    pub fn wait_and_take(&self, print_id: PrintId, wait: Duration) -> Vec<Arrival> {
213        let deadline = Instant::now() + wait;
214        let mut state = self.held();
215        loop {
216            if let Some(inbox) = state.inboxes.get_mut(&print_id)
217                && !inbox.pending.is_empty()
218            {
219                return core::mem::take(&mut inbox.pending);
220            }
221            let now = Instant::now();
222            if now >= deadline {
223                return Vec::new();
224            }
225            state = self
226                .arrived
227                .wait_timeout(state, deadline - now)
228                .unwrap_or_else(std::sync::PoisonError::into_inner)
229                .0;
230        }
231    }
232}
233
234#[cfg(test)]
235mod tests {
236    use super::{Arrival, Inboxes};
237    use printobserver_types::{
238        EventBody, EventId, EventKind, EventRecord, EventSource, PrintId, Timestamp,
239    };
240    use std::time::{Duration, Instant};
241
242    /// One arrival, of no kind in particular.
243    fn arrival() -> Arrival {
244        Arrival {
245            frame_captured_at: None,
246            event: EventRecord {
247                id: EventId::new(),
248                print_id: None,
249                source: EventSource::new("obico"),
250                received_at: Timestamp::now(),
251                image: None,
252                body: EventBody {
253                    kind: EventKind::new("obico_failure_alert").expect("a kind"),
254                    payload: printobserver_types::serde_json::Value::Null,
255                },
256                raw: None,
257            },
258            detection: None,
259            camera_frame: super::AlertCameraFrame::NotAsked,
260        }
261    }
262
263    /// A second arrival while a turn runs is handed over rather than claimed,
264    /// is what the turn's next look takes, and the turn is released once
265    /// nothing is left.
266    #[test]
267    fn an_arrival_during_a_turn_is_handed_to_it() {
268        let inboxes = Inboxes::default();
269        let print = PrintId::new();
270        assert!(inboxes.claim_or_hand_over(print, arrival()));
271        assert!(!inboxes.claim_or_hand_over(print, arrival()));
272        assert_eq!(inboxes.wait_and_take(print, Duration::ZERO).len(), 1);
273        assert_eq!(inboxes.next_or_release(print), None);
274        assert!(inboxes.claim_or_hand_over(print, arrival()));
275    }
276
277    /// What a turn never took is handed to the next turn, not dropped, and the
278    /// print stays claimed while that turn runs.
279    #[test]
280    fn what_a_turn_never_took_is_handed_to_the_next() {
281        let inboxes = Inboxes::default();
282        let print = PrintId::new();
283        assert!(inboxes.claim_or_hand_over(print, arrival()));
284        assert!(!inboxes.claim_or_hand_over(print, arrival()));
285        assert_eq!(
286            inboxes.next_or_release(print).map(|left| left.len()),
287            Some(1)
288        );
289        assert!(!inboxes.claim_or_hand_over(print, arrival()));
290    }
291
292    /// Releasing a print drops what was waiting, and its next event claims a
293    /// turn of its own.
294    #[test]
295    fn a_released_print_drops_what_was_waiting() {
296        let inboxes = Inboxes::default();
297        let print = PrintId::new();
298        assert!(inboxes.claim_or_hand_over(print, arrival()));
299        assert!(!inboxes.claim_or_hand_over(print, arrival()));
300        inboxes.release(print);
301        assert!(inboxes.wait_and_take(print, Duration::ZERO).is_empty());
302        assert!(inboxes.claim_or_hand_over(print, arrival()));
303    }
304
305    /// An idle claim takes a print nobody holds and is refused one a turn
306    /// holds, handing nothing to that turn; an event that arrives after it is
307    /// handed to the turn it claimed.
308    #[test]
309    fn an_idle_claim_hands_nothing_to_a_running_turn() {
310        let inboxes = Inboxes::default();
311        let print = PrintId::new();
312        assert!(inboxes.claim_or_hand_over(print, arrival()));
313        assert!(!inboxes.claim_if_idle(print));
314        assert!(inboxes.wait_and_take(print, Duration::ZERO).is_empty());
315        assert_eq!(inboxes.next_or_release(print), None);
316        assert!(inboxes.claim_if_idle(print));
317        assert!(!inboxes.claim_if_idle(print));
318        assert!(!inboxes.claim_or_hand_over(print, arrival()));
319        assert_eq!(inboxes.wait_and_take(print, Duration::ZERO).len(), 1);
320    }
321
322    /// A claim since a count is refused once a turn of the print has ended
323    /// after it, whether the turn released or was released, and taken again
324    /// from a fresh count; another print's turn ending moves nothing.
325    #[test]
326    fn a_claim_since_a_count_is_refused_once_a_turn_ended_after_it() {
327        let inboxes = Inboxes::default();
328        let print = PrintId::new();
329        let other = PrintId::new();
330        let seen = inboxes.turns_ended(print);
331        assert!(inboxes.claim_or_hand_over(print, arrival()));
332        assert!(!inboxes.claim_if_idle_since(print, seen));
333        assert_eq!(inboxes.next_or_release(print), None);
334        assert!(!inboxes.claim_if_idle_since(print, seen));
335        let seen = inboxes.turns_ended(print);
336        assert!(inboxes.claim_or_hand_over(other, arrival()));
337        inboxes.release(other);
338        assert!(inboxes.claim_if_idle_since(print, seen));
339        inboxes.release(print);
340        assert!(!inboxes.claim_if_idle_since(print, seen));
341        assert_eq!(inboxes.turns_ended(print), seen + 1);
342    }
343
344    /// What a look took and could not deliver goes back ahead of what arrived
345    /// since, and a print with no turn running takes nothing back.
346    #[test]
347    fn what_a_look_could_not_deliver_goes_back_first() {
348        let inboxes = Inboxes::default();
349        let print = PrintId::new();
350        assert!(inboxes.claim_or_hand_over(print, arrival()));
351        let first = arrival();
352        assert!(!inboxes.claim_or_hand_over(print, first.clone()));
353        let taken = inboxes.wait_and_take(print, Duration::ZERO);
354        let since = arrival();
355        assert!(!inboxes.claim_or_hand_over(print, since.clone()));
356        inboxes.put_back(print, taken);
357        assert_eq!(
358            inboxes.wait_and_take(print, Duration::ZERO),
359            vec![first, since]
360        );
361        inboxes.release(print);
362        inboxes.put_back(print, vec![arrival()]);
363        assert!(inboxes.claim_or_hand_over(print, arrival()));
364        assert!(inboxes.wait_and_take(print, Duration::ZERO).is_empty());
365    }
366
367    /// A wait returns the moment something is handed over, rather than at the
368    /// end of the wait.
369    #[test]
370    fn a_wait_returns_early_on_an_arrival() {
371        let inboxes = Inboxes::default();
372        let print = PrintId::new();
373        assert!(inboxes.claim_or_hand_over(print, arrival()));
374        let started = Instant::now();
375        std::thread::scope(|scope| {
376            let waiting = scope.spawn(|| inboxes.wait_and_take(print, Duration::from_secs(30)));
377            std::thread::sleep(Duration::from_millis(50));
378            assert!(!inboxes.claim_or_hand_over(print, arrival()));
379            assert_eq!(waiting.join().expect("the wait ends").len(), 1);
380        });
381        assert!(started.elapsed() < Duration::from_secs(10));
382    }
383}