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