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