Skip to main content

printobserver_core/
look.rs

1//! A fresh look at a print: what arrived, what the camera shows, and what the
2//! printer says, now — or at the printer, with no print named.
3//!
4//! The context a turn reads is the one collected when its event arrived; a
5//! look is how the agent sees the print as it is *now*, as often as it wants,
6//! and how it watches for a while before deciding. A look waits up to
7//! [`MAX_LOOK_WAIT_S`](crate::MAX_LOOK_WAIT_S) for something to arrive for the
8//! print and returns the moment something does — that is how an event that
9//! arrives during a turn reaches the agent already running rather than a
10//! second one.
11//!
12//! # Two halves, because one of them blocks
13//!
14//! [`Supervisor::await_arrivals`] waits on a thread of its own and takes what
15//! arrived; [`Supervisor::take_look`] writes the look down, takes the frame and
16//! reads the printer. The server calls the first on a blocking thread, exactly
17//! as it drives a turn, so that a minute and a half of waiting holds no
18//! asynchronous worker.
19//!
20//! # Every frame is kept
21//!
22//! A look is written down as a [`CameraLookPayload`] event, and the frame is
23//! that event's image, so a print's whole record of what it looked like is in
24//! its history rather than in whatever scratch directory asked.
25//!
26//! # The frame is fetched first, and kept with its event in one write
27//!
28//! The camera is asked before anything is written, and the event is then
29//! written together with its frame
30//! ([`EventStore::append_event_with_image`](crate::store::EventStore::append_event_with_image)),
31//! so the first read anybody following the log makes of a look or a scheduled
32//! check already finds its image. A store that will not keep the frame leaves
33//! the event written without it, with the store's refusal recorded against it.
34//!
35//! # A look at the printer
36//!
37//! [`Supervisor::take_printer_look`] is a look with no print named: before a
38//! print, between prints, after one — the bed check before a start among
39//! them. Its event and its frame belong to no print. It waits on nothing that
40//! arrives for a print, so it can never take an event meant for a print's
41//! agent, and it delivers nothing.
42//!
43//! # A camera answering a server error is asked again
44//!
45//! A fetch the camera answered `500` to `599` is made again after
46//! [`CameraRetry::backoff`], up to [`CameraRetry::retries`] more times, each
47//! refusal written down as a [`CameraRetryPayload`] as it happens. Only a
48//! fetch whose attempts all ran out is the port failure it always was. Any
49//! other refusal — a `404`, a timeout, a host refusing the connection — is one
50//! a second attempt would not change, and fails the fetch at once.
51//!
52//! # A frame that shows nothing is not handed over as one
53//!
54//! Each frame is judged before it is kept
55//! ([`VisionPort::judge_frame`](printobserver_vision_api::VisionPort::judge_frame)):
56//! one that does not decode whole, or decodes near-uniform grey, is fetched
57//! again, up to [`FRAME_ATTEMPTS`] in all. The first good one is the look's
58//! frame. When every one is bad the look is written down as a
59//! [`CameraDegradedPayload`] in its place, carrying no frame, so nothing the
60//! camera could not show is handed to the agent as a picture of the print. A
61//! camera that will not answer at all is a port failure recorded against the
62//! look, as it always was.
63
64use std::path::PathBuf;
65use std::time::Duration;
66
67use printobserver_printer_api::{JobSnapshot, PrinterSnapshot, PrinterState};
68use printobserver_types::contract::Sample;
69use printobserver_types::schemars::JsonSchema;
70use printobserver_types::serde::{Deserialize, Serialize};
71use printobserver_types::{EventBody, EventRecord, ImageRef, PrintId};
72
73use crate::error::CoreError;
74use crate::inbox::Arrival;
75use crate::kinds::{
76    CameraDegradedPayload, CameraLookPayload, CameraRetryPayload, FrameCause, PortFailureSite,
77};
78use crate::store::{EventDraft, ImageDraft};
79use crate::supervisor::Supervisor;
80use printobserver_vision_api::{FetchedImage, FrameFault, VisionError};
81
82/// One fresh look at a print.
83///
84/// An answer rather than a record, so it admits fields beside its own the way
85/// every answer of the server does: a client that could not open the frame's
86/// path says so in a field of its own beside the rest of the answer.
87#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
88#[serde(crate = "printobserver_types::serde")]
89#[schemars(crate = "printobserver_types::schemars")]
90pub struct Look {
91    /// The look itself, as it was written into the print's history — or the
92    /// printer's, for a look at the printer — carrying the frame as its image
93    /// when there is one.
94    pub event: EventRecord,
95    /// The events for this print that arrived while the look waited, oldest
96    /// first; the look returned early when there were any.
97    #[serde(default, skip_serializing_if = "Vec::is_empty")]
98    pub arrived: Vec<EventRecord>,
99    /// The frame the camera gave, absent when no camera is configured or it
100    /// gave none — which the history records as a port failure.
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    pub frame: Option<ImageRef>,
103    /// The absolute path the frame's bytes are at, on the supervisor's host.
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub image_path: Option<PathBuf>,
106    /// The printer's state now, absent when it could not be read.
107    #[serde(default, skip_serializing_if = "Option::is_none")]
108    pub printer: Option<PrinterSnapshot>,
109    /// The job the printer reports now, absent when it could not be read.
110    #[serde(default, skip_serializing_if = "Option::is_none")]
111    pub job: Option<JobSnapshot>,
112    /// Whether the print is paused and the pause is the detector's, which is
113    /// what an adjustment asked for now would be applied under.
114    pub detector_paused: bool,
115}
116
117impl Sample for Look {
118    fn sample_full() -> Self {
119        Self {
120            event: EventRecord::sample_full(),
121            arrived: vec![EventRecord::sample_full()],
122            frame: Some(ImageRef::sample_full()),
123            image_path: Some(PathBuf::from("/var/lib/printobserver/images/look.jpg")),
124            printer: Some(PrinterSnapshot::sample_full()),
125            job: Some(JobSnapshot::sample_full()),
126            detector_paused: true,
127        }
128    }
129
130    fn sample_minimal() -> Self {
131        Self {
132            event: EventRecord::sample_minimal(),
133            arrived: Vec::new(),
134            frame: None,
135            image_path: None,
136            printer: None,
137            job: None,
138            detector_paused: false,
139        }
140    }
141}
142
143impl Supervisor {
144    /// Wait up to `wait` for anything to arrive for one print's running turn,
145    /// and take it.
146    ///
147    /// **This blocks the calling thread** for as long as it waits; call it
148    /// where a blocking wait is expected.
149    #[must_use]
150    pub fn await_arrivals(&self, print_id: PrintId, wait: Duration) -> Vec<Arrival> {
151        self.inboxes().wait_and_take(print_id, wait)
152    }
153
154    /// Take a frame, write one look down with it, and read the printer.
155    ///
156    /// # Errors
157    ///
158    /// Returns [`CoreError::NoSuchPrint`] when nothing is held under that
159    /// identifier, and the store's own error when the look could not be
160    /// written down. A camera or printer that will not answer is recorded and
161    /// answered as an absence rather than as an error.
162    ///
163    /// What arrived is delivered by the look written down, so a look that
164    /// could not be written down delivers nothing: what it was handed goes
165    /// back to the print's running turn, ahead of anything that arrived since,
166    /// for its next look or the turn after it.
167    pub async fn take_look(
168        &self,
169        print_id: PrintId,
170        waited: Duration,
171        arrived: Vec<Arrival>,
172    ) -> Result<Look, CoreError> {
173        let written = match self.stores().prints.print(print_id).await {
174            Ok(Some(print)) => {
175                let fetched = self.fetch_configured_frame(Some(print.id)).await;
176                let payload = CameraLookPayload {
177                    waited_s: u32::try_from(waited.as_secs()).unwrap_or(u32::MAX),
178                    delivered: arrived.iter().map(|each| each.event.id).collect(),
179                };
180                self.write_with_frame(Some(print.id), &payload, fetched)
181                    .await
182                    .map(|event| (print, event))
183            }
184            Ok(None) => Err(CoreError::NoSuchPrint { print_id }),
185            Err(error) => Err(error.into()),
186        };
187        let (print, event) = match written {
188            Ok(written) => written,
189            Err(error) => {
190                self.inboxes().put_back(print_id, arrived);
191                return Err(error);
192            }
193        };
194        let arrived: Vec<EventRecord> = arrived.into_iter().map(|each| each.event).collect();
195        let printer = self.read_snapshot().await.ok();
196        let job = self.read_job().await.ok();
197        // `OctoPrint` clears a job's position when it is cancelled or fails,
198        // so every read that finds the print running is where it is next known
199        // to have stopped. The look is already written down and answered
200        // either way: a position the store would not keep costs this look
201        // nothing, and the next read records one.
202        if let Some(job) = &job
203            && print.ended_at.is_none()
204        {
205            let _ = self
206                .record_position_from(&print, job, self.clock().now())
207                .await;
208        }
209        let detector_paused = self.detector_paused(print.id)
210            && printer
211                .as_ref()
212                .is_some_and(|taken| taken.connection == PrinterState::Paused);
213        Ok(self
214            .answered(event, arrived, printer, job, detector_paused)
215            .await)
216    }
217
218    /// Take a frame of the printer with no print named, write the look down
219    /// with it, and read the printer.
220    ///
221    /// The look and its frame belong to no print. Nothing is waited on here
222    /// and nothing is delivered: a look at the printer takes no event any
223    /// print's agent is owed.
224    ///
225    /// # Errors
226    ///
227    /// Returns the store's own error when the look could not be written down.
228    /// A camera or printer that will not answer is recorded and answered as an
229    /// absence rather than as an error.
230    pub async fn take_printer_look(&self, waited: Duration) -> Result<Look, CoreError> {
231        let fetched = self.fetch_configured_frame(None).await;
232        let payload = CameraLookPayload {
233            waited_s: u32::try_from(waited.as_secs()).unwrap_or(u32::MAX),
234            delivered: Vec::new(),
235        };
236        let event = self.write_with_frame(None, &payload, fetched).await?;
237        let printer = self.read_snapshot().await.ok();
238        let job = self.read_job().await.ok();
239        Ok(self.answered(event, Vec::new(), printer, job, false).await)
240    }
241
242    /// The answer to one look, its frame's path read off the store.
243    async fn answered(
244        &self,
245        event: EventRecord,
246        arrived: Vec<EventRecord>,
247        printer: Option<PrinterSnapshot>,
248        job: Option<JobSnapshot>,
249        detector_paused: bool,
250    ) -> Look {
251        let frame = event.image.clone();
252        let image_path = match &frame {
253            Some(reference) => self.image_path(reference).await,
254            None => None,
255        };
256        Look {
257            event,
258            arrived,
259            frame,
260            image_path,
261            printer,
262            job,
263            detector_paused,
264        }
265    }
266
267    /// Fetch a frame from the configured camera, when one is configured: the
268    /// URL it was fetched from, and what the fetch came to.
269    pub(crate) async fn fetch_configured_frame(
270        &self,
271        print_id: Option<PrintId>,
272    ) -> Option<(String, Frame)> {
273        let url = self
274            .config()
275            .camera_snapshot_url
276            .as_ref()?
277            .as_str()
278            .to_owned();
279        let fetched = self.fetch_frame(&url, print_id).await;
280        Some((url, fetched))
281    }
282
283    /// Write one event down with what a fetch gave as its image.
284    ///
285    /// A good frame is kept with the event in one write. A camera whose
286    /// frames were all bad is written down as a [`CameraDegradedPayload`] in
287    /// the event's place, carrying no frame. A camera that would not answer
288    /// leaves the event written without one, and the refusal recorded against
289    /// it; so does a store that could not write the frame's bytes
290    /// ([`StoreError::Io`](crate::store::StoreError::Io)), which stored
291    /// nothing of the write.
292    ///
293    /// # Errors
294    ///
295    /// Returns the store's own error when the event could not be written down
296    /// at all.
297    pub(crate) async fn write_with_frame<P: printobserver_types::EventPayload>(
298        &self,
299        print_id: Option<PrintId>,
300        payload: &P,
301        fetched: Option<(String, Frame)>,
302    ) -> Result<EventRecord, CoreError> {
303        let draft = |body: EventBody| EventDraft {
304            print_id,
305            source: crate::kinds::system_source(),
306            received_at: self.clock().now(),
307            body,
308            raw: None,
309        };
310        let body = EventBody::of(payload)?;
311        let Some((url, fetched)) = fetched else {
312            return Ok(self.stores().events.append_event(draft(body)).await?);
313        };
314        let refused = match fetched {
315            Frame::Good(image) => {
316                let image = ImageDraft {
317                    source_url: Some(url),
318                    content_type: image.content_type,
319                    bytes: image.bytes,
320                };
321                match self
322                    .stores()
323                    .events
324                    .append_event_with_image(draft(body.clone()), image)
325                    .await
326                {
327                    Ok(event) => return Ok(event),
328                    // The frame's bytes could not be written, and nothing was
329                    // stored: the event is written without its frame. Any
330                    // other refusal is the event's own, and answered as one.
331                    Err(error @ crate::store::StoreError::Io { .. }) => error.to_string(),
332                    Err(error) => return Err(error.into()),
333                }
334            }
335            Frame::Failed(detail) => detail,
336            Frame::Degraded(degraded) => {
337                return self
338                    .append_system_event_to(print_id, EventBody::of(&degraded)?)
339                    .await;
340            }
341        };
342        let event = self.stores().events.append_event(draft(body)).await?;
343        self.record_port_failure_to(print_id, event.id, PortFailureSite::CameraLook, refused)
344            .await;
345        Ok(event)
346    }
347
348    /// Fetch frames from the camera until one is good, up to
349    /// [`FRAME_ATTEMPTS`] of them, each asked again while the camera answers a
350    /// server error.
351    pub(crate) async fn fetch_frame(&self, url: &str, print_id: Option<PrintId>) -> Frame {
352        let mut faults: Vec<FrameFault> = Vec::new();
353        while faults.len() < FRAME_ATTEMPTS as usize {
354            let fetched = match self.fetch_retrying(url, print_id).await {
355                Ok(fetched) => fetched,
356                Err(error) => return Frame::Failed(error.to_string()),
357            };
358            match self.vision().judge_frame(fetched).await {
359                Ok(good) => return Frame::Good(good),
360                Err(fault) => faults.push(fault),
361            }
362        }
363        let cause = match faults.last() {
364            Some(FrameFault::Undecodable { .. }) => FrameCause::Undecodable,
365            _ => FrameCause::Blank,
366        };
367        let detail = faults
368            .iter()
369            .enumerate()
370            .map(|(index, fault)| format!("frame {}: {fault}", index + 1))
371            .collect::<Vec<_>>()
372            .join("; ");
373        Frame::Degraded(CameraDegradedPayload {
374            attempts: FRAME_ATTEMPTS,
375            cause,
376            detail,
377        })
378    }
379
380    /// Fetch one frame, asking again after [`CameraRetry::backoff`] each time
381    /// the camera answers a server error, up to [`CameraRetry::retries`] more
382    /// times — and writing each such answer down, as it happens, before the
383    /// wait.
384    async fn fetch_retrying(
385        &self,
386        url: &str,
387        print_id: Option<PrintId>,
388    ) -> Result<FetchedImage, VisionError> {
389        let retry = self.config().camera_retry;
390        let attempts = retry.retries.saturating_add(1);
391        let mut attempt: u32 = 1;
392        loop {
393            let error = match self.vision().fetch_image(url.to_owned()).await {
394                Ok(fetched) => return Ok(fetched),
395                Err(error) => error,
396            };
397            let VisionError::Status {
398                status, excerpt, ..
399            } = &error
400            else {
401                return Err(error);
402            };
403            if !error.is_server_error() || attempt >= attempts {
404                return Err(error);
405            }
406            let retried = CameraRetryPayload {
407                attempt,
408                attempts,
409                status: *status,
410                excerpt: excerpt.clone(),
411                backoff_ms: u64::try_from(retry.backoff.as_millis()).unwrap_or(u64::MAX),
412            };
413            // A record that will not render, or that the store refuses, costs
414            // the fetch nothing: the retry is made whether or not it was
415            // written down.
416            if let Ok(body) = EventBody::of(&retried) {
417                let _ = self.append_system_event_to(print_id, body).await;
418            }
419            // A wait the system could not start is no reason to give up the
420            // frame: the next attempt is made at once instead.
421            let _ = crate::delay::Delay::new(retry.backoff).await;
422            attempt += 1;
423        }
424    }
425}
426
427/// How often, and how far apart, a fetch the camera answered with a server
428/// error is made again.
429///
430/// The defaults bound what a camera failing every attempt costs a scheduled
431/// check: with the vision adapter's own per-fetch timeout of five seconds,
432/// four attempts and three waits are at most about 21.5 s.
433#[derive(Debug, Clone, Copy, PartialEq, Eq)]
434pub struct CameraRetry {
435    /// How many more times a fetch is made after its first is answered with a
436    /// server error.
437    pub retries: u32,
438    /// How long after a server error the next attempt is made.
439    pub backoff: Duration,
440}
441
442impl Default for CameraRetry {
443    fn default() -> Self {
444        Self {
445            retries: DEFAULT_CAMERA_RETRIES,
446            backoff: DEFAULT_CAMERA_RETRY_BACKOFF,
447        }
448    }
449}
450
451/// How many more times a fetch the camera answered with a server error is
452/// made: three, so four attempts in all.
453pub const DEFAULT_CAMERA_RETRIES: u32 = 3;
454
455/// How long after a server error the next attempt at a frame is made.
456pub const DEFAULT_CAMERA_RETRY_BACKOFF: Duration = Duration::from_millis(500);
457
458/// How many frames one look or observation fetches before it records the
459/// camera degraded: the first, and two more.
460pub const FRAME_ATTEMPTS: u32 = 3;
461
462/// What fetching a frame came to.
463#[derive(Debug)]
464pub(crate) enum Frame {
465    /// A good frame.
466    Good(FetchedImage),
467    /// The camera would not answer, in its own words.
468    Failed(String),
469    /// Every frame fetched was bad.
470    Degraded(CameraDegradedPayload),
471}