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, and the frame, 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. The camera is asked for its frame before the event
41//! is written too, and the event is written together with that frame as its
42//! image in one store write, so anybody following the log — the `events` read,
43//! `printobserver watch` — reads the check with its frame the first time it
44//! reads it, rather than an event with no image that nothing sends again. A
45//! read that failed, a camera that would not answer however often it was
46//! asked ([`crate::look`]), and a store that would not keep the frame are each
47//! recorded against the event once it is written, as a port failure, as the
48//! loop records one. A camera that gives only bad frames is recorded as a
49//! `camera_degraded` after the observation, and that is the event the turn is
50//! given, so the agent is told there is no frame rather than handed one.
51
52use printobserver_printer_api::{JobSnapshot, PrinterError, PrinterSnapshot};
53use printobserver_types::{EventBody, PrintId};
54
55use crate::error::CoreError;
56use crate::events::{PendingTurn, TERMINAL_STATES};
57use crate::inbox::Arrival;
58use crate::kinds::{PeriodicObservationPayload, PortFailureSite};
59use crate::look::Frame;
60use crate::records::PrintRecord;
61use crate::supervisor::Supervisor;
62
63/// What one round of observations claimed, and what it could not write down.
64#[derive(Debug, Default)]
65pub struct Observed {
66 /// The turns the observations claimed, each to be run by
67 /// [`Supervisor::run_supervision`]: a turn claimed and never run leaves its
68 /// print claimed.
69 pub turns: Vec<PendingTurn>,
70 /// Each print whose observation the store would not write down, with the
71 /// store's own error. Such a print claimed no turn, and the next round
72 /// observes it again.
73 pub refused: Vec<(PrintId, CoreError)>,
74}
75
76impl Supervisor {
77 /// Observe every active print nobody is watching, and answer the turns
78 /// those observations claimed.
79 ///
80 /// One print's observation that could not be written down is answered in
81 /// [`Observed::refused`] and stops no other: every turn the round claimed
82 /// is answered, because a claimed turn nobody runs is a print no later
83 /// event could reach.
84 ///
85 /// # Errors
86 ///
87 /// Returns the store's own error when the open prints could not be read or
88 /// settled, before any print was claimed.
89 pub async fn observe_active_prints(&self) -> Result<Observed, CoreError> {
90 let mut observed = Observed::default();
91 for print in self.prints_to_observe().await? {
92 let print_id = print.id;
93 match self.observe(print).await {
94 Ok(Some(turn)) => observed.turns.push(turn),
95 Ok(None) => {}
96 Err(error) => observed.refused.push((print_id, error)),
97 }
98 }
99 Ok(observed)
100 }
101
102 /// The open prints an observation is owed to, once the printer's job has
103 /// settled them.
104 async fn prints_to_observe(&self) -> Result<Vec<PrintRecord>, CoreError> {
105 let resolving = self.resolving().await;
106 let active = match self.observe_job().await {
107 Some(observed) => Some(self.settle_and_adopt(&observed).await?),
108 None => None,
109 };
110 drop(resolving);
111 let open = self.stores().prints.open_prints().await?;
112 Ok(match active {
113 Some(running) => open
114 .into_iter()
115 .filter(|print| Some(print.id) == running)
116 .collect(),
117 None => open,
118 })
119 }
120
121 /// Observe one print, when it is printing and nobody is watching it.
122 async fn observe(&self, print: PrintRecord) -> Result<Option<PendingTurn>, CoreError> {
123 let printer = self.read_snapshot().await;
124 if printer
125 .as_ref()
126 .is_ok_and(|snapshot| TERMINAL_STATES.contains(&snapshot.connection))
127 {
128 return Ok(None);
129 }
130 let job = self.read_job().await;
131 if !self.inboxes().claim_if_idle(print.id) {
132 return Ok(None);
133 }
134 match self.write_observation_down(&print, printer, job).await {
135 Ok(arrival) => Ok(Some(PendingTurn::new(print, arrival, Vec::new()))),
136 Err(error) => {
137 // Anything handed to the print while it was claimed is owed a
138 // turn of its own, and is answered as one rather than dropped.
139 let Some(mut left) = self.inboxes().next_or_release(print.id) else {
140 return Err(error);
141 };
142 let latest = left.pop().ok_or(error)?;
143 Ok(Some(PendingTurn::new(print, latest, left)))
144 }
145 }
146 }
147
148 /// Take the camera's frame, write one observation down with it as its
149 /// image, and record a read that failed against it.
150 async fn write_observation_down(
151 &self,
152 print: &PrintRecord,
153 printer: Result<PrinterSnapshot, PrinterError>,
154 job: Result<JobSnapshot, PrinterError>,
155 ) -> Result<Arrival, CoreError> {
156 let payload = PeriodicObservationPayload {
157 interval_s: self.config().observation_interval.as_secs(),
158 printer: printer.as_ref().ok().cloned(),
159 job: job.as_ref().ok().cloned(),
160 };
161 let fetched = self.fetch_configured_frame(Some(print.id)).await;
162 // The observation keeps the telemetry it read whatever the camera
163 // gave; a camera giving only bad frames is the turn's event instead.
164 let (fetched, degraded) = match fetched {
165 Some((_, Frame::Degraded(degraded))) => (None, Some(degraded)),
166 fetched => (fetched, None),
167 };
168 let event = self
169 .write_with_frame(Some(print.id), &payload, fetched)
170 .await?;
171 if let Err(error) = printer {
172 self.record_port_failure(
173 print.id,
174 event.id,
175 PortFailureSite::PrinterSnapshot,
176 error.to_string(),
177 )
178 .await;
179 }
180 if let Err(error) = job {
181 self.record_port_failure(
182 print.id,
183 event.id,
184 PortFailureSite::PrinterJob,
185 error.to_string(),
186 )
187 .await;
188 }
189 if let Some(degraded) = degraded {
190 let degraded = self
191 .append_system_event(print.id, EventBody::of(°raded)?)
192 .await?;
193 return Ok(Arrival {
194 event: degraded,
195 detection: None,
196 });
197 }
198 Ok(Arrival {
199 event,
200 detection: None,
201 })
202 }
203}