Skip to main content

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//! # An idle compaction of the session ends first
35//!
36//! A supervisor port may compact a print's session while no turn of it runs
37//! ([`SupervisorPort::idle_work_ended`](printobserver_supervisor_api::SupervisorPort::idle_work_ended)),
38//! and every other event's turn cancels that compaction at once. A scheduled
39//! check alone waits for it to end, bounded by the compaction's own timeout,
40//! because it is the turn that continues that session on the port's own
41//! cadence: cancelling it would leave the session as large as it was and the
42//! next gap no longer.
43//!
44//! # The detector's record is read first
45//!
46//! Each round begins by reading the failure detector's own record of the
47//! active print, when the composition root installed something to read it
48//! with ([`crate::scoring`]), so that every turn the round claims reads the
49//! detector's status as it stands now. A read that failed is recorded against
50//! each observation the round writes, as a port failure.
51//!
52//! # The reads, and the frame, precede the append
53//!
54//! Everywhere else the event append is the first thing the loop does
55//! ([`crate::events`]), because an alert arrives from outside and must be in
56//! the history before anything can fail on its behalf. An observation is
57//! raised here, and what it records *is* the reads, so they are taken first and
58//! the event carries them. The camera is asked for its frame before the event
59//! is written too, and the event is written together with that frame as its
60//! image in one store write, so anybody following the log — the `events` read,
61//! `printobserver watch` — reads the check with its frame the first time it
62//! reads it, rather than an event with no image that nothing sends again. A
63//! read that failed, a camera that would not answer however often it was
64//! asked ([`crate::look`]), and a store that would not keep the frame are each
65//! recorded against the event once it is written, as a port failure, as the
66//! loop records one. A camera that gives only bad frames is recorded as a
67//! `camera_degraded` after the observation, and that is the event the turn is
68//! given, so the agent is told there is no frame rather than handed one.
69
70use printobserver_printer_api::{JobSnapshot, PrinterError, PrinterSnapshot};
71use printobserver_types::{EventBody, PrintId};
72
73use crate::error::CoreError;
74use crate::events::{PendingTurn, TERMINAL_STATES};
75use crate::inbox::Arrival;
76use crate::kinds::{PeriodicObservationPayload, PortFailureSite};
77use crate::look::Frame;
78use crate::records::PrintRecord;
79use crate::supervisor::Supervisor;
80
81/// What one round of observations claimed, and what it could not write down.
82#[derive(Debug, Default)]
83pub struct Observed {
84    /// The turns the observations claimed, each to be run by
85    /// [`Supervisor::run_supervision`]: a turn claimed and never run leaves its
86    /// print claimed.
87    pub turns: Vec<PendingTurn>,
88    /// Each print whose observation the store would not write down, with the
89    /// store's own error. Such a print claimed no turn, and the next round
90    /// observes it again.
91    pub refused: Vec<(PrintId, CoreError)>,
92}
93
94impl Supervisor {
95    /// Observe every active print nobody is watching, and answer the turns
96    /// those observations claimed.
97    ///
98    /// One print's observation that could not be written down is answered in
99    /// [`Observed::refused`] and stops no other: every turn the round claimed
100    /// is answered, because a claimed turn nobody runs is a print no later
101    /// event could reach.
102    ///
103    /// # Errors
104    ///
105    /// Returns the store's own error when the open prints could not be read or
106    /// settled, before any print was claimed.
107    pub async fn observe_active_prints(&self) -> Result<Observed, CoreError> {
108        let mut observed = Observed::default();
109        let prints = self.prints_to_observe().await?;
110        let scoring_failed = self.read_scoring(&prints).await;
111        for print in prints {
112            let print_id = print.id;
113            match self.observe(print, scoring_failed.as_deref()).await {
114                Ok(Some(turn)) => observed.turns.push(turn),
115                Ok(None) => {}
116                Err(error) => observed.refused.push((print_id, error)),
117            }
118        }
119        Ok(observed)
120    }
121
122    /// The open prints an observation is owed to, once the printer's job has
123    /// settled them.
124    async fn prints_to_observe(&self) -> Result<Vec<PrintRecord>, CoreError> {
125        let resolving = self.resolving().await;
126        let active = match self.observe_job().await {
127            Some(observed) => Some(self.settle_and_adopt(&observed).await?),
128            None => None,
129        };
130        drop(resolving);
131        let open = self.stores().prints.open_prints().await?;
132        Ok(match active {
133            Some(running) => open
134                .into_iter()
135                .filter(|print| Some(print.id) == running)
136                .collect(),
137            None => open,
138        })
139    }
140
141    /// Observe one print, when it is printing and nobody is watching it.
142    async fn observe(
143        &self,
144        print: PrintRecord,
145        scoring_failed: Option<&str>,
146    ) -> Result<Option<PendingTurn>, CoreError> {
147        // A scheduled check continues the session it is about, so it lets an
148        // idle compaction of that session end rather than cancel it, and reads
149        // the printer once it has.
150        // A wait that could not be taken leaves the check to run at once.
151        let _ = self.agent().idle_work_ended(print.id).await;
152        let printer = self.read_snapshot().await;
153        if printer
154            .as_ref()
155            .is_ok_and(|snapshot| TERMINAL_STATES.contains(&snapshot.connection))
156        {
157            return Ok(None);
158        }
159        let job = self.read_job().await;
160        if !self.inboxes().claim_if_idle(print.id) {
161            return Ok(None);
162        }
163        match self
164            .write_observation_down(&print, printer, job, scoring_failed)
165            .await
166        {
167            Ok(arrival) => Ok(Some(PendingTurn::new(print, arrival, Vec::new()))),
168            Err(error) => {
169                // Anything handed to the print while it was claimed is owed a
170                // turn of its own, and is answered as one rather than dropped.
171                let Some(mut left) = self.inboxes().next_or_release(print.id) else {
172                    return Err(error);
173                };
174                let latest = left.pop().ok_or(error)?;
175                Ok(Some(PendingTurn::new(print, latest, left)))
176            }
177        }
178    }
179
180    /// Take the camera's frame, write one observation down with it as its
181    /// image, and record a read that failed against it.
182    async fn write_observation_down(
183        &self,
184        print: &PrintRecord,
185        printer: Result<PrinterSnapshot, PrinterError>,
186        job: Result<JobSnapshot, PrinterError>,
187        scoring_failed: Option<&str>,
188    ) -> Result<Arrival, CoreError> {
189        let fetched = self.fetch_configured_frame(Some(print.id)).await;
190        let payload = PeriodicObservationPayload {
191            interval_s: self.config().observation_interval.as_secs(),
192            printer: printer.as_ref().ok().cloned(),
193            job: job.as_ref().ok().cloned(),
194            frame_captured_at: self.frame_captured_at(fetched.as_ref()),
195        };
196        // The observation keeps the telemetry it read whatever the camera
197        // gave; a camera giving only bad frames is the turn's event instead.
198        let (fetched, degraded) = match fetched {
199            Some((_, Frame::Degraded(degraded))) => (None, Some(degraded)),
200            fetched => (fetched, None),
201        };
202        let event = self
203            .write_with_frame(Some(print.id), &payload, fetched)
204            .await?;
205        if let Err(error) = printer {
206            self.record_port_failure(
207                print.id,
208                event.id,
209                PortFailureSite::PrinterSnapshot,
210                error.to_string(),
211            )
212            .await;
213        }
214        if let Err(error) = job {
215            self.record_port_failure(
216                print.id,
217                event.id,
218                PortFailureSite::PrinterJob,
219                error.to_string(),
220            )
221            .await;
222        }
223        if let Some(detail) = scoring_failed {
224            self.record_port_failure(
225                print.id,
226                event.id,
227                PortFailureSite::DetectorScoringRead,
228                detail.to_owned(),
229            )
230            .await;
231        }
232        if let Some(degraded) = degraded {
233            let degraded = self
234                .append_system_event(print.id, EventBody::of(&degraded)?)
235                .await?;
236            return Ok(Arrival {
237                event: degraded,
238                detection: None,
239                frame_captured_at: None,
240                camera_frame: crate::inbox::AlertCameraFrame::NotAsked,
241            });
242        }
243        Ok(Arrival {
244            event,
245            detection: None,
246            frame_captured_at: None,
247            camera_frame: crate::inbox::AlertCameraFrame::NotAsked,
248        })
249    }
250}