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.
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//! # A frame that shows nothing is not handed over as one
27//!
28//! Each frame is judged before it is kept
29//! ([`VisionPort::judge_frame`](printobserver_vision_api::VisionPort::judge_frame)):
30//! one that does not decode whole, or decodes near-uniform grey, is fetched
31//! again, up to [`FRAME_ATTEMPTS`] in all. The first good one is the look's
32//! frame. When every one is bad the look is written down as a
33//! [`CameraDegradedPayload`] in its place, carrying no frame, so nothing the
34//! camera could not show is handed to the agent as a picture of the print. A
35//! camera that will not answer at all is a port failure recorded against the
36//! look, as it always was.
37
38use std::path::PathBuf;
39use std::time::Duration;
40
41use printobserver_printer_api::{JobSnapshot, PrinterSnapshot, PrinterState};
42use printobserver_types::contract::Sample;
43use printobserver_types::schemars::JsonSchema;
44use printobserver_types::serde::{Deserialize, Serialize};
45use printobserver_types::{EventBody, EventRecord, ImageRef, PrintId};
46
47use crate::error::CoreError;
48use crate::inbox::Arrival;
49use crate::kinds::{CameraDegradedPayload, CameraLookPayload, FrameCause, PortFailureSite};
50use crate::supervisor::Supervisor;
51use printobserver_vision_api::{FetchedImage, FrameFault};
52
53/// One fresh look at a print.
54///
55/// An answer rather than a record, so it admits fields beside its own the way
56/// every answer of the server does: a client that could not open the frame's
57/// path says so in a field of its own beside the rest of the answer.
58#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
59#[serde(crate = "printobserver_types::serde")]
60#[schemars(crate = "printobserver_types::schemars")]
61pub struct Look {
62    /// The look itself, as it was written into the print's history, carrying
63    /// the frame as its image when there is one.
64    pub event: EventRecord,
65    /// The events for this print that arrived while the look waited, oldest
66    /// first; the look returned early when there were any.
67    #[serde(default, skip_serializing_if = "Vec::is_empty")]
68    pub arrived: Vec<EventRecord>,
69    /// The frame the camera gave, absent when no camera is configured or it
70    /// gave none — which the history records as a port failure.
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub frame: Option<ImageRef>,
73    /// The absolute path the frame's bytes are at, on the supervisor's host.
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    pub image_path: Option<PathBuf>,
76    /// The printer's state now, absent when it could not be read.
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    pub printer: Option<PrinterSnapshot>,
79    /// The job the printer reports now, absent when it could not be read.
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    pub job: Option<JobSnapshot>,
82    /// Whether the print is paused and the pause is the detector's, which is
83    /// what an adjustment asked for now would be applied under.
84    pub detector_paused: bool,
85}
86
87impl Sample for Look {
88    fn sample_full() -> Self {
89        Self {
90            event: EventRecord::sample_full(),
91            arrived: vec![EventRecord::sample_full()],
92            frame: Some(ImageRef::sample_full()),
93            image_path: Some(PathBuf::from("/var/lib/printobserver/images/look.jpg")),
94            printer: Some(PrinterSnapshot::sample_full()),
95            job: Some(JobSnapshot::sample_full()),
96            detector_paused: true,
97        }
98    }
99
100    fn sample_minimal() -> Self {
101        Self {
102            event: EventRecord::sample_minimal(),
103            arrived: Vec::new(),
104            frame: None,
105            image_path: None,
106            printer: None,
107            job: None,
108            detector_paused: false,
109        }
110    }
111}
112
113impl Supervisor {
114    /// Wait up to `wait` for anything to arrive for one print's running turn,
115    /// and take it.
116    ///
117    /// **This blocks the calling thread** for as long as it waits; call it
118    /// where a blocking wait is expected.
119    #[must_use]
120    pub fn await_arrivals(&self, print_id: PrintId, wait: Duration) -> Vec<Arrival> {
121        self.inboxes().wait_and_take(print_id, wait)
122    }
123
124    /// Write one look down, take a frame, and read the printer.
125    ///
126    /// # Errors
127    ///
128    /// Returns [`CoreError::NoSuchPrint`] when nothing is held under that
129    /// identifier, and the store's own error when the look could not be
130    /// written down. A camera or printer that will not answer is recorded and
131    /// answered as an absence rather than as an error.
132    ///
133    /// What arrived is delivered by the look written down, so a look that
134    /// could not be written down delivers nothing: what it was handed goes
135    /// back to the print's running turn, ahead of anything that arrived since,
136    /// for its next look or the turn after it.
137    pub async fn take_look(
138        &self,
139        print_id: PrintId,
140        waited: Duration,
141        arrived: Vec<Arrival>,
142    ) -> Result<Look, CoreError> {
143        let url = self
144            .config()
145            .camera_snapshot_url
146            .as_ref()
147            .map(|url| url.as_str().to_owned());
148        let fetched = match &url {
149            Some(url) => Some(self.fetch_frame(url).await),
150            None => None,
151        };
152        let written = match &fetched {
153            Some(Frame::Degraded(degraded)) => self.write_degraded_down(print_id, degraded).await,
154            _ => self.write_look_down(print_id, waited, &arrived).await,
155        };
156        let (print, mut event) = match written {
157            Ok(written) => written,
158            Err(error) => {
159                self.inboxes().put_back(print_id, arrived);
160                return Err(error);
161            }
162        };
163        let arrived: Vec<EventRecord> = arrived.into_iter().map(|each| each.event).collect();
164        let frame = match (fetched, url) {
165            (Some(fetched), Some(url)) => self.keep_frame(print.id, &event, url, fetched).await,
166            _ => None,
167        };
168        let image_path = match &frame {
169            Some(reference) => self.image_path(reference).await,
170            None => None,
171        };
172        event.image.clone_from(&frame);
173        let printer = self.read_snapshot().await.ok();
174        let job = self.read_job().await.ok();
175        // `OctoPrint` clears a job's position when it is cancelled or fails,
176        // so every read that finds the print running is where it is next known
177        // to have stopped. The look is already written down and answered
178        // either way: a position the store would not keep costs this look
179        // nothing, and the next read records one.
180        if let Some(job) = &job
181            && print.ended_at.is_none()
182        {
183            let _ = self
184                .record_position_from(&print, job, self.clock().now())
185                .await;
186        }
187        let detector_paused = self.detector_paused(print.id)
188            && printer
189                .as_ref()
190                .is_some_and(|taken| taken.connection == PrinterState::Paused);
191        Ok(Look {
192            event,
193            arrived,
194            frame,
195            image_path,
196            printer,
197            job,
198            detector_paused,
199        })
200    }
201
202    /// Write one degraded look down in its print's history, in place of the
203    /// look.
204    async fn write_degraded_down(
205        &self,
206        print_id: PrintId,
207        degraded: &CameraDegradedPayload,
208    ) -> Result<(crate::records::PrintRecord, EventRecord), CoreError> {
209        let print = self
210            .stores()
211            .prints
212            .print(print_id)
213            .await?
214            .ok_or(CoreError::NoSuchPrint { print_id })?;
215        let event = self
216            .append_system_event(print.id, EventBody::of(degraded)?)
217            .await?;
218        Ok((print, event))
219    }
220
221    /// Write one look down in its print's history, naming what it delivered.
222    async fn write_look_down(
223        &self,
224        print_id: PrintId,
225        waited: Duration,
226        arrived: &[Arrival],
227    ) -> Result<(crate::records::PrintRecord, EventRecord), CoreError> {
228        let print = self
229            .stores()
230            .prints
231            .print(print_id)
232            .await?
233            .ok_or(CoreError::NoSuchPrint { print_id })?;
234        let payload = CameraLookPayload {
235            waited_s: u32::try_from(waited.as_secs()).unwrap_or(u32::MAX),
236            delivered: arrived.iter().map(|each| each.event.id).collect(),
237        };
238        let event = self
239            .append_system_event(print.id, EventBody::of(&payload)?)
240            .await?;
241        Ok((print, event))
242    }
243
244    /// Fetch frames from the camera until one is good, up to
245    /// [`FRAME_ATTEMPTS`] of them.
246    pub(crate) async fn fetch_frame(&self, url: &str) -> Frame {
247        let mut faults: Vec<FrameFault> = Vec::new();
248        while faults.len() < FRAME_ATTEMPTS as usize {
249            let fetched = match self.vision().fetch_image(url.to_owned()).await {
250                Ok(fetched) => fetched,
251                Err(error) => return Frame::Failed(error.to_string()),
252            };
253            match self.vision().judge_frame(fetched).await {
254                Ok(good) => return Frame::Good(good),
255                Err(fault) => faults.push(fault),
256            }
257        }
258        let cause = match faults.last() {
259            Some(FrameFault::Undecodable { .. }) => FrameCause::Undecodable,
260            _ => FrameCause::Blank,
261        };
262        let detail = faults
263            .iter()
264            .enumerate()
265            .map(|(index, fault)| format!("frame {}: {fault}", index + 1))
266            .collect::<Vec<_>>()
267            .join("; ");
268        Frame::Degraded(CameraDegradedPayload {
269            attempts: FRAME_ATTEMPTS,
270            cause,
271            detail,
272        })
273    }
274
275    /// Keep what one fetch gave as an event's image: a good frame stored,
276    /// a camera that would not answer recorded against the event, and a
277    /// degraded one kept as nothing.
278    pub(crate) async fn keep_frame(
279        &self,
280        print_id: PrintId,
281        event: &EventRecord,
282        url: String,
283        fetched: Frame,
284    ) -> Option<ImageRef> {
285        let image = match fetched {
286            Frame::Good(image) => image,
287            Frame::Failed(detail) => {
288                self.record_port_failure(print_id, event.id, PortFailureSite::CameraLook, detail)
289                    .await;
290                return None;
291            }
292            Frame::Degraded(_) => return None,
293        };
294        match self
295            .stores()
296            .images
297            .put_image(
298                print_id,
299                event.id,
300                Some(url),
301                image.content_type,
302                image.bytes,
303            )
304            .await
305        {
306            Ok(record) => Some(ImageRef {
307                id: record.id,
308                sha256: record.sha256,
309            }),
310            Err(error) => {
311                self.record_port_failure(
312                    print_id,
313                    event.id,
314                    PortFailureSite::CameraLook,
315                    error.to_string(),
316                )
317                .await;
318                None
319            }
320        }
321    }
322}
323
324/// How many frames one look or observation fetches before it records the
325/// camera degraded: the first, and two more.
326pub const FRAME_ATTEMPTS: u32 = 3;
327
328/// What fetching a frame came to.
329#[derive(Debug)]
330pub(crate) enum Frame {
331    /// A good frame.
332    Good(FetchedImage),
333    /// The camera would not answer, in its own words.
334    Failed(String),
335    /// Every frame fetched was bad.
336    Degraded(CameraDegradedPayload),
337}