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 the signal an arrival raises.
66#[derive(Debug, Default)]
67pub struct Inboxes {
68    /// One inbox per print that has a turn running.
69    state: Mutex<BTreeMap<PrintId, Inbox>>,
70    /// Raised whenever something is handed to a running turn.
71    arrived: Condvar,
72}
73
74impl Inboxes {
75    /// Every inbox, held.
76    fn held(&self) -> MutexGuard<'_, BTreeMap<PrintId, Inbox>> {
77        self.state
78            .lock()
79            .unwrap_or_else(std::sync::PoisonError::into_inner)
80    }
81
82    /// Claim the print's turn for this arrival, or hand it to the turn already
83    /// running.
84    ///
85    /// Answers `true` when the caller now holds the print's turn and must run
86    /// it, and `false` when the arrival was handed to a turn already running.
87    pub fn claim_or_hand_over(&self, print_id: PrintId, arrival: Arrival) -> bool {
88        let mut state = self.held();
89        let inbox = state.entry(print_id).or_default();
90        if inbox.busy {
91            inbox.pending.push(arrival);
92            drop(state);
93            self.arrived.notify_all();
94            return false;
95        }
96        inbox.busy = true;
97        true
98    }
99
100    /// Claim the print's turn only when nothing holds it.
101    ///
102    /// Answers `true` when the caller now holds the print's turn and must run
103    /// it, and `false` — handing nothing over — when a turn is already running
104    /// for it. What the periodic observation claims with: an observation is
105    /// owed to a print nobody is watching, and one queued behind a running turn
106    /// would only pile up beside what that turn is already looking at.
107    pub fn claim_if_idle(&self, print_id: PrintId) -> bool {
108        let mut state = self.held();
109        let inbox = state.entry(print_id).or_default();
110        if inbox.busy {
111            return false;
112        }
113        inbox.busy = true;
114        true
115    }
116
117    /// What the turn that just returned never took, oldest first, or — when it
118    /// took everything — nothing, with the print's turn released.
119    pub fn next_or_release(&self, print_id: PrintId) -> Option<Vec<Arrival>> {
120        let mut state = self.held();
121        let taken = state
122            .get_mut(&print_id)
123            .map(|inbox| core::mem::take(&mut inbox.pending))
124            .filter(|left| !left.is_empty());
125        if taken.is_none() {
126            state.remove(&print_id);
127        }
128        taken
129    }
130
131    /// Hand what a look took back to the print's running turn, ahead of
132    /// anything that arrived since, because the look that took it delivered
133    /// nothing.
134    ///
135    /// A print with no turn running any more has nothing to hand it to: its
136    /// turn released it, and what was waiting went with it.
137    pub fn put_back(&self, print_id: PrintId, taken: Vec<Arrival>) {
138        if taken.is_empty() {
139            return;
140        }
141        let mut state = self.held();
142        if let Some(inbox) = state.get_mut(&print_id) {
143            let since = core::mem::replace(&mut inbox.pending, taken);
144            inbox.pending.extend(since);
145            drop(state);
146            self.arrived.notify_all();
147        }
148    }
149
150    /// Release the print's turn, dropping anything still waiting for it.
151    ///
152    /// For a print that has ended: nothing waiting for it can be acted on.
153    pub fn release(&self, print_id: PrintId) {
154        self.held().remove(&print_id);
155    }
156
157    /// Wait up to `wait` for anything to be handed to the print's running
158    /// turn, and take it.
159    ///
160    /// Answers at once when something is already waiting, and answers nothing
161    /// after the whole wait when nothing arrives. A print with no turn running
162    /// has nothing handed to it, because an event for it claims a turn of its
163    /// own instead; a look at it simply waits.
164    pub fn wait_and_take(&self, print_id: PrintId, wait: Duration) -> Vec<Arrival> {
165        let deadline = Instant::now() + wait;
166        let mut state = self.held();
167        loop {
168            if let Some(inbox) = state.get_mut(&print_id)
169                && !inbox.pending.is_empty()
170            {
171                return core::mem::take(&mut inbox.pending);
172            }
173            let now = Instant::now();
174            if now >= deadline {
175                return Vec::new();
176            }
177            state = self
178                .arrived
179                .wait_timeout(state, deadline - now)
180                .unwrap_or_else(std::sync::PoisonError::into_inner)
181                .0;
182        }
183    }
184}
185
186#[cfg(test)]
187mod tests {
188    use super::{Arrival, Inboxes};
189    use printobserver_types::{
190        EventBody, EventId, EventKind, EventRecord, EventSource, PrintId, Timestamp,
191    };
192    use std::time::{Duration, Instant};
193
194    /// One arrival, of no kind in particular.
195    fn arrival() -> Arrival {
196        Arrival {
197            frame_captured_at: None,
198            event: EventRecord {
199                id: EventId::new(),
200                print_id: None,
201                source: EventSource::new("obico"),
202                received_at: Timestamp::now(),
203                image: None,
204                body: EventBody {
205                    kind: EventKind::new("obico_failure_alert").expect("a kind"),
206                    payload: printobserver_types::serde_json::Value::Null,
207                },
208                raw: None,
209            },
210            detection: None,
211            camera_frame: super::AlertCameraFrame::NotAsked,
212        }
213    }
214
215    /// A second arrival while a turn runs is handed over rather than claimed,
216    /// is what the turn's next look takes, and the turn is released once
217    /// nothing is left.
218    #[test]
219    fn an_arrival_during_a_turn_is_handed_to_it() {
220        let inboxes = Inboxes::default();
221        let print = PrintId::new();
222        assert!(inboxes.claim_or_hand_over(print, arrival()));
223        assert!(!inboxes.claim_or_hand_over(print, arrival()));
224        assert_eq!(inboxes.wait_and_take(print, Duration::ZERO).len(), 1);
225        assert_eq!(inboxes.next_or_release(print), None);
226        assert!(inboxes.claim_or_hand_over(print, arrival()));
227    }
228
229    /// What a turn never took is handed to the next turn, not dropped, and the
230    /// print stays claimed while that turn runs.
231    #[test]
232    fn what_a_turn_never_took_is_handed_to_the_next() {
233        let inboxes = Inboxes::default();
234        let print = PrintId::new();
235        assert!(inboxes.claim_or_hand_over(print, arrival()));
236        assert!(!inboxes.claim_or_hand_over(print, arrival()));
237        assert_eq!(
238            inboxes.next_or_release(print).map(|left| left.len()),
239            Some(1)
240        );
241        assert!(!inboxes.claim_or_hand_over(print, arrival()));
242    }
243
244    /// Releasing a print drops what was waiting, and its next event claims a
245    /// turn of its own.
246    #[test]
247    fn a_released_print_drops_what_was_waiting() {
248        let inboxes = Inboxes::default();
249        let print = PrintId::new();
250        assert!(inboxes.claim_or_hand_over(print, arrival()));
251        assert!(!inboxes.claim_or_hand_over(print, arrival()));
252        inboxes.release(print);
253        assert!(inboxes.wait_and_take(print, Duration::ZERO).is_empty());
254        assert!(inboxes.claim_or_hand_over(print, arrival()));
255    }
256
257    /// An idle claim takes a print nobody holds and is refused one a turn
258    /// holds, handing nothing to that turn; an event that arrives after it is
259    /// handed to the turn it claimed.
260    #[test]
261    fn an_idle_claim_hands_nothing_to_a_running_turn() {
262        let inboxes = Inboxes::default();
263        let print = PrintId::new();
264        assert!(inboxes.claim_or_hand_over(print, arrival()));
265        assert!(!inboxes.claim_if_idle(print));
266        assert!(inboxes.wait_and_take(print, Duration::ZERO).is_empty());
267        assert_eq!(inboxes.next_or_release(print), None);
268        assert!(inboxes.claim_if_idle(print));
269        assert!(!inboxes.claim_if_idle(print));
270        assert!(!inboxes.claim_or_hand_over(print, arrival()));
271        assert_eq!(inboxes.wait_and_take(print, Duration::ZERO).len(), 1);
272    }
273
274    /// What a look took and could not deliver goes back ahead of what arrived
275    /// since, and a print with no turn running takes nothing back.
276    #[test]
277    fn what_a_look_could_not_deliver_goes_back_first() {
278        let inboxes = Inboxes::default();
279        let print = PrintId::new();
280        assert!(inboxes.claim_or_hand_over(print, arrival()));
281        let first = arrival();
282        assert!(!inboxes.claim_or_hand_over(print, first.clone()));
283        let taken = inboxes.wait_and_take(print, Duration::ZERO);
284        let since = arrival();
285        assert!(!inboxes.claim_or_hand_over(print, since.clone()));
286        inboxes.put_back(print, taken);
287        assert_eq!(
288            inboxes.wait_and_take(print, Duration::ZERO),
289            vec![first, since]
290        );
291        inboxes.release(print);
292        inboxes.put_back(print, vec![arrival()]);
293        assert!(inboxes.claim_or_hand_over(print, arrival()));
294        assert!(inboxes.wait_and_take(print, Duration::ZERO).is_empty());
295    }
296
297    /// A wait returns the moment something is handed over, rather than at the
298    /// end of the wait.
299    #[test]
300    fn a_wait_returns_early_on_an_arrival() {
301        let inboxes = Inboxes::default();
302        let print = PrintId::new();
303        assert!(inboxes.claim_or_hand_over(print, arrival()));
304        let started = Instant::now();
305        std::thread::scope(|scope| {
306            let waiting = scope.spawn(|| inboxes.wait_and_take(print, Duration::from_secs(30)));
307            std::thread::sleep(Duration::from_millis(50));
308            assert!(!inboxes.claim_or_hand_over(print, arrival()));
309            assert_eq!(waiting.join().expect("the wait ends").len(), 1);
310        });
311        assert!(started.elapsed() < Duration::from_secs(10));
312    }
313}