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, Timestamp};
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                    frame_captured_at: self.frame_captured_at(fetched.as_ref()),
180                };
181                self.write_with_frame(Some(print.id), &payload, fetched)
182                    .await
183                    .map(|event| (print, event))
184            }
185            Ok(None) => Err(CoreError::NoSuchPrint { print_id }),
186            Err(error) => Err(error.into()),
187        };
188        let (print, event) = match written {
189            Ok(written) => written,
190            Err(error) => {
191                self.inboxes().put_back(print_id, arrived);
192                return Err(error);
193            }
194        };
195        let arrived: Vec<EventRecord> = arrived.into_iter().map(|each| each.event).collect();
196        let printer = self.read_snapshot().await.ok();
197        let job = self.read_job().await.ok();
198        // `OctoPrint` clears a job's position when it is cancelled or fails,
199        // so every read that finds the print running is where it is next known
200        // to have stopped. The look is already written down and answered
201        // either way: a position the store would not keep costs this look
202        // nothing, and the next read records one.
203        if let Some(job) = &job
204            && print.ended_at.is_none()
205        {
206            let _ = self
207                .record_position_from(&print, job, self.clock().now())
208                .await;
209        }
210        let detector_paused = self.detector_paused(print.id)
211            && printer
212                .as_ref()
213                .is_some_and(|taken| taken.connection == PrinterState::Paused);
214        Ok(self
215            .answered(event, arrived, printer, job, detector_paused)
216            .await)
217    }
218
219    /// Take a frame of the printer with no print named, write the look down
220    /// with it, and read the printer.
221    ///
222    /// The look and its frame belong to no print. Nothing is waited on here
223    /// and nothing is delivered: a look at the printer takes no event any
224    /// print's agent is owed.
225    ///
226    /// # Errors
227    ///
228    /// Returns the store's own error when the look could not be written down.
229    /// A camera or printer that will not answer is recorded and answered as an
230    /// absence rather than as an error.
231    pub async fn take_printer_look(&self, waited: Duration) -> Result<Look, CoreError> {
232        let fetched = self.fetch_configured_frame(None).await;
233        let payload = CameraLookPayload {
234            waited_s: u32::try_from(waited.as_secs()).unwrap_or(u32::MAX),
235            delivered: Vec::new(),
236            frame_captured_at: self.frame_captured_at(fetched.as_ref()),
237        };
238        let event = self.write_with_frame(None, &payload, fetched).await?;
239        let printer = self.read_snapshot().await.ok();
240        let job = self.read_job().await.ok();
241        Ok(self.answered(event, Vec::new(), printer, job, false).await)
242    }
243
244    /// The answer to one look, its frame's path read off the store.
245    async fn answered(
246        &self,
247        event: EventRecord,
248        arrived: Vec<EventRecord>,
249        printer: Option<PrinterSnapshot>,
250        job: Option<JobSnapshot>,
251        detector_paused: bool,
252    ) -> Look {
253        let frame = event.image.clone();
254        let image_path = match &frame {
255            Some(reference) => self.image_path(reference).await,
256            None => None,
257        };
258        Look {
259            event,
260            arrived,
261            frame,
262            image_path,
263            printer,
264            job,
265            detector_paused,
266        }
267    }
268
269    /// Fetch a frame from the configured camera, when one is configured: the
270    /// URL it was fetched from, and what the fetch came to.
271    pub(crate) async fn fetch_configured_frame(
272        &self,
273        print_id: Option<PrintId>,
274    ) -> Option<(String, Frame)> {
275        let url = self
276            .config()
277            .camera_snapshot_url
278            .as_ref()?
279            .as_str()
280            .to_owned();
281        let fetched = self.fetch_frame(&url, print_id).await;
282        Some((url, fetched))
283    }
284
285    /// When a fetched frame was captured: what its source says, or now.
286    pub(crate) fn frame_captured_at(&self, fetched: Option<&(String, Frame)>) -> Option<Timestamp> {
287        match fetched {
288            Some((_, Frame::Good(image))) => {
289                Some(image.captured_at.unwrap_or_else(|| self.clock().now()))
290            }
291            _ => None,
292        }
293    }
294
295    /// Write one event down with what a fetch gave as its image.
296    ///
297    /// A good frame is kept with the event in one write. A camera whose
298    /// frames were all bad is written down as a [`CameraDegradedPayload`] in
299    /// the event's place, carrying no frame. A camera that would not answer
300    /// leaves the event written without one, and the refusal recorded against
301    /// it; so does a store that could not write the frame's bytes
302    /// ([`StoreError::Io`](crate::store::StoreError::Io)), which stored
303    /// nothing of the write.
304    ///
305    /// # Errors
306    ///
307    /// Returns the store's own error when the event could not be written down
308    /// at all.
309    pub(crate) async fn write_with_frame<P: printobserver_types::EventPayload>(
310        &self,
311        print_id: Option<PrintId>,
312        payload: &P,
313        fetched: Option<(String, Frame)>,
314    ) -> Result<EventRecord, CoreError> {
315        let draft = |body: EventBody| EventDraft {
316            print_id,
317            source: crate::kinds::system_source(),
318            received_at: self.clock().now(),
319            body,
320            raw: None,
321        };
322        let body = EventBody::of(payload)?;
323        let Some((url, fetched)) = fetched else {
324            return Ok(self.stores().events.append_event(draft(body)).await?);
325        };
326        let refused = match fetched {
327            Frame::Good(image) => {
328                let image = ImageDraft {
329                    source_url: Some(url),
330                    content_type: image.content_type,
331                    bytes: image.bytes,
332                };
333                match self
334                    .stores()
335                    .events
336                    .append_event_with_image(draft(body.clone()), image)
337                    .await
338                {
339                    Ok(event) => return Ok(event),
340                    // The frame's bytes could not be written, and nothing was
341                    // stored: the event is written without its frame. Any
342                    // other refusal is the event's own, and answered as one.
343                    Err(error @ crate::store::StoreError::Io { .. }) => error.to_string(),
344                    Err(error) => return Err(error.into()),
345                }
346            }
347            Frame::Failed(detail) => detail,
348            Frame::Degraded(degraded) => {
349                return self
350                    .append_system_event_to(print_id, EventBody::of(&degraded)?)
351                    .await;
352            }
353        };
354        let event = self.stores().events.append_event(draft(body)).await?;
355        self.record_port_failure_to(print_id, event.id, PortFailureSite::CameraLook, refused)
356            .await;
357        Ok(event)
358    }
359
360    /// Fetch frames from the camera until one is good, up to
361    /// [`FRAME_ATTEMPTS`] of them, each asked again while the camera answers a
362    /// server error.
363    pub(crate) async fn fetch_frame(&self, url: &str, print_id: Option<PrintId>) -> Frame {
364        let mut faults: Vec<FrameFault> = Vec::new();
365        while faults.len() < FRAME_ATTEMPTS as usize {
366            let fetched = match self.fetch_retrying(url, print_id).await {
367                Ok(fetched) => fetched,
368                Err(error) => return Frame::Failed(error.to_string()),
369            };
370            match self.vision().judge_frame(fetched).await {
371                Ok(good) => return Frame::Good(good),
372                Err(fault) => faults.push(fault),
373            }
374        }
375        let cause = match faults.last() {
376            Some(FrameFault::Undecodable { .. }) => FrameCause::Undecodable,
377            _ => FrameCause::Blank,
378        };
379        let detail = faults
380            .iter()
381            .enumerate()
382            .map(|(index, fault)| format!("frame {}: {fault}", index + 1))
383            .collect::<Vec<_>>()
384            .join("; ");
385        Frame::Degraded(CameraDegradedPayload {
386            attempts: FRAME_ATTEMPTS,
387            cause,
388            detail,
389        })
390    }
391
392    /// Fetch one frame, asking again after [`CameraRetry::backoff`] each time
393    /// the camera answers a server error, up to [`CameraRetry::retries`] more
394    /// times — and writing each such answer down, as it happens, before the
395    /// wait.
396    async fn fetch_retrying(
397        &self,
398        url: &str,
399        print_id: Option<PrintId>,
400    ) -> Result<FetchedImage, VisionError> {
401        let retry = self.config().camera_retry;
402        let attempts = retry.retries.saturating_add(1);
403        let mut attempt: u32 = 1;
404        loop {
405            let error = match self.vision().fetch_image(url.to_owned()).await {
406                Ok(fetched) => return Ok(fetched),
407                Err(error) => error,
408            };
409            let VisionError::Status {
410                status, excerpt, ..
411            } = &error
412            else {
413                return Err(error);
414            };
415            if !error.is_server_error() || attempt >= attempts {
416                return Err(error);
417            }
418            let retried = CameraRetryPayload {
419                attempt,
420                attempts,
421                status: *status,
422                excerpt: excerpt.clone(),
423                backoff_ms: u64::try_from(retry.backoff.as_millis()).unwrap_or(u64::MAX),
424            };
425            // A record that will not render, or that the store refuses, costs
426            // the fetch nothing: the retry is made whether or not it was
427            // written down.
428            if let Ok(body) = EventBody::of(&retried) {
429                let _ = self.append_system_event_to(print_id, body).await;
430            }
431            // A wait the system could not start is no reason to give up the
432            // frame: the next attempt is made at once instead.
433            let _ = crate::delay::Delay::new(retry.backoff).await;
434            attempt += 1;
435        }
436    }
437}
438
439/// How often, and how far apart, a fetch the camera answered with a server
440/// error is made again.
441///
442/// The defaults bound what a camera failing every attempt costs a scheduled
443/// check: with the vision adapter's own per-fetch timeout of five seconds,
444/// four attempts and three waits are at most about 21.5 s.
445#[derive(Debug, Clone, Copy, PartialEq, Eq)]
446pub struct CameraRetry {
447    /// How many more times a fetch is made after its first is answered with a
448    /// server error.
449    pub retries: u32,
450    /// How long after a server error the next attempt is made.
451    pub backoff: Duration,
452}
453
454impl Default for CameraRetry {
455    fn default() -> Self {
456        Self {
457            retries: DEFAULT_CAMERA_RETRIES,
458            backoff: DEFAULT_CAMERA_RETRY_BACKOFF,
459        }
460    }
461}
462
463/// How many more times a fetch the camera answered with a server error is
464/// made: three, so four attempts in all.
465pub const DEFAULT_CAMERA_RETRIES: u32 = 3;
466
467/// How long after a server error the next attempt at a frame is made.
468pub const DEFAULT_CAMERA_RETRY_BACKOFF: Duration = Duration::from_millis(500);
469
470/// How many frames one look or observation fetches before it records the
471/// camera degraded: the first, and two more.
472pub const FRAME_ATTEMPTS: u32 = 3;
473
474/// What fetching a frame came to.
475#[derive(Debug)]
476pub(crate) enum Frame {
477    /// A good frame.
478    Good(FetchedImage),
479    /// The camera would not answer, in its own words.
480    Failed(String),
481    /// Every frame fetched was bad.
482    Degraded(CameraDegradedPayload),
483}