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