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