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_supervisor_api::{ImageFallback, ImageKind};
69use printobserver_types::contract::Sample;
70use printobserver_types::schemars::JsonSchema;
71use printobserver_types::serde::{Deserialize, Serialize};
72use printobserver_types::{EventBody, EventRecord, ImageRef, PrintId, Timestamp};
73
74use crate::error::CoreError;
75use crate::inbox::Arrival;
76use crate::kinds::{
77    CameraDegradedPayload, CameraLookPayload, CameraRetryPayload, FrameCause, PortFailureSite,
78};
79use crate::store::{EventDraft, ImageDraft};
80use crate::supervisor::Supervisor;
81use printobserver_vision_api::{FetchedImage, FrameFault, VisionError};
82
83/// One fresh look at a print.
84///
85/// An answer rather than a record, so it admits fields beside its own the way
86/// every answer of the server does: a client that could not open the frame's
87/// path says so in a field of its own beside the rest of the answer.
88#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
89#[serde(crate = "printobserver_types::serde")]
90#[schemars(crate = "printobserver_types::schemars")]
91pub struct Look {
92    /// The look itself, as it was written into the print's history — or the
93    /// printer's, for a look at the printer — carrying the frame as its image
94    /// when there is one.
95    pub event: EventRecord,
96    /// The events for this print that arrived while the look waited, oldest
97    /// first; the look returned early when there were any.
98    #[serde(default, skip_serializing_if = "Vec::is_empty")]
99    pub arrived: Vec<EventRecord>,
100    /// The frame the camera gave, absent when no camera is configured or it
101    /// gave none — which the history records as a port failure.
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub frame: Option<ImageRef>,
104    /// The absolute path the frame's bytes are at, on the supervisor's host.
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub image_path: Option<PathBuf>,
107    /// What the image at `image_path` is, and why it is that one, in one line;
108    /// absent with no image, or when what made it says nothing.
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub image_note: Option<String>,
111    /// Which image is at `image_path`; absent with no image.
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub image_kind: Option<ImageKind>,
114    /// Why the image at `image_path` is the whole frame; absent for the
115    /// three-panel image, with no image, or when what made it gave no reason.
116    #[serde(default, skip_serializing_if = "Option::is_none")]
117    pub image_fallback: Option<ImageFallback>,
118    /// The printer's state now, absent when it could not be read.
119    #[serde(default, skip_serializing_if = "Option::is_none")]
120    pub printer: Option<PrinterSnapshot>,
121    /// The job the printer reports now, absent when it could not be read.
122    #[serde(default, skip_serializing_if = "Option::is_none")]
123    pub job: Option<JobSnapshot>,
124    /// Whether the print is paused and the pause is the detector's, which is
125    /// what an adjustment asked for now would be applied under.
126    pub detector_paused: bool,
127}
128
129impl Sample for Look {
130    fn sample_full() -> Self {
131        Self {
132            event: EventRecord::sample_full(),
133            arrived: vec![EventRecord::sample_full()],
134            frame: Some(ImageRef::sample_full()),
135            image_path: Some(PathBuf::from("/var/lib/printobserver/images/look.jpg")),
136            image_note: Some(
137                "the whole camera frame, scaled to fit 1280x720 and uncropped: no print is named, \
138                 so there is no plan to draw on it"
139                    .to_owned(),
140            ),
141            image_kind: Some(ImageKind::WholeFrame),
142            image_fallback: Some(ImageFallback {
143                code: printobserver_supervisor_api::WholeFrameReasonCode::NoPrint,
144                message: "no print is named, so there is no planned toolpath to draw on it"
145                    .to_owned(),
146            }),
147            printer: Some(PrinterSnapshot::sample_full()),
148            job: Some(JobSnapshot::sample_full()),
149            detector_paused: true,
150        }
151    }
152
153    fn sample_minimal() -> Self {
154        Self {
155            event: EventRecord::sample_minimal(),
156            arrived: Vec::new(),
157            frame: None,
158            image_path: None,
159            image_note: None,
160            image_kind: None,
161            image_fallback: None,
162            printer: None,
163            job: None,
164            detector_paused: false,
165        }
166    }
167}
168
169impl Supervisor {
170    /// Wait up to `wait` for anything to arrive for one print's running turn,
171    /// and take it.
172    ///
173    /// **This blocks the calling thread** for as long as it waits; call it
174    /// where a blocking wait is expected.
175    #[must_use]
176    pub fn await_arrivals(&self, print_id: PrintId, wait: Duration) -> Vec<Arrival> {
177        self.inboxes().wait_and_take(print_id, wait)
178    }
179
180    /// Wait up to `wait` for anything to arrive for one print's running turn,
181    /// take it, and answer how long the wait was.
182    ///
183    /// Nothing pending and the wait passed on a replay's clock
184    /// ([`Timestamp::pass_replay_time`]) answers at once, having waited all of
185    /// `wait`: on that clock nothing arrives during a turn, so the whole wait
186    /// is what waiting it out would have been.
187    ///
188    /// **This blocks the calling thread** for as long as it waits; call it
189    /// where a blocking wait is expected.
190    #[must_use]
191    pub fn await_look_arrivals(
192        &self,
193        print_id: PrintId,
194        wait: Duration,
195    ) -> (Vec<Arrival>, Duration) {
196        let started = std::time::Instant::now();
197        let pending = self.inboxes().wait_and_take(print_id, Duration::ZERO);
198        if !pending.is_empty() {
199            return (pending, started.elapsed());
200        }
201        if printobserver_types::Timestamp::pass_replay_time(wait) {
202            return (pending, wait);
203        }
204        let arrived = self.inboxes().wait_and_take(print_id, wait);
205        (arrived, started.elapsed())
206    }
207
208    /// Take a frame, write one look down with it, and read the printer.
209    ///
210    /// # Errors
211    ///
212    /// Returns [`CoreError::NoSuchPrint`] when nothing is held under that
213    /// identifier, and the store's own error when the look could not be
214    /// written down. A camera or printer that will not answer is recorded and
215    /// answered as an absence rather than as an error.
216    ///
217    /// What arrived is delivered by the look written down, so a look that
218    /// could not be written down delivers nothing: what it was handed goes
219    /// back to the print's running turn, ahead of anything that arrived since,
220    /// for its next look or the turn after it.
221    pub async fn take_look(
222        &self,
223        print_id: PrintId,
224        waited: Duration,
225        arrived: Vec<Arrival>,
226    ) -> Result<Look, CoreError> {
227        let written = match self.stores().prints.print(print_id).await {
228            Ok(Some(print)) => {
229                let fetched = self.fetch_configured_frame(Some(print.id)).await;
230                let payload = CameraLookPayload {
231                    waited_s: u32::try_from(waited.as_secs()).unwrap_or(u32::MAX),
232                    delivered: arrived.iter().map(|each| each.event.id).collect(),
233                    frame_captured_at: self.frame_captured_at(fetched.as_ref()),
234                };
235                self.write_with_frame(Some(print.id), &payload, fetched)
236                    .await
237                    .map(|event| (print, event))
238            }
239            Ok(None) => Err(CoreError::NoSuchPrint { print_id }),
240            Err(error) => Err(error.into()),
241        };
242        let (print, event) = match written {
243            Ok(written) => written,
244            Err(error) => {
245                self.inboxes().put_back(print_id, arrived);
246                return Err(error);
247            }
248        };
249        let arrived: Vec<EventRecord> = arrived.into_iter().map(|each| each.event).collect();
250        let printer = self.read_snapshot().await.ok();
251        let job = self.read_job().await.ok();
252        // `OctoPrint` clears a job's position when it is cancelled or fails,
253        // so every read that finds the print running is where it is next known
254        // to have stopped. The look is already written down and answered
255        // either way: a position the store would not keep costs this look
256        // nothing, and the next read records one.
257        if let Some(job) = &job
258            && print.ended_at.is_none()
259        {
260            let _ = self
261                .record_position_from(&print, job, self.clock().now())
262                .await;
263        }
264        // A look's frame is one the plan's rise can later be measured from,
265        // when it was this print's file the job had reached a place in.
266        if let (Some(captured), Some(job)) = (
267            event
268                .payload_as::<CameraLookPayload>()
269                .and_then(Result::ok)
270                .and_then(|look| look.frame_captured_at),
271            &job,
272        ) && print.ended_at.is_none()
273            && job.file_name.is_some()
274            && job.file_name == print.file_name
275            && let Some(position) = job.file_position_bytes
276        {
277            self.gcode_indexes()
278                .note_look(print.id, captured, position, self.clock().now());
279        }
280        let paused = printer
281            .as_ref()
282            .is_some_and(|taken| taken.connection == PrinterState::Paused);
283        let detector_paused = self.detector_paused(print.id) && paused;
284        let plan = if print.ended_at.is_none() {
285            self.plan_position(&print, job.as_ref()).await
286        } else {
287            None
288        };
289        Ok(self
290            .answered(event, arrived, printer, job, detector_paused, plan, paused)
291            .await)
292    }
293
294    /// Take a frame of the printer with no print named, write the look down
295    /// with it, and read the printer.
296    ///
297    /// The look and its frame belong to no print. Nothing is waited on here
298    /// and nothing is delivered: a look at the printer takes no event any
299    /// print's agent is owed.
300    ///
301    /// # Errors
302    ///
303    /// Returns the store's own error when the look could not be written down.
304    /// A camera or printer that will not answer is recorded and answered as an
305    /// absence rather than as an error.
306    pub async fn take_printer_look(&self, waited: Duration) -> Result<Look, CoreError> {
307        let fetched = self.fetch_configured_frame(None).await;
308        let payload = CameraLookPayload {
309            waited_s: u32::try_from(waited.as_secs()).unwrap_or(u32::MAX),
310            delivered: Vec::new(),
311            frame_captured_at: self.frame_captured_at(fetched.as_ref()),
312        };
313        let event = self.write_with_frame(None, &payload, fetched).await?;
314        let printer = self.read_snapshot().await.ok();
315        let job = self.read_job().await.ok();
316        let paused = printer
317            .as_ref()
318            .is_some_and(|taken| taken.connection == PrinterState::Paused);
319        Ok(self
320            .answered(event, Vec::new(), printer, job, false, None, paused)
321            .await)
322    }
323
324    /// The answer to one look, its frame's path read off the store.
325    #[expect(
326        clippy::too_many_arguments,
327        reason = "each is one part of the answer the look gathered"
328    )]
329    async fn answered(
330        &self,
331        event: EventRecord,
332        arrived: Vec<EventRecord>,
333        printer: Option<PrinterSnapshot>,
334        job: Option<JobSnapshot>,
335        detector_paused: bool,
336        plan: Option<crate::check_image::PlanPosition>,
337        paused: bool,
338    ) -> Look {
339        let frame = event.image.clone();
340        let shown = match &frame {
341            Some(reference) => {
342                let captured_at = crate::check_image::captured_at_of(&event, None);
343                self.shown_image_of(
344                    reference,
345                    event.print_id,
346                    captured_at,
347                    crate::check_image::ImageUse::Look,
348                    plan,
349                    true,
350                    paused,
351                )
352                .await
353            }
354            None => None,
355        };
356        let image_kind = shown.as_ref().map(crate::check_image::ShownImage::kind);
357        let (image_path, image_note, image_fallback) = shown.map_or((None, None, None), |shown| {
358            (Some(shown.path), shown.note, shown.fallback)
359        });
360        Look {
361            event,
362            arrived,
363            frame,
364            image_path,
365            image_note,
366            image_kind,
367            image_fallback,
368            printer,
369            job,
370            detector_paused,
371        }
372    }
373
374    /// Fetch a frame from the configured camera, when one is configured: the
375    /// URL it was fetched from, and what the fetch came to.
376    pub(crate) async fn fetch_configured_frame(
377        &self,
378        print_id: Option<PrintId>,
379    ) -> Option<(String, Frame)> {
380        let url = self
381            .config()
382            .camera_snapshot_url
383            .as_ref()?
384            .as_str()
385            .to_owned();
386        let fetched = self.fetch_frame(&url, print_id).await;
387        Some((url, fetched))
388    }
389
390    /// One good frame from the configured camera, as its JPEG bytes and the
391    /// URL they came from, fetched as a look fetches one — retried while the
392    /// camera answers a server error and judged by the vision port, each such
393    /// answer written down to the print's history as a look's are. Nothing
394    /// when no camera is configured or no good frame came; the frame itself is
395    /// not recorded.
396    pub async fn fetch_camera_frame(&self, print_id: PrintId) -> Option<(String, Vec<u8>)> {
397        match self.fetch_configured_frame(Some(print_id)).await? {
398            (url, Frame::Good(image)) => Some((url, image.bytes.as_slice().to_vec())),
399            _ => None,
400        }
401    }
402
403    /// One good frame from the configured camera, kept unstored, with the URL
404    /// it came from: fetched as a look fetches one, retried and judged alike.
405    /// Nothing when no camera is configured or no good frame came. A record
406    /// written with it ([`record_with_frame`](Self::record_with_frame)) stores
407    /// it.
408    pub async fn fetch_camera_image(&self, print_id: PrintId) -> Option<(String, FetchedImage)> {
409        match self.fetch_configured_frame(Some(print_id)).await? {
410            (url, Frame::Good(image)) => Some((url, image)),
411            _ => None,
412        }
413    }
414
415    /// Append one record the server made to a print's history, through the
416    /// frame-carrying write every check and look is written with: with a frame
417    /// fetched for it, which is stored with the record, or with none, when the
418    /// record names a frame already stored.
419    ///
420    /// # Errors
421    ///
422    /// The store's own error when the record could not be written down.
423    pub async fn record_with_frame(
424        &self,
425        print_id: PrintId,
426        body: EventBody,
427        frame: Option<(String, FetchedImage)>,
428    ) -> Result<EventRecord, CoreError> {
429        self.write_body_with_frame(
430            Some(print_id),
431            body,
432            frame.map(|(url, image)| (url, Frame::Good(image))),
433        )
434        .await
435    }
436
437    /// When a fetched frame was captured: what its source says, or now.
438    pub(crate) fn frame_captured_at(&self, fetched: Option<&(String, Frame)>) -> Option<Timestamp> {
439        match fetched {
440            Some((_, Frame::Good(image))) => {
441                Some(image.captured_at.unwrap_or_else(|| self.clock().now()))
442            }
443            _ => None,
444        }
445    }
446
447    /// Write one event down with what a fetch gave as its image.
448    ///
449    /// A good frame is kept with the event in one write. A camera whose
450    /// frames were all bad is written down as a [`CameraDegradedPayload`] in
451    /// the event's place, carrying no frame. A camera that would not answer
452    /// leaves the event written without one, and the refusal recorded against
453    /// it; so does a store that could not write the frame's bytes
454    /// ([`StoreError::Io`](crate::store::StoreError::Io)), which stored
455    /// nothing of the write.
456    ///
457    /// # Errors
458    ///
459    /// Returns the store's own error when the event could not be written down
460    /// at all.
461    pub(crate) async fn write_with_frame<P: printobserver_types::EventPayload>(
462        &self,
463        print_id: Option<PrintId>,
464        payload: &P,
465        fetched: Option<(String, Frame)>,
466    ) -> Result<EventRecord, CoreError> {
467        self.write_body_with_frame(print_id, EventBody::of(payload)?, fetched)
468            .await
469    }
470
471    /// [`write_with_frame`](Self::write_with_frame) of a body already
472    /// rendered.
473    pub(crate) async fn write_body_with_frame(
474        &self,
475        print_id: Option<PrintId>,
476        body: EventBody,
477        fetched: Option<(String, Frame)>,
478    ) -> Result<EventRecord, CoreError> {
479        let draft = |body: EventBody| EventDraft {
480            print_id,
481            source: crate::kinds::system_source(),
482            received_at: self.clock().now(),
483            body,
484            raw: None,
485        };
486        let Some((url, fetched)) = fetched else {
487            return Ok(self.stores().events.append_event(draft(body)).await?);
488        };
489        let refused = match fetched {
490            Frame::Good(image) => {
491                let image = ImageDraft {
492                    source_url: Some(url),
493                    content_type: image.content_type,
494                    bytes: image.bytes,
495                };
496                match self
497                    .stores()
498                    .events
499                    .append_event_with_image(draft(body.clone()), image)
500                    .await
501                {
502                    Ok(event) => return Ok(event),
503                    // The frame's bytes could not be written, and nothing was
504                    // stored: the event is written without its frame. Any
505                    // other refusal is the event's own, and answered as one.
506                    Err(error @ crate::store::StoreError::Io { .. }) => error.to_string(),
507                    Err(error) => return Err(error.into()),
508                }
509            }
510            Frame::Failed(detail) => detail,
511            Frame::Degraded(degraded) => {
512                return self
513                    .append_system_event_to(print_id, EventBody::of(&degraded)?)
514                    .await;
515            }
516        };
517        let event = self.stores().events.append_event(draft(body)).await?;
518        self.record_port_failure_to(print_id, event.id, PortFailureSite::CameraLook, refused)
519            .await;
520        Ok(event)
521    }
522
523    /// Fetch frames from the camera until one is good, up to
524    /// [`FRAME_ATTEMPTS`] of them, each asked again while the camera answers a
525    /// server error.
526    pub(crate) async fn fetch_frame(&self, url: &str, print_id: Option<PrintId>) -> Frame {
527        let mut faults: Vec<FrameFault> = Vec::new();
528        while faults.len() < FRAME_ATTEMPTS as usize {
529            let fetched = match self.fetch_retrying(url, print_id).await {
530                Ok(fetched) => fetched,
531                Err(error) => return Frame::Failed(error.to_string()),
532            };
533            match self.vision().judge_frame(fetched).await {
534                Ok(good) => return Frame::Good(good),
535                Err(fault) => faults.push(fault),
536            }
537        }
538        let cause = match faults.last() {
539            Some(FrameFault::Undecodable { .. }) => FrameCause::Undecodable,
540            _ => FrameCause::Blank,
541        };
542        let detail = faults
543            .iter()
544            .enumerate()
545            .map(|(index, fault)| format!("frame {}: {fault}", index + 1))
546            .collect::<Vec<_>>()
547            .join("; ");
548        Frame::Degraded(CameraDegradedPayload {
549            attempts: FRAME_ATTEMPTS,
550            cause,
551            detail,
552        })
553    }
554
555    /// Fetch one frame, asking again after [`CameraRetry::backoff`] each time
556    /// the camera answers a server error, up to [`CameraRetry::retries`] more
557    /// times — and writing each such answer down, as it happens, before the
558    /// wait.
559    async fn fetch_retrying(
560        &self,
561        url: &str,
562        print_id: Option<PrintId>,
563    ) -> Result<FetchedImage, VisionError> {
564        let retry = self.config().camera_retry;
565        let attempts = retry.retries.saturating_add(1);
566        let mut attempt: u32 = 1;
567        loop {
568            let error = match self.vision().fetch_image(url.to_owned()).await {
569                Ok(fetched) => return Ok(fetched),
570                Err(error) => error,
571            };
572            let VisionError::Status {
573                status, excerpt, ..
574            } = &error
575            else {
576                return Err(error);
577            };
578            if !error.is_server_error() || attempt >= attempts {
579                return Err(error);
580            }
581            let retried = CameraRetryPayload {
582                attempt,
583                attempts,
584                status: *status,
585                excerpt: excerpt.clone(),
586                backoff_ms: u64::try_from(retry.backoff.as_millis()).unwrap_or(u64::MAX),
587            };
588            // A record that will not render, or that the store refuses, costs
589            // the fetch nothing: the retry is made whether or not it was
590            // written down.
591            if let Ok(body) = EventBody::of(&retried) {
592                let _ = self.append_system_event_to(print_id, body).await;
593            }
594            // A wait the system could not start is no reason to give up the
595            // frame: the next attempt is made at once instead.
596            let _ = crate::delay::Delay::new(retry.backoff).await;
597            attempt += 1;
598        }
599    }
600}
601
602/// How often, and how far apart, a fetch the camera answered with a server
603/// error is made again.
604///
605/// The defaults bound what a camera failing every attempt costs a scheduled
606/// check: with the vision adapter's own per-fetch timeout of five seconds,
607/// four attempts and three waits are at most about 21.5 s.
608#[derive(Debug, Clone, Copy, PartialEq, Eq)]
609pub struct CameraRetry {
610    /// How many more times a fetch is made after its first is answered with a
611    /// server error.
612    pub retries: u32,
613    /// How long after a server error the next attempt is made.
614    pub backoff: Duration,
615}
616
617impl Default for CameraRetry {
618    fn default() -> Self {
619        Self {
620            retries: DEFAULT_CAMERA_RETRIES,
621            backoff: DEFAULT_CAMERA_RETRY_BACKOFF,
622        }
623    }
624}
625
626/// How many more times a fetch the camera answered with a server error is
627/// made: three, so four attempts in all.
628pub const DEFAULT_CAMERA_RETRIES: u32 = 3;
629
630/// How long after a server error the next attempt at a frame is made.
631pub const DEFAULT_CAMERA_RETRY_BACKOFF: Duration = Duration::from_millis(500);
632
633/// How many frames one look or observation fetches before it records the
634/// camera degraded: the first, and two more.
635pub const FRAME_ATTEMPTS: u32 = 3;
636
637/// What fetching a frame came to.
638#[derive(Debug)]
639pub(crate) enum Frame {
640    /// A good frame.
641    Good(FetchedImage),
642    /// The camera would not answer, in its own words.
643    Failed(String),
644    /// Every frame fetched was bad.
645    Degraded(CameraDegradedPayload),
646}