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        if let Some(job) = &job
160            && print.ended_at.is_none()
161        {
162            let _ = self
163                .record_position_from(&print, job, self.clock().now())
164                .await;
165        }
166        let detector_paused = self.detector_paused(print.id)
167            && printer
168                .as_ref()
169                .is_some_and(|taken| taken.connection == PrinterState::Paused);
170        Ok(Look {
171            event,
172            arrived,
173            frame,
174            image_path,
175            printer,
176            job,
177            detector_paused,
178        })
179    }
180
181    /// Write one look down in its print's history, naming what it delivered.
182    async fn write_look_down(
183        &self,
184        print_id: PrintId,
185        waited: Duration,
186        arrived: &[Arrival],
187    ) -> Result<(crate::records::PrintRecord, EventRecord), CoreError> {
188        let print = self
189            .stores()
190            .prints
191            .print(print_id)
192            .await?
193            .ok_or(CoreError::NoSuchPrint { print_id })?;
194        let payload = CameraLookPayload {
195            waited_s: u32::try_from(waited.as_secs()).unwrap_or(u32::MAX),
196            delivered: arrived.iter().map(|each| each.event.id).collect(),
197        };
198        let event = self
199            .append_system_event(print.id, EventBody::of(&payload)?)
200            .await?;
201        Ok((print, event))
202    }
203
204    /// Fetch one frame from the camera and store it as a look's image,
205    /// recording either failure against the look.
206    pub(crate) async fn take_frame(
207        &self,
208        print_id: PrintId,
209        event: &EventRecord,
210        url: String,
211    ) -> Option<ImageRef> {
212        let fetched = match self.vision().fetch_image(url.clone()).await {
213            Ok(fetched) => fetched,
214            Err(error) => {
215                self.record_port_failure(
216                    print_id,
217                    event.id,
218                    PortFailureSite::CameraLook,
219                    error.to_string(),
220                )
221                .await;
222                return None;
223            }
224        };
225        match self
226            .stores()
227            .images
228            .put_image(
229                print_id,
230                event.id,
231                Some(url),
232                fetched.content_type,
233                fetched.bytes,
234            )
235            .await
236        {
237            Ok(record) => Some(ImageRef {
238                id: record.id,
239                sha256: record.sha256,
240            }),
241            Err(error) => {
242                self.record_port_failure(
243                    print_id,
244                    event.id,
245                    PortFailureSite::CameraLook,
246                    error.to_string(),
247                )
248                .await;
249                None
250            }
251        }
252    }
253}