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