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 before the camera is
23//! asked for anything, and the frame is that event's image, so a print's whole
24//! record of what it looked like is in its history rather than in whatever
25//! scratch directory asked.
26
27use std::path::PathBuf;
28use std::time::Duration;
29
30use printobserver_printer_api::{JobSnapshot, PrinterSnapshot, PrinterState};
31use printobserver_types::contract::Sample;
32use printobserver_types::schemars::JsonSchema;
33use printobserver_types::serde::{Deserialize, Serialize};
34use printobserver_types::{EventBody, EventRecord, ImageRef, PrintId};
35
36use crate::error::CoreError;
37use crate::inbox::Arrival;
38use crate::kinds::{CameraLookPayload, PortFailureSite};
39use crate::supervisor::Supervisor;
40
41/// One fresh look at a print.
42///
43/// An answer rather than a record, so it admits fields beside its own the way
44/// every answer of the server does: a client that could not open the frame's
45/// path says so in a field of its own beside the rest of the answer.
46#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
47#[serde(crate = "printobserver_types::serde")]
48#[schemars(crate = "printobserver_types::schemars")]
49pub struct Look {
50    /// The look itself, as it was written into the print's history, carrying
51    /// the frame as its image when there is one.
52    pub event: EventRecord,
53    /// The events for this print that arrived while the look waited, oldest
54    /// first; the look returned early when there were any.
55    #[serde(default, skip_serializing_if = "Vec::is_empty")]
56    pub arrived: Vec<EventRecord>,
57    /// The frame the camera gave, absent when no camera is configured or it
58    /// gave none — which the history records as a port failure.
59    #[serde(default, skip_serializing_if = "Option::is_none")]
60    pub frame: Option<ImageRef>,
61    /// The absolute path the frame's bytes are at, on the supervisor's host.
62    #[serde(default, skip_serializing_if = "Option::is_none")]
63    pub image_path: Option<PathBuf>,
64    /// The printer's state now, absent when it could not be read.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub printer: Option<PrinterSnapshot>,
67    /// The job the printer reports now, absent when it could not be read.
68    #[serde(default, skip_serializing_if = "Option::is_none")]
69    pub job: Option<JobSnapshot>,
70    /// Whether the print is paused and the pause is the detector's, which is
71    /// what an adjustment asked for now would be applied under.
72    pub detector_paused: bool,
73}
74
75impl Sample for Look {
76    fn sample_full() -> Self {
77        Self {
78            event: EventRecord::sample_full(),
79            arrived: vec![EventRecord::sample_full()],
80            frame: Some(ImageRef::sample_full()),
81            image_path: Some(PathBuf::from("/var/lib/printobserver/images/look.jpg")),
82            printer: Some(PrinterSnapshot::sample_full()),
83            job: Some(JobSnapshot::sample_full()),
84            detector_paused: true,
85        }
86    }
87
88    fn sample_minimal() -> Self {
89        Self {
90            event: EventRecord::sample_minimal(),
91            arrived: Vec::new(),
92            frame: None,
93            image_path: None,
94            printer: None,
95            job: None,
96            detector_paused: false,
97        }
98    }
99}
100
101impl Supervisor {
102    /// Wait up to `wait` for anything to arrive for one print's running turn,
103    /// and take it.
104    ///
105    /// **This blocks the calling thread** for as long as it waits; call it
106    /// where a blocking wait is expected.
107    #[must_use]
108    pub fn await_arrivals(&self, print_id: PrintId, wait: Duration) -> Vec<Arrival> {
109        self.inboxes().wait_and_take(print_id, wait)
110    }
111
112    /// Write one look down, take a frame, and read the printer.
113    ///
114    /// # Errors
115    ///
116    /// Returns [`CoreError::NoSuchPrint`] when nothing is held under that
117    /// identifier, and the store's own error when the look could not be
118    /// written down. A camera or printer that will not answer is recorded and
119    /// answered as an absence rather than as an error.
120    ///
121    /// What arrived is delivered by the look written down, so a look that
122    /// could not be written down delivers nothing: what it was handed goes
123    /// back to the print's running turn, ahead of anything that arrived since,
124    /// for its next look or the turn after it.
125    pub async fn take_look(
126        &self,
127        print_id: PrintId,
128        waited: Duration,
129        arrived: Vec<Arrival>,
130    ) -> Result<Look, CoreError> {
131        let written = self.write_look_down(print_id, waited, &arrived).await;
132        let (print, mut event) = match written {
133            Ok(written) => written,
134            Err(error) => {
135                self.inboxes().put_back(print_id, arrived);
136                return Err(error);
137            }
138        };
139        let arrived: Vec<EventRecord> = arrived.into_iter().map(|each| each.event).collect();
140        let frame = match &self.config().camera_snapshot_url {
141            Some(url) => {
142                self.take_frame(print.id, &event, url.as_str().to_owned())
143                    .await
144            }
145            None => None,
146        };
147        let image_path = match &frame {
148            Some(reference) => self.image_path(reference).await,
149            None => None,
150        };
151        event.image.clone_from(&frame);
152        let printer = self.read_snapshot().await.ok();
153        let job = self.read_job().await.ok();
154        // `OctoPrint` clears a job's position when it is cancelled or fails,
155        // so every read that finds the print running is where it is next known
156        // to have stopped. The look is already written down and answered
157        // either way: a position the store would not keep costs this look
158        // nothing, and the next read records one.
159        // llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
160        if let Some(job) = &job
161            && print.ended_at.is_none()
162        {
163            let _ = self
164                .record_position_from(&print, job, self.clock().now())
165                .await;
166        }
167        let detector_paused = self.detector_paused(print.id)
168            && printer
169                .as_ref()
170                .is_some_and(|taken| taken.connection == PrinterState::Paused);
171        Ok(Look {
172            event,
173            arrived,
174            frame,
175            image_path,
176            printer,
177            job,
178            detector_paused,
179        })
180    }
181
182    /// Write one look down in its print's history, naming what it delivered.
183    async fn write_look_down(
184        &self,
185        print_id: PrintId,
186        waited: Duration,
187        arrived: &[Arrival],
188    ) -> Result<(crate::records::PrintRecord, EventRecord), CoreError> {
189        let print = self
190            .stores()
191            .prints
192            .print(print_id)
193            .await?
194            .ok_or(CoreError::NoSuchPrint { print_id })?;
195        let payload = CameraLookPayload {
196            waited_s: u32::try_from(waited.as_secs()).unwrap_or(u32::MAX),
197            delivered: arrived.iter().map(|each| each.event.id).collect(),
198        };
199        let event = self
200            .append_system_event(print.id, EventBody::of(&payload)?)
201            .await?;
202        Ok((print, event))
203    }
204
205    /// Fetch one frame from the camera and store it as a look's image,
206    /// recording either failure against the look.
207    pub(crate) async fn take_frame(
208        &self,
209        print_id: PrintId,
210        event: &EventRecord,
211        url: String,
212    ) -> Option<ImageRef> {
213        let fetched = match self.vision().fetch_image(url.clone()).await {
214            Ok(fetched) => fetched,
215            Err(error) => {
216                self.record_port_failure(
217                    print_id,
218                    event.id,
219                    PortFailureSite::CameraLook,
220                    error.to_string(),
221                )
222                .await;
223                return None;
224            }
225        };
226        match self
227            .stores()
228            .images
229            .put_image(
230                print_id,
231                event.id,
232                Some(url),
233                fetched.content_type,
234                fetched.bytes,
235            )
236            .await
237        {
238            Ok(record) => Some(ImageRef {
239                id: record.id,
240                sha256: record.sha256,
241            }),
242            Err(error) => {
243                self.record_port_failure(
244                    print_id,
245                    event.id,
246                    PortFailureSite::CameraLook,
247                    error.to_string(),
248                )
249                .await;
250                None
251            }
252        }
253    }
254}