Skip to main content

printobserver_core/
detector.rs

1//! A print the detector paused, and the resume an adjustment earns it.
2//!
3//! A detector that pauses a print reacts faster than any turn can, so the
4//! pause is left to it; what it cannot do is decide whether the print can be
5//! saved. When the supervising agent decides it can — and asks for an
6//! adjustment while the print is still held by the detector's pause — the
7//! adjustment is applied at once and the print is resumed with it, so that the
8//! change takes effect as the print moves again rather than waiting for a
9//! person to notice the pause.
10//!
11//! # The resume is the supervisor's, through the policy
12//!
13//! The agent is not granted resume: a print it may resume is a print whose
14//! pause it may overrule, and a pause a person made is not one it should.
15//! The resume here is requested as [`Actor::System`], through
16//! [`Supervisor::request_action`] like every other action, so it is recorded
17//! with its reason and refused — and the print left paused — when the envelope
18//! does not grant the system resume.
19//!
20//! # When the resume happens
21//!
22//! [`CoreConfig::detector_resume_grace`](crate::CoreConfig) after the agent's
23//! last such adjustment, or when its turn ends, whichever comes first — so
24//! that two or three changes asked for one after the other reach the print
25//! together. An agent that acknowledges the detection with the disposition
26//! `stop` has decided a person should look, and the pause is then left alone;
27//! so is one somebody else has already resumed or cancelled.
28//!
29//! # The detector is told
30//!
31//! Once the print has resumed, the detector is told its detection was handled,
32//! which is what re-arms it for the rest of the print; a failure to tell it is
33//! recorded against the detection's own event.
34
35use std::collections::BTreeMap;
36
37use printobserver_types::{EventId, PrintId, Timestamp};
38use printobserver_vision_api::Detection;
39
40use crate::clock::plus_seconds;
41use crate::kinds::PortFailureSite;
42use crate::records::{Actor, PrintAction};
43use crate::supervisor::Supervisor;
44
45/// One print the detector paused, and what the agent has asked of it since.
46#[derive(Debug, Clone, PartialEq)]
47pub(crate) struct DetectorPause {
48    /// The event the detection arrived as.
49    pub event_id: EventId,
50    /// What the detector did.
51    pub detection: Detection,
52    /// The adjustments the agent asked for under the pause, and the resume
53    /// they earned; absent until it asks for one.
54    pub adjusted: Option<Adjusted>,
55}
56
57/// The adjustments asked for under one detector's pause, and the resume they
58/// earned: there is no resume without an adjustment, and no adjustment
59/// without a resume.
60#[derive(Debug, Clone, PartialEq)]
61pub(crate) struct Adjusted {
62    /// The reason of the first adjustment asked for.
63    pub first: String,
64    /// The reasons of every adjustment asked for after it, in order.
65    pub later: Vec<String>,
66    /// When the print is to be resumed: the grace after the last of them.
67    pub resume_due: Timestamp,
68}
69
70impl Adjusted {
71    /// Every reason, in the order the adjustments were asked for.
72    fn reasons(&self) -> Vec<&str> {
73        core::iter::once(self.first.as_str())
74            .chain(self.later.iter().map(String::as_str))
75            .collect()
76    }
77}
78
79/// Every print the detector has paused and nobody has resumed yet.
80pub(crate) type DetectorPauses = BTreeMap<PrintId, DetectorPause>;
81
82impl Supervisor {
83    /// Remember that the detector paused one print, under one event.
84    ///
85    /// A print whose pause is already held keeps what the agent has asked of
86    /// it — and the resume that earned — and the newer detection is the one
87    /// acknowledged once it resumes: a detector that says so again has not
88    /// undone the agent's adjustment.
89    pub(crate) fn note_detector_pause(
90        &self,
91        print_id: PrintId,
92        event_id: EventId,
93        detection: Detection,
94    ) {
95        self.detector_pauses()
96            .entry(print_id)
97            .and_modify(|held| {
98                held.event_id = event_id;
99                held.detection = detection;
100            })
101            .or_insert(DetectorPause {
102                event_id,
103                detection,
104                adjusted: None,
105            });
106    }
107
108    /// Note an adjustment the agent asked for while the detector's pause held
109    /// the print, and schedule the resume it earns.
110    pub(crate) fn note_adjustment_while_paused(&self, print_id: PrintId, reason: &str) {
111        let now = self.clock().now();
112        let grace =
113            i64::try_from(self.config().detector_resume_grace.as_secs()).unwrap_or(i64::MAX);
114        let due = plus_seconds(now, grace).unwrap_or(now);
115        if let Some(pause) = self.detector_pauses().get_mut(&print_id) {
116            match &mut pause.adjusted {
117                Some(adjusted) => {
118                    adjusted.later.push(reason.to_owned());
119                    adjusted.resume_due = due;
120                }
121                None => {
122                    pause.adjusted = Some(Adjusted {
123                        first: reason.to_owned(),
124                        later: Vec::new(),
125                        resume_due: due,
126                    });
127                }
128            }
129        }
130    }
131
132    /// Leave the detector's pause alone from now on: the agent decided a
133    /// person should look, somebody else moved the print on, or it ended.
134    pub(crate) fn forget_detector_pause(&self, print_id: PrintId) {
135        self.detector_pauses().remove(&print_id);
136    }
137
138    /// Whether the detector's pause is one this supervisor is still holding
139    /// for one print.
140    pub(crate) fn detector_paused(&self, print_id: PrintId) -> bool {
141        self.detector_pauses().contains_key(&print_id)
142    }
143
144    /// Resume every print whose resume has come due.
145    pub async fn resume_due_detector_pauses(&self) {
146        let now = self.clock().now();
147        let due: Vec<(PrintId, DetectorPause)> = {
148            let mut pauses = self.detector_pauses();
149            let ids: Vec<PrintId> = pauses
150                .iter()
151                .filter(|(_, pause)| {
152                    pause
153                        .adjusted
154                        .as_ref()
155                        .is_some_and(|adjusted| adjusted.resume_due <= now)
156                })
157                .map(|(id, _)| *id)
158                .collect();
159            ids.into_iter()
160                .filter_map(|id| pauses.remove(&id).map(|pause| (id, pause)))
161                .collect()
162        };
163        for (print_id, pause) in due {
164            self.resume_detector_pause(print_id, pause).await;
165        }
166    }
167
168    /// Resume one print at once when the agent adjusted it under the
169    /// detector's pause, because the turn that asked has ended.
170    pub(crate) async fn resume_adjusted_detector_pause(&self, print_id: PrintId) {
171        let taken = {
172            let mut pauses = self.detector_pauses();
173            match pauses.get(&print_id) {
174                Some(pause) if pause.adjusted.is_some() => pauses.remove(&print_id),
175                _ => None,
176            }
177        };
178        if let Some(pause) = taken {
179            self.resume_detector_pause(print_id, pause).await;
180        }
181    }
182
183    /// Resume one print the detector paused, and tell the detector.
184    ///
185    /// A resume the policy refuses, or the printer does, is recorded by the
186    /// request itself, and the detector is then told nothing: the print is
187    /// still paused, and a re-armed detector over a paused print would alert
188    /// on nothing.
189    async fn resume_detector_pause(&self, print_id: PrintId, pause: DetectorPause) {
190        let reason = format!(
191            "the detector paused this print and the supervising agent adjusted it while \
192             paused ({}); resuming so the adjustment takes effect",
193            pause
194                .adjusted
195                .as_ref()
196                .map(|adjusted| adjusted.reasons().join("; "))
197                .unwrap_or_default()
198        );
199        let resumed = self
200            .request_action(
201                print_id,
202                PrintAction::Resume {
203                    reason,
204                    actor: Actor::System,
205                },
206            )
207            .await;
208        if !resumed.is_ok_and(|outcome| matches!(outcome.executed, Some(Ok(())))) {
209            return;
210        }
211        if let Err(error) = self.vision().clear_detection(pause.detection).await {
212            self.record_port_failure(
213                print_id,
214                pause.event_id,
215                PortFailureSite::DetectorAcknowledgement,
216                error.to_string(),
217            )
218            .await;
219        }
220    }
221}