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