printobserver_core/observation.rs
1//! A periodic observation of every active print, which no detector asked for.
2//!
3//! A failure detector alerts on what it was trained to see, and a print can go
4//! wrong in ways that stay below every one of its thresholds: firmware pausing
5//! a print and cutting its heater while the host goes on reporting it printing,
6//! a fan cut at a bridge, a wall going thin. Nothing in the machine's state or
7//! the camera's frame is hidden from an agent that looks — so every interval
8//! ([`CoreConfig::observation_interval`](crate::CoreConfig::observation_interval))
9//! each active print is written a [`PeriodicObservationPayload`] event carrying
10//! the printer's telemetry, with the camera's frame as its image, and the turn
11//! that event claims is that print's agent looking at it.
12//!
13//! # Which prints are observed
14//!
15//! The printer's job is read and settled exactly as the listing's is
16//! ([`crate::listing`]): a job found over closes its prints, and a running job
17//! no open print records is adopted. When that read succeeds the print the job
18//! is — when it is one — is the one active print; a printer whose job cannot be
19//! read leaves every open print a candidate, because nothing then says which
20//! of them stopped. A printer reporting one of
21//! [`TERMINAL_STATES`](crate::TERMINAL_STATES) is not printing anything, and an
22//! ended print has nothing left to act on, so neither is observed.
23//!
24//! # No pile-up
25//!
26//! An observation claims a print's turn only when nothing holds it
27//! ([`Inboxes::claim_if_idle`](crate::Inboxes::claim_if_idle)). A print whose
28//! turn is running — on an alert, or on the last observation — is being
29//! watched already, and is given no observation to queue behind it; so at most
30//! one observation per print is ever outstanding, and every turn the agent is
31//! given still runs under the same one-agent-per-print rule and the same action
32//! policy, `safety.agent_min_interval_s` included.
33//!
34//! # The reads precede the append
35//!
36//! Everywhere else the event append is the first thing the loop does
37//! ([`crate::events`]), because an alert arrives from outside and must be in
38//! the history before anything can fail on its behalf. An observation is
39//! raised here, and what it records *is* the reads, so they are taken first and
40//! the event carries them; a read that failed is then recorded against the
41//! event as a port failure, as the loop records one, and the camera is asked
42//! for its frame only once the event is there to record a refusal against.
43
44use printobserver_printer_api::{JobSnapshot, PrinterError, PrinterSnapshot};
45use printobserver_types::{EventBody, PrintId};
46
47use crate::error::CoreError;
48use crate::events::{PendingTurn, TERMINAL_STATES};
49use crate::inbox::Arrival;
50use crate::kinds::{PeriodicObservationPayload, PortFailureSite};
51use crate::records::PrintRecord;
52use crate::supervisor::Supervisor;
53
54/// What one round of observations claimed, and what it could not write down.
55#[derive(Debug, Default)]
56pub struct Observed {
57 /// The turns the observations claimed, each to be run by
58 /// [`Supervisor::run_supervision`]: a turn claimed and never run leaves its
59 /// print claimed.
60 pub turns: Vec<PendingTurn>,
61 /// Each print whose observation the store would not write down, with the
62 /// store's own error. Such a print claimed no turn, and the next round
63 /// observes it again.
64 pub refused: Vec<(PrintId, CoreError)>,
65}
66
67impl Supervisor {
68 /// Observe every active print nobody is watching, and answer the turns
69 /// those observations claimed.
70 ///
71 /// One print's observation that could not be written down is answered in
72 /// [`Observed::refused`] and stops no other: every turn the round claimed
73 /// is answered, because a claimed turn nobody runs is a print no later
74 /// event could reach.
75 ///
76 /// # Errors
77 ///
78 /// Returns the store's own error when the open prints could not be read or
79 /// settled, before any print was claimed.
80 pub async fn observe_active_prints(&self) -> Result<Observed, CoreError> {
81 let mut observed = Observed::default();
82 for print in self.prints_to_observe().await? {
83 let print_id = print.id;
84 match self.observe(print).await {
85 Ok(Some(turn)) => observed.turns.push(turn),
86 Ok(None) => {}
87 Err(error) => observed.refused.push((print_id, error)),
88 }
89 }
90 Ok(observed)
91 }
92
93 /// The open prints an observation is owed to, once the printer's job has
94 /// settled them.
95 async fn prints_to_observe(&self) -> Result<Vec<PrintRecord>, CoreError> {
96 let resolving = self.resolving().await;
97 let active = match self.observe_job().await {
98 Some(observed) => Some(self.settle_and_adopt(&observed).await?),
99 None => None,
100 };
101 drop(resolving);
102 let open = self.stores().prints.open_prints().await?;
103 Ok(match active {
104 Some(running) => open
105 .into_iter()
106 .filter(|print| Some(print.id) == running)
107 .collect(),
108 None => open,
109 })
110 }
111
112 /// Observe one print, when it is printing and nobody is watching it.
113 async fn observe(&self, print: PrintRecord) -> Result<Option<PendingTurn>, CoreError> {
114 let printer = self.read_snapshot().await;
115 if printer
116 .as_ref()
117 .is_ok_and(|snapshot| TERMINAL_STATES.contains(&snapshot.connection))
118 {
119 return Ok(None);
120 }
121 let job = self.read_job().await;
122 if !self.inboxes().claim_if_idle(print.id) {
123 return Ok(None);
124 }
125 match self.write_observation_down(&print, printer, job).await {
126 Ok(arrival) => Ok(Some(PendingTurn::new(print, arrival, Vec::new()))),
127 Err(error) => {
128 // Anything handed to the print while it was claimed is owed a
129 // turn of its own, and is answered as one rather than dropped.
130 let Some(mut left) = self.inboxes().next_or_release(print.id) else {
131 return Err(error);
132 };
133 let latest = left.pop().ok_or(error)?;
134 Ok(Some(PendingTurn::new(print, latest, left)))
135 }
136 }
137 }
138
139 /// Write one observation down, recording a read that failed against it,
140 /// and take the camera's frame as its image.
141 async fn write_observation_down(
142 &self,
143 print: &PrintRecord,
144 printer: Result<PrinterSnapshot, PrinterError>,
145 job: Result<JobSnapshot, PrinterError>,
146 ) -> Result<Arrival, CoreError> {
147 let payload = PeriodicObservationPayload {
148 interval_s: self.config().observation_interval.as_secs(),
149 printer: printer.as_ref().ok().cloned(),
150 job: job.as_ref().ok().cloned(),
151 };
152 let mut event = self
153 .append_system_event(print.id, EventBody::of(&payload)?)
154 .await?;
155 if let Err(error) = printer {
156 self.record_port_failure(
157 print.id,
158 event.id,
159 PortFailureSite::PrinterSnapshot,
160 error.to_string(),
161 )
162 .await;
163 }
164 if let Err(error) = job {
165 self.record_port_failure(
166 print.id,
167 event.id,
168 PortFailureSite::PrinterJob,
169 error.to_string(),
170 )
171 .await;
172 }
173 if let Some(url) = &self.config().camera_snapshot_url {
174 event.image = self
175 .take_frame(print.id, &event, url.as_str().to_owned())
176 .await;
177 }
178 Ok(Arrival {
179 event,
180 detection: None,
181 })
182 }
183}