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 one fresh look a camera check takes of the printer, kept as a look
325    /// at the printer is: one fetch, its frame stored with its own
326    /// `camera_look` event, which belongs to no print.
327    ///
328    /// Unlike every other look, a frame the vision port finds blank is kept
329    /// rather than refused: a covered camera's black frame is what the check
330    /// judges, and finds no sheet on. A frame that does not decode, a camera
331    /// answering with no frame, and one that could not be reached or took too
332    /// long are each answered apart, and recorded against the look as every
333    /// camera failure is.
334    ///
335    /// # Errors
336    ///
337    /// Returns the store's own error when the look could not be written down.
338    pub async fn take_check_look(&self) -> Result<CheckLook, CoreError> {
339        let Some(url) = self
340            .config()
341            .camera_snapshot_url
342            .as_ref()
343            .map(|url| url.as_str().to_owned())
344        else {
345            return Ok(CheckLook::NoCamera);
346        };
347        let payload = |frame_captured_at: Option<Timestamp>| CameraLookPayload {
348            waited_s: 0,
349            delivered: Vec::new(),
350            frame_captured_at,
351        };
352        let fetched = match self.fetch_retrying(&url, None).await {
353            Ok(fetched) => fetched,
354            Err(error) => {
355                let failed = matches!(
356                    error,
357                    VisionError::TimedOut | VisionError::Unreachable { .. }
358                );
359                let detail = error.to_string();
360                let look = self
361                    .write_with_frame(
362                        None,
363                        &payload(None),
364                        Some((url, Frame::Failed(detail.clone()))),
365                    )
366                    .await?;
367                return Ok(if failed {
368                    CheckLook::Failed { look, detail }
369                } else {
370                    CheckLook::NoFrame { look, detail }
371                });
372            }
373        };
374        let kept = match self.vision().judge_frame(fetched.clone()).await {
375            Ok(good) => good,
376            Err(FrameFault::Blank { .. }) => fetched,
377            Err(fault @ FrameFault::Undecodable { .. }) => {
378                let detail = fault.to_string();
379                let look = self
380                    .write_with_frame(
381                        None,
382                        &payload(None),
383                        Some((url, Frame::Failed(detail.clone()))),
384                    )
385                    .await?;
386                return Ok(CheckLook::NoFrame { look, detail });
387            }
388        };
389        let bytes = kept.bytes.as_slice().to_vec();
390        let captured_at = kept.captured_at.unwrap_or_else(|| self.clock().now());
391        let look = self
392            .write_with_frame(
393                None,
394                &payload(Some(captured_at)),
395                Some((url.clone(), Frame::Good(kept))),
396            )
397            .await?;
398        let stored = match &look.image {
399            Some(frame) => self
400                .image_path(frame)
401                .await
402                .map(|path| (frame.clone(), path)),
403            None => None,
404        };
405        Ok(match stored {
406            Some((frame, path)) => CheckLook::Framed {
407                look,
408                frame,
409                path,
410                bytes,
411                url,
412            },
413            None => CheckLook::Failed {
414                look,
415                detail: "the camera's frame could not be stored".to_owned(),
416            },
417        })
418    }
419
420    /// The answer to one look, its frame's path read off the store.
421    #[expect(
422        clippy::too_many_arguments,
423        reason = "each is one part of the answer the look gathered"
424    )]
425    async fn answered(
426        &self,
427        event: EventRecord,
428        arrived: Vec<EventRecord>,
429        printer: Option<PrinterSnapshot>,
430        job: Option<JobSnapshot>,
431        detector_paused: bool,
432        plan: Option<crate::check_image::PlanPosition>,
433        paused: bool,
434    ) -> Look {
435        let frame = event.image.clone();
436        let shown = match &frame {
437            Some(reference) => {
438                let captured_at = crate::check_image::captured_at_of(&event, None);
439                self.shown_image_of(
440                    reference,
441                    event.print_id,
442                    captured_at,
443                    crate::check_image::ImageUse::Look,
444                    plan,
445                    true,
446                    paused,
447                )
448                .await
449            }
450            None => None,
451        };
452        let image_kind = shown.as_ref().map(crate::check_image::ShownImage::kind);
453        let (image_path, image_note, image_fallback) = shown.map_or((None, None, None), |shown| {
454            (Some(shown.path), shown.note, shown.fallback)
455        });
456        Look {
457            event,
458            arrived,
459            frame,
460            image_path,
461            image_note,
462            image_kind,
463            image_fallback,
464            printer,
465            job,
466            detector_paused,
467        }
468    }
469
470    /// Fetch a frame from the configured camera, when one is configured: the
471    /// URL it was fetched from, and what the fetch came to.
472    pub(crate) async fn fetch_configured_frame(
473        &self,
474        print_id: Option<PrintId>,
475    ) -> Option<(String, Frame)> {
476        let url = self
477            .config()
478            .camera_snapshot_url
479            .as_ref()?
480            .as_str()
481            .to_owned();
482        let fetched = self.fetch_frame(&url, print_id).await;
483        Some((url, fetched))
484    }
485
486    /// One good frame from the configured camera, as its JPEG bytes and the
487    /// URL they came from, fetched as a look fetches one — retried while the
488    /// camera answers a server error and judged by the vision port, each such
489    /// answer written down to the print's history as a look's are. Nothing
490    /// when no camera is configured or no good frame came; the frame itself is
491    /// not recorded.
492    pub async fn fetch_camera_frame(&self, print_id: PrintId) -> Option<(String, Vec<u8>)> {
493        match self.fetch_configured_frame(Some(print_id)).await? {
494            (url, Frame::Good(image)) => Some((url, image.bytes.as_slice().to_vec())),
495            _ => None,
496        }
497    }
498
499    /// One good frame from the configured camera, kept unstored, with the URL
500    /// it came from: fetched as a look fetches one, retried and judged alike.
501    /// Nothing when no camera is configured or no good frame came. A record
502    /// written with it ([`record_with_frame`](Self::record_with_frame)) stores
503    /// it.
504    pub async fn fetch_camera_image(&self, print_id: PrintId) -> Option<(String, FetchedImage)> {
505        match self.fetch_configured_frame(Some(print_id)).await? {
506            (url, Frame::Good(image)) => Some((url, image)),
507            _ => None,
508        }
509    }
510
511    /// Append one record the server made to a print's history, through the
512    /// frame-carrying write every check and look is written with: with a frame
513    /// fetched for it, which is stored with the record, or with none, when the
514    /// record names a frame already stored.
515    ///
516    /// # Errors
517    ///
518    /// The store's own error when the record could not be written down.
519    pub async fn record_with_frame(
520        &self,
521        print_id: PrintId,
522        body: EventBody,
523        frame: Option<(String, FetchedImage)>,
524    ) -> Result<EventRecord, CoreError> {
525        self.write_body_with_frame(
526            Some(print_id),
527            body,
528            frame.map(|(url, image)| (url, Frame::Good(image))),
529        )
530        .await
531    }
532
533    /// When a fetched frame was captured: what its source says, or now.
534    pub(crate) fn frame_captured_at(&self, fetched: Option<&(String, Frame)>) -> Option<Timestamp> {
535        match fetched {
536            Some((_, Frame::Good(image))) => {
537                Some(image.captured_at.unwrap_or_else(|| self.clock().now()))
538            }
539            _ => None,
540        }
541    }
542
543    /// Write one event down with what a fetch gave as its image.
544    ///
545    /// A good frame is kept with the event in one write. A camera whose
546    /// frames were all bad is written down as a [`CameraDegradedPayload`] in
547    /// the event's place, carrying no frame. A camera that would not answer
548    /// leaves the event written without one, and the refusal recorded against
549    /// it; so does a store that could not write the frame's bytes
550    /// ([`StoreError::Io`](crate::store::StoreError::Io)), which stored
551    /// nothing of the write.
552    ///
553    /// # Errors
554    ///
555    /// Returns the store's own error when the event could not be written down
556    /// at all.
557    pub(crate) async fn write_with_frame<P: printobserver_types::EventPayload>(
558        &self,
559        print_id: Option<PrintId>,
560        payload: &P,
561        fetched: Option<(String, Frame)>,
562    ) -> Result<EventRecord, CoreError> {
563        self.write_body_with_frame(print_id, EventBody::of(payload)?, fetched)
564            .await
565    }
566
567    /// [`write_with_frame`](Self::write_with_frame) of a body already
568    /// rendered.
569    pub(crate) async fn write_body_with_frame(
570        &self,
571        print_id: Option<PrintId>,
572        body: EventBody,
573        fetched: Option<(String, Frame)>,
574    ) -> Result<EventRecord, CoreError> {
575        let draft = |body: EventBody| EventDraft {
576            print_id,
577            source: crate::kinds::system_source(),
578            received_at: self.clock().now(),
579            body,
580            raw: None,
581        };
582        let Some((url, fetched)) = fetched else {
583            return Ok(self.stores().events.append_event(draft(body)).await?);
584        };
585        let refused = match fetched {
586            Frame::Good(image) => {
587                let image = ImageDraft {
588                    source_url: Some(url),
589                    content_type: image.content_type,
590                    bytes: image.bytes,
591                };
592                match self
593                    .stores()
594                    .events
595                    .append_event_with_image(draft(body.clone()), image)
596                    .await
597                {
598                    Ok(event) => return Ok(event),
599                    // The frame's bytes could not be written, and nothing was
600                    // stored: the event is written without its frame. Any
601                    // other refusal is the event's own, and answered as one.
602                    Err(error @ crate::store::StoreError::Io { .. }) => error.to_string(),
603                    Err(error) => return Err(error.into()),
604                }
605            }
606            Frame::Failed(detail) => detail,
607            Frame::Degraded(degraded) => {
608                return self
609                    .append_system_event_to(print_id, EventBody::of(&degraded)?)
610                    .await;
611            }
612        };
613        let event = self.stores().events.append_event(draft(body)).await?;
614        self.record_port_failure_to(print_id, event.id, PortFailureSite::CameraLook, refused)
615            .await;
616        Ok(event)
617    }
618
619    /// Fetch frames from the camera until one is good, up to
620    /// [`FRAME_ATTEMPTS`] of them, each asked again while the camera answers a
621    /// server error.
622    pub(crate) async fn fetch_frame(&self, url: &str, print_id: Option<PrintId>) -> Frame {
623        let mut faults: Vec<FrameFault> = Vec::new();
624        while faults.len() < FRAME_ATTEMPTS as usize {
625            let fetched = match self.fetch_retrying(url, print_id).await {
626                Ok(fetched) => fetched,
627                Err(error) => return Frame::Failed(error.to_string()),
628            };
629            match self.vision().judge_frame(fetched).await {
630                Ok(good) => return Frame::Good(good),
631                Err(fault) => faults.push(fault),
632            }
633        }
634        let cause = match faults.last() {
635            Some(FrameFault::Undecodable { .. }) => FrameCause::Undecodable,
636            _ => FrameCause::Blank,
637        };
638        let detail = faults
639            .iter()
640            .enumerate()
641            .map(|(index, fault)| format!("frame {}: {fault}", index + 1))
642            .collect::<Vec<_>>()
643            .join("; ");
644        Frame::Degraded(CameraDegradedPayload {
645            attempts: FRAME_ATTEMPTS,
646            cause,
647            detail,
648        })
649    }
650
651    /// Fetch one frame, asking again after [`CameraRetry::backoff`] each time
652    /// the camera answers a server error, up to [`CameraRetry::retries`] more
653    /// times — and writing each such answer down, as it happens, before the
654    /// wait.
655    async fn fetch_retrying(
656        &self,
657        url: &str,
658        print_id: Option<PrintId>,
659    ) -> Result<FetchedImage, VisionError> {
660        let retry = self.config().camera_retry;
661        let attempts = retry.retries.saturating_add(1);
662        let mut attempt: u32 = 1;
663        loop {
664            let error = match self.vision().fetch_image(url.to_owned()).await {
665                Ok(fetched) => return Ok(fetched),
666                Err(error) => error,
667            };
668            let VisionError::Status {
669                status, excerpt, ..
670            } = &error
671            else {
672                return Err(error);
673            };
674            if !error.is_server_error() || attempt >= attempts {
675                return Err(error);
676            }
677            let retried = CameraRetryPayload {
678                attempt,
679                attempts,
680                status: *status,
681                excerpt: excerpt.clone(),
682                backoff_ms: u64::try_from(retry.backoff.as_millis()).unwrap_or(u64::MAX),
683            };
684            // A record that will not render, or that the store refuses, costs
685            // the fetch nothing: the retry is made whether or not it was
686            // written down.
687            if let Ok(body) = EventBody::of(&retried) {
688                let _ = self.append_system_event_to(print_id, body).await;
689            }
690            // A wait the system could not start is no reason to give up the
691            // frame: the next attempt is made at once instead.
692            let _ = crate::delay::Delay::new(retry.backoff).await;
693            attempt += 1;
694        }
695    }
696}
697
698/// How often, and how far apart, a fetch the camera answered with a server
699/// error is made again.
700///
701/// The defaults bound what a camera failing every attempt costs a scheduled
702/// check: with the vision adapter's own per-fetch timeout of five seconds,
703/// four attempts and three waits are at most about 21.5 s.
704#[derive(Debug, Clone, Copy, PartialEq, Eq)]
705pub struct CameraRetry {
706    /// How many more times a fetch is made after its first is answered with a
707    /// server error.
708    pub retries: u32,
709    /// How long after a server error the next attempt is made.
710    pub backoff: Duration,
711}
712
713impl Default for CameraRetry {
714    fn default() -> Self {
715        Self {
716            retries: DEFAULT_CAMERA_RETRIES,
717            backoff: DEFAULT_CAMERA_RETRY_BACKOFF,
718        }
719    }
720}
721
722/// How many more times a fetch the camera answered with a server error is
723/// made: three, so four attempts in all.
724pub const DEFAULT_CAMERA_RETRIES: u32 = 3;
725
726/// How long after a server error the next attempt at a frame is made.
727pub const DEFAULT_CAMERA_RETRY_BACKOFF: Duration = Duration::from_millis(500);
728
729/// How many frames one look or observation fetches before it records the
730/// camera degraded: the first, and two more.
731pub const FRAME_ATTEMPTS: u32 = 3;
732
733/// What a camera check's one fresh look came to.
734#[derive(Debug, Clone)]
735pub enum CheckLook {
736    /// No camera is configured, so nothing was asked or recorded.
737    NoCamera,
738    /// The camera gave a frame, stored with the look.
739    Framed {
740        /// The look, as it was written down.
741        look: EventRecord,
742        /// The stored frame.
743        frame: ImageRef,
744        /// Where its bytes are, on this host.
745        path: std::path::PathBuf,
746        /// Its bytes.
747        bytes: Vec<u8>,
748        /// The snapshot URL it came from.
749        url: String,
750    },
751    /// The camera answered and gave no frame: an error status, a body that is
752    /// no image, or a frame that does not decode.
753    NoFrame {
754        /// The look, written down with no frame.
755        look: EventRecord,
756        /// What the camera answered, in words.
757        detail: String,
758    },
759    /// The look failed: the camera could not be reached, took too long, or its
760    /// frame could not be stored.
761    Failed {
762        /// The look, written down with no frame.
763        look: EventRecord,
764        /// Why, in words.
765        detail: String,
766    },
767}
768
769/// What fetching a frame came to.
770#[derive(Debug)]
771pub(crate) enum Frame {
772    /// A good frame.
773    Good(FetchedImage),
774    /// The camera would not answer, in its own words.
775    Failed(String),
776    /// Every frame fetched was bad.
777    Degraded(CameraDegradedPayload),
778}