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