Skip to main content

printobserver_core/
events.rs

1//! The loop: one normalized event becomes one supervised turn.
2//!
3//! The order is the contract. **The store's event append is the first thing the
4//! loop does**, before the image is written, before the printer is read and
5//! before a supervision turn is run, so that a failure of any of those is
6//! recorded against an event that is already in the history. The one failure
7//! that cannot be covered that way is the append itself: the store is where the
8//! record lives, so when the append fails there is nowhere to record it. The
9//! loop then calls no other port for that event, answers the store's own error
10//! to its caller rather than swallowing it, and goes on to handle the next
11//! event. Losing the alert that way is an availability failure; acting on the
12//! printer with no record behind it would be a safety one, and this crate takes
13//! the first over the second.
14//!
15//! # The context a turn reads is the one the loop collected
16//!
17//! A turn reads its print's context by running the command
18//! [`CoreConfig::context_command_for`](crate::CoreConfig::context_command_for)
19//! names, and that command reads it back through [`Supervisor::context`]. While
20//! a turn is running, that call answers the context the loop collected for the
21//! event that prompted it rather than a fresh read: what the agent reasons
22//! about is the state the event was handled at, not whatever the machine has
23//! drifted to since.
24
25use printobserver_store_api::HistoryQuery;
26use printobserver_supervisor_api::TurnRequest;
27use printobserver_types::{
28    EventPayload, EventRecord, EventSource, ImageRef, PortFailurePayload, PortFailureSite,
29    PrintContext, PrintId, PrintRecord, PrinterState, SessionPhase,
30    SupervisionSessionClosedPayload, SupervisionSessionOpenedPayload,
31};
32use printobserver_vision_api::NormalizedAlert;
33
34use crate::error::CoreError;
35use crate::supervisor::Supervisor;
36
37/// The states a print does not carry on from.
38///
39/// Read off the printer's own reported state rather than inferred from a
40/// notification's wording: the machine is the authority on whether it is still
41/// printing.
42pub const TERMINAL_STATES: [PrinterState; 3] = [
43    PrinterState::Operational,
44    PrinterState::Error,
45    PrinterState::Offline,
46];
47
48/// Obico's own identifier for the print an alert is about, when it names one.
49fn obico_print_id(payload: &EventPayload) -> Option<i64> {
50    match payload {
51        EventPayload::ObicoFailureAlert(alert) => alert.obico_print_id,
52        EventPayload::ObicoPrinterNotification(notification) => notification.obico_print_id,
53        _ => None,
54    }
55}
56
57/// The file an alert names, when it names one.
58fn alert_file_name(payload: &EventPayload) -> Option<String> {
59    match payload {
60        EventPayload::ObicoFailureAlert(alert) => alert.file_name.clone(),
61        EventPayload::ObicoPrinterNotification(notification) => notification.file_name.clone(),
62        _ => None,
63    }
64}
65
66impl Supervisor {
67    /// Handle one normalized event, from the store's own append to the turn.
68    ///
69    /// # Errors
70    ///
71    /// Returns the store's own error when the **initial event append** fails,
72    /// which is the one failure this loop cannot record anywhere; no other port
73    /// is called for that event, and a later event whose append succeeds is
74    /// handled to completion. Every other port failure this loop reaches is
75    /// recorded against the event rather than answered here.
76    pub async fn handle_event(&self, alert: NormalizedAlert) -> Result<EventRecord, CoreError> {
77        let print = self.resolve_print(&alert).await?;
78        let draft = printobserver_store_api::EventDraft {
79            print_id: print.as_ref().map(|record| record.id),
80            source: alert.source,
81            received_at: alert.received_at,
82            payload: alert.payload.clone(),
83            raw: Some(alert.raw.clone()),
84        };
85        let event = self
86            .store()
87            .append_event(draft)
88            .await
89            .map_err(CoreError::Store)?;
90        let Some(print) = print else {
91            return Ok(event);
92        };
93        let image = self
94            .write_image(&print, &event, alert.image_url.clone())
95            .await;
96        let terminal = self.supervise(&print, &event, image).await?;
97        if let Some(state) = terminal {
98            self.close_out_print(&print, &state).await?;
99        }
100        Ok(event)
101    }
102
103    /// The print an alert belongs to, opened if this system has not seen it.
104    async fn resolve_print(
105        &self,
106        alert: &NormalizedAlert,
107    ) -> Result<Option<PrintRecord>, CoreError> {
108        let Some(obico_print_id) = obico_print_id(&alert.payload) else {
109            return Ok(None);
110        };
111        if let Some(found) = self.store().print_by_obico_id(obico_print_id).await? {
112            return Ok(Some(found));
113        }
114        let opened = self
115            .store()
116            .open_print(Some(obico_print_id), alert_file_name(&alert.payload))
117            .await?;
118        Ok(Some(opened))
119    }
120
121    /// Fetch and store the image an alert names, recording either failure.
122    async fn write_image(
123        &self,
124        print: &PrintRecord,
125        event: &EventRecord,
126        image_url: Option<String>,
127    ) -> Option<ImageRef> {
128        let source_url = image_url?;
129        let fetched = match self.vision().fetch_image(source_url.clone()).await {
130            Ok(fetched) => fetched,
131            Err(error) => {
132                self.record_port_failure(
133                    print.id,
134                    event.id,
135                    PortFailureSite::ImageWrite,
136                    error.to_string(),
137                )
138                .await;
139                return None;
140            }
141        };
142        match self
143            .store()
144            .put_image(
145                print.id,
146                event.id,
147                Some(source_url),
148                fetched.content_type,
149                fetched.bytes,
150            )
151            .await
152        {
153            Ok(record) => Some(ImageRef {
154                id: record.id,
155                sha256: record.sha256,
156            }),
157            Err(error) => {
158                self.record_port_failure(
159                    print.id,
160                    event.id,
161                    PortFailureSite::ImageWrite,
162                    error.to_string(),
163                )
164                .await;
165                None
166            }
167        }
168    }
169
170    /// Collect the context, run one turn on it, and persist what it answered.
171    ///
172    /// Answers the terminal state the printer reported, when it reported one.
173    async fn supervise(
174        &self,
175        print: &PrintRecord,
176        event: &EventRecord,
177        image: Option<ImageRef>,
178    ) -> Result<Option<PrinterState>, CoreError> {
179        let guard = self.turns().acquire(print.id).await;
180        let context = self.gather_context(print, Some(event.id)).await?;
181        let terminal = context
182            .printer
183            .as_ref()
184            .map(|snapshot| snapshot.connection.clone())
185            .filter(|state| TERMINAL_STATES.contains(state));
186        let image_path = match &image {
187            Some(reference) => self.image_path(reference).await,
188            None => None,
189        };
190        let mut carried = event.clone();
191        carried.image = image.or(carried.image);
192        self.hold_context(print.id, context);
193        let turn = self
194            .agent()
195            .run_turn(TurnRequest {
196                print_id: print.id,
197                event: carried,
198                image_path,
199                context_command: self.config().context_command_for(print.id),
200            })
201            .await;
202        self.drop_context(print.id);
203        drop(guard);
204        match turn {
205            Ok(outcome) => {
206                if outcome.phase == SessionPhase::Created {
207                    self.append_system_event(
208                        print.id,
209                        EventPayload::SupervisionSessionOpened(SupervisionSessionOpenedPayload {
210                            session_name: outcome.session.session_name.clone(),
211                            harness_identity: outcome.session.harness_identity.clone(),
212                        }),
213                    )
214                    .await?;
215                }
216                let session_name = outcome.session.session_name.clone();
217                self.store().put_session(outcome.session).await?;
218                self.append_system_event(
219                    print.id,
220                    EventPayload::AgentAssessment(printobserver_types::AgentAssessmentPayload {
221                        session_name,
222                        assessment: outcome.assessment,
223                    }),
224                )
225                .await?;
226            }
227            Err(error) => {
228                self.record_port_failure(
229                    print.id,
230                    event.id,
231                    PortFailureSite::SupervisionTurn,
232                    error.to_string(),
233                )
234                .await;
235            }
236        }
237        Ok(terminal)
238    }
239
240    /// Everything a supervision turn is given about one print.
241    ///
242    /// While a turn is running for the print, this answers the context the loop
243    /// collected for the event that prompted it.
244    ///
245    /// # Errors
246    ///
247    /// Returns [`CoreError::NoSuchPrint`] when nothing is held under that
248    /// identifier, and the store's own error when the context could not be
249    /// read.
250    pub async fn context(&self, print_id: PrintId) -> Result<PrintContext, CoreError> {
251        if let Some(held) = self.held_context(print_id) {
252            return Ok(held);
253        }
254        let print = self
255            .store()
256            .print(print_id)
257            .await?
258            .ok_or(CoreError::NoSuchPrint { print_id })?;
259        self.gather_context(&print, None).await
260    }
261
262    /// Read one print's whole context, recording a printer read that fails.
263    ///
264    /// A read failure is recorded against the event being handled when there is
265    /// one; a context read that no event prompted has nowhere to record it and
266    /// carries the absence in the context itself, which is what an absent
267    /// `printer` or `job` means.
268    async fn gather_context(
269        &self,
270        print: &PrintRecord,
271        event_id: Option<printobserver_types::EventId>,
272    ) -> Result<PrintContext, CoreError> {
273        let printer = match self.read_snapshot().await {
274            Ok(snapshot) => Some(snapshot),
275            Err(error) => {
276                self.record_read_failure(
277                    print.id,
278                    event_id,
279                    PortFailureSite::PrinterSnapshot,
280                    error.to_string(),
281                )
282                .await;
283                None
284            }
285        };
286        let job = match self.read_job().await {
287            Ok(job) => Some(job),
288            Err(error) => {
289                self.record_read_failure(
290                    print.id,
291                    event_id,
292                    PortFailureSite::PrinterJob,
293                    error.to_string(),
294                )
295                .await;
296                None
297            }
298        };
299        let manifest = self.store().manifest(print.id).await?;
300        let bounds = self.bounds_for(Some(print), print.id).await?;
301        let interventions = self.store().active_interventions(print.id).await?;
302        let recent_events = self
303            .store()
304            .history(HistoryQuery {
305                print_id: print.id,
306                kinds: Vec::new(),
307                since: None,
308                until: None,
309                limit: Some(self.config().recent_events),
310            })
311            .await?;
312        let latest_image = recent_events.iter().find_map(|record| record.image.clone());
313        Ok(PrintContext {
314            print: print.clone(),
315            printer,
316            job,
317            manifest,
318            bounds: bounds.effective,
319            interventions,
320            recent_events,
321            latest_image,
322        })
323    }
324
325    /// Where one image's bytes are, when the store still has them.
326    async fn image_path(&self, image: &ImageRef) -> Option<std::path::PathBuf> {
327        match self.store().image(image.id).await {
328            Ok(printobserver_store_api::ImageLookup::Found { path, .. }) => Some(path),
329            _ => None,
330        }
331    }
332
333    /// End the print, expire what it had running, and close its session.
334    ///
335    /// The interventions are expired **before** the print is ended, because a
336    /// restoration is an action against the print and a print that has already
337    /// ended is one no action may be taken against.
338    async fn close_out_print(
339        &self,
340        print: &PrintRecord,
341        state: &PrinterState,
342    ) -> Result<(), CoreError> {
343        let reason = format!("the print reached {state:?}");
344        self.expire_all_active(print.id).await?;
345        self.store()
346            .end_print(print.id, state.clone(), self.clock().now(), reason.clone())
347            .await?;
348        let _ = self.agent().close_session(print.id, reason.clone()).await;
349        if let Some(session) = self.store().session(print.id).await? {
350            self.append_system_event(
351                print.id,
352                EventPayload::SupervisionSessionClosed(SupervisionSessionClosedPayload {
353                    session_name: session.session_name,
354                    close_reason: reason,
355                }),
356            )
357            .await?;
358        }
359        Ok(())
360    }
361
362    /// Append one event this system raised itself.
363    async fn append_system_event(
364        &self,
365        print_id: PrintId,
366        payload: EventPayload,
367    ) -> Result<EventRecord, CoreError> {
368        Ok(self
369            .store()
370            .append_event(printobserver_store_api::EventDraft {
371                print_id: Some(print_id),
372                source: EventSource::System,
373                received_at: self.clock().now(),
374                payload,
375                raw: None,
376            })
377            .await?)
378    }
379
380    /// Record a printer read that failed, when an event prompted the read.
381    async fn record_read_failure(
382        &self,
383        print_id: PrintId,
384        event_id: Option<printobserver_types::EventId>,
385        site: PortFailureSite,
386        detail: String,
387    ) {
388        if let Some(event_id) = event_id {
389            self.record_port_failure(print_id, event_id, site, detail)
390                .await;
391        }
392    }
393
394    /// Record that a port failed while one event was being handled.
395    ///
396    /// The event is already in the history by the time any of these sites is
397    /// reached, which is what gives the failure somewhere to be recorded.
398    /// Nothing is answered to the caller: the loop survives this and goes on.
399    async fn record_port_failure(
400        &self,
401        print_id: PrintId,
402        event_id: printobserver_types::EventId,
403        site: PortFailureSite,
404        detail: String,
405    ) {
406        let _ = self
407            .append_system_event(
408                print_id,
409                EventPayload::PortFailure(PortFailurePayload {
410                    event_id,
411                    site,
412                    detail,
413                }),
414            )
415            .await;
416    }
417}