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//! # Context reads gather the print's current state
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`]. Each
20//! read gathers the current printer, job and interventions, even while a turn
21//! is running, so an operator's completed action is visible immediately. The
22//! turn's event and situation still describe what prompted it; a look
23//! ([`crate::look`]) also takes a fresh camera frame.
24//!
25//! # One agent per print
26//!
27//! [`Supervisor::receive_event`] writes an event down and claims its print's
28//! turn, or — when a turn is already running for that print — hands the event
29//! to that turn through the print's inbox ([`crate::inbox`]), where its next
30//! look takes it. [`Supervisor::run_supervision`] runs a claimed turn and then
31//! one more, in the same session, for whatever arrived during it that it never
32//! took. A print that has ended starts no turn at all, and its inbox is
33//! released with whatever was still waiting in it.
34
35use crate::records::PrintRecord;
36use crate::store::{EventDraft, HistoryQuery, ImageLookup};
37use printobserver_printer_api::{JobSnapshot, PrinterState};
38use printobserver_supervisor_api::SessionPhase;
39use printobserver_supervisor_api::{
40    SupervisionSessionClosedPayload, SupervisionSessionOpenedPayload, TurnRequest, TurnSituation,
41};
42use printobserver_types::{EventBody, EventRecord, ImageRef, PrintId};
43use printobserver_vision_api::NormalizedAlert;
44
45use crate::context::PrintContext;
46use crate::error::CoreError;
47use crate::inbox::Arrival;
48use crate::kinds::{AgentAssessmentPayload, PortFailurePayload, PortFailureSite, system_source};
49use crate::listing::{self, ObservedJob, reached_reason};
50use crate::supervisor::Supervisor;
51
52/// One event written down, and the turn it claimed, when it claimed one.
53#[derive(Debug, Clone, PartialEq)]
54pub struct Received {
55    /// The event, as the store holds it.
56    pub event: EventRecord,
57    /// The turn it claimed: absent when it belongs to no print, to a print that
58    /// has ended, or was handed to the turn already running for its print.
59    pub turn: Option<PendingTurn>,
60}
61
62/// What became of one turn.
63enum Supervised {
64    /// It ran, and the printer was not in a terminal state.
65    Ran,
66    /// It ran, and the printer reported this terminal state.
67    Terminal(PrinterState),
68    /// The print had ended by the time the turn held it, so nothing ran.
69    Ended,
70}
71
72/// A turn one event claimed, to be run by [`Supervisor::run_supervision`].
73#[derive(Debug, Clone, PartialEq)]
74pub struct PendingTurn {
75    /// The print the turn is about.
76    print: PrintRecord,
77    /// The event that claimed it.
78    arrival: Arrival,
79    /// What was handed to the print before that event and never taken,
80    /// oldest first.
81    earlier: Vec<Arrival>,
82}
83
84impl PendingTurn {
85    /// The turn one arrival claimed, after what was handed over before it.
86    pub(crate) const fn new(print: PrintRecord, arrival: Arrival, earlier: Vec<Arrival>) -> Self {
87        Self {
88            print,
89            arrival,
90            earlier,
91        }
92    }
93}
94
95/// The print an alert belongs to, and whether resolving it opened one.
96enum Resolution {
97    /// The alert is about no print.
98    NoPrint,
99    /// A print this system already held.
100    Existing(PrintRecord),
101    /// A print opened for it now, which is owed its `print_started`.
102    Opened(PrintRecord),
103}
104
105impl Resolution {
106    /// The print, however it was found.
107    const fn print(&self) -> Option<&PrintRecord> {
108        match self {
109            Self::NoPrint => None,
110            Self::Existing(print) | Self::Opened(print) => Some(print),
111        }
112    }
113}
114
115/// The states a print does not carry on from.
116///
117/// Read off the printer's own reported state rather than inferred from a
118/// notification's wording: the machine is the authority on whether it is still
119/// printing.
120pub const TERMINAL_STATES: [PrinterState; 3] = [
121    PrinterState::Operational,
122    PrinterState::Error,
123    PrinterState::Offline,
124];
125
126impl Supervisor {
127    /// Handle one normalized event, from the store's own append to the turn.
128    ///
129    /// # Errors
130    ///
131    /// Returns the store's own error when the **initial event append** fails,
132    /// which is the one failure this loop cannot record anywhere; no other port
133    /// is called for that event, and a later event whose append succeeds is
134    /// handled to completion. Every other port failure this loop reaches is
135    /// recorded against the event rather than answered here — except the
136    /// writes that come after the event is already in the history and are
137    /// owed the spool ledger: a new print's `print_started`, and what a
138    /// filament-change signal the alert relays charges and marks. Those are
139    /// answered as the store's own error, the alert itself already written.
140    pub async fn handle_event(&self, alert: NormalizedAlert) -> Result<EventRecord, CoreError> {
141        let received = self.receive_event(alert).await?;
142        if let Some(turn) = received.turn {
143            self.run_supervision(turn).await?;
144        }
145        Ok(received.event)
146    }
147
148    /// Write one normalized event down, and say whether it needs a turn of
149    /// its own.
150    ///
151    /// The first half of [`Supervisor::handle_event`], for a caller that runs
152    /// the turn somewhere else so that the next event can be written down
153    /// while this one's turn is still running. An event for a print whose turn
154    /// is already running is handed to that turn and answers no turn of its
155    /// own: one agent per print, and what arrives reaches the agent already
156    /// watching it.
157    ///
158    /// # Errors
159    ///
160    /// Exactly as [`Supervisor::handle_event`]'s.
161    pub async fn receive_event(&self, alert: NormalizedAlert) -> Result<Received, CoreError> {
162        let resolution = self.resolve_print(&alert).await?;
163        let draft = EventDraft {
164            print_id: resolution.print().map(|record| record.id),
165            source: alert.source.clone(),
166            received_at: alert.received_at,
167            body: alert.body.clone(),
168            raw: Some(alert.raw.clone()),
169        };
170        let event = self
171            .stores()
172            .events
173            .append_event(draft)
174            .await
175            .map_err(CoreError::Store)?;
176        let print = match resolution {
177            Resolution::NoPrint => return Ok(Received { event, turn: None }),
178            Resolution::Existing(print) => print,
179            // llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
180            Resolution::Opened(print) => {
181                self.record_print_started(print.id, print.file_name.clone(), None, None)
182                    .await?;
183                print
184            }
185        };
186        let image = self
187            .write_image(&print, &event, alert.image_url.clone())
188            .await;
189        if print.ended_at.is_some() {
190            return Ok(Received { event, turn: None });
191        }
192        if let Some(signal) = alert.signal {
193            self.handle_signal(&print, signal, alert.kind()).await?;
194        }
195        let mut carried = event.clone();
196        carried.image = image.or(carried.image);
197        if let Some(detection) = alert.detection
198            && detection.paused_the_print
199        {
200            self.note_detector_pause(print.id, event.id, detection);
201        }
202        let arrival = Arrival {
203            event: carried,
204            detection: alert.detection,
205        };
206        let turn = self
207            .inboxes()
208            .claim_or_hand_over(print.id, arrival.clone())
209            .then(|| PendingTurn::new(print, arrival, Vec::new()));
210        Ok(Received { event, turn })
211    }
212
213    /// Run the turn one received event claimed, and one more for whatever
214    /// arrived during it that it never took, until nothing is left.
215    ///
216    /// The detector's pause the agent adjusted the print under is resumed as
217    /// each turn ends, when its grace has not already resumed it.
218    ///
219    /// # Errors
220    ///
221    /// Returns the store's own error when a turn's outcome could not be
222    /// recorded; a turn that fails is recorded rather than answered.
223    pub async fn run_supervision(&self, turn: PendingTurn) -> Result<(), CoreError> {
224        let PendingTurn {
225            print,
226            arrival,
227            earlier,
228        } = turn;
229        let mut next = Some((arrival, earlier));
230        while let Some((arrival, earlier)) = next {
231            let supervised = self.supervise(&print, &arrival, earlier).await;
232            if !matches!(supervised, Ok(Supervised::Ended)) {
233                self.resume_adjusted_detector_pause(print.id).await;
234            }
235            match supervised {
236                Ok(Supervised::Ran) => {}
237                Ok(Supervised::Ended) => {
238                    self.inboxes().release(print.id);
239                    self.forget_detector_pause(print.id);
240                    return Ok(());
241                }
242                Ok(Supervised::Terminal(state)) => {
243                    self.inboxes().release(print.id);
244                    let _turn = self.turns().acquire(print.id).await;
245                    return self
246                        .close_out_print(print.id, &state, &reached_reason(&state), None)
247                        .await
248                        .map(drop);
249                }
250                Err(error) => {
251                    self.inboxes().release(print.id);
252                    return Err(error);
253                }
254            }
255            next = self
256                .inboxes()
257                .next_or_release(print.id)
258                .and_then(|mut left| left.pop().map(|latest| (latest, left)));
259        }
260        Ok(())
261    }
262
263    /// The print an alert belongs to, opened if this system has not seen it.
264    ///
265    /// Correlated on the provider's own identifier the alert carries beside its
266    /// body, and never on the body by kind: which provider raised the alert is
267    /// the adapter's business, and this loop reads nothing an adapter declares.
268    ///
269    /// In order: the print already carrying that identifier; otherwise the most
270    /// recently opened print with no end recorded, no provider identifier, the
271    /// alert's own file name and a job the alert's start may be
272    /// ([`listing::may_have_started_it`]), which is a job somebody found before
273    /// the provider reported on it and which takes the identifier here;
274    /// otherwise a print opened for it. The file name is the one key the two
275    /// sides share — the provider names the job by the file the printer
276    /// reported, and the printer names it by that same file — and the start is
277    /// what tells that job from a later one of the same file.
278    ///
279    /// Nothing here reads the printer: an alert is written down before anything
280    /// is asked of a port, and a print a later job replaced is closed by the
281    /// next read that finds that job, not by an alert about it.
282    ///
283    /// Answers whether this opened it, so that the print's `print_started` is
284    /// written once the alert itself has been.
285    async fn resolve_print(&self, alert: &NormalizedAlert) -> Result<Resolution, CoreError> {
286        let Some(provider_print) = &alert.print else {
287            return Ok(Resolution::NoPrint);
288        };
289        let _resolving = self.resolving().await;
290        if let Some(found) = self
291            .stores()
292            .prints
293            .print_by_provider_id(provider_print.id)
294            .await?
295        {
296            return Ok(Resolution::Existing(found));
297        }
298        if let Some(file_name) = &provider_print.file_name {
299            let unattached = self
300                .stores()
301                .prints
302                .open_prints()
303                .await?
304                .into_iter()
305                .find(|open| {
306                    open.provider_print_id.is_none()
307                        && open.file_name.as_ref() == Some(file_name)
308                        && listing::may_have_started_it(open, provider_print.started_at)
309                });
310            if let Some(found) = unattached {
311                let attached = self
312                    .stores()
313                    .prints
314                    .attach_obico_print(found.id, provider_print.id)
315                    .await?;
316                return Ok(Resolution::Existing(attached));
317            }
318        }
319        let opened = self
320            .stores()
321            .prints
322            .open_print(Some(provider_print.id), provider_print.file_name.clone())
323            .await?;
324        Ok(Resolution::Opened(opened))
325    }
326
327    /// Fetch and store the image an alert names, recording either failure.
328    async fn write_image(
329        &self,
330        print: &PrintRecord,
331        event: &EventRecord,
332        image_url: Option<String>,
333    ) -> Option<ImageRef> {
334        let source_url = image_url?;
335        let fetched = match self.vision().fetch_image(source_url.clone()).await {
336            Ok(fetched) => fetched,
337            Err(error) => {
338                self.record_port_failure(
339                    print.id,
340                    event.id,
341                    PortFailureSite::ImageWrite,
342                    error.to_string(),
343                )
344                .await;
345                return None;
346            }
347        };
348        match self
349            .stores()
350            .images
351            .put_image(
352                print.id,
353                event.id,
354                Some(source_url),
355                fetched.content_type,
356                fetched.bytes,
357            )
358            .await
359        {
360            Ok(record) => Some(ImageRef {
361                id: record.id,
362                sha256: record.sha256,
363            }),
364            Err(error) => {
365                self.record_port_failure(
366                    print.id,
367                    event.id,
368                    PortFailureSite::ImageWrite,
369                    error.to_string(),
370                )
371                .await;
372                None
373            }
374        }
375    }
376
377    /// Collect the context, run one turn on it, and persist what it answered.
378    ///
379    /// `earlier` is what arrived for the print before `arrival` while an
380    /// earlier turn was running and that turn never took, oldest first.
381    ///
382    /// Answers the terminal state the printer reported, when it reported one,
383    /// and runs nothing for a print that ended — at a read that found its job
384    /// over — before this turn came to hold it.
385    async fn supervise(
386        &self,
387        print: &PrintRecord,
388        arrival: &Arrival,
389        earlier: Vec<Arrival>,
390    ) -> Result<Supervised, CoreError> {
391        let event = &arrival.event;
392        let guard = self.turns().acquire(print.id).await;
393        if self
394            .stores()
395            .prints
396            .print(print.id)
397            .await?
398            .is_none_or(|held| held.ended_at.is_some())
399        {
400            return Ok(Supervised::Ended);
401        }
402        let context = self.gather_context(print, Some(event.id)).await?;
403        let printer_state = context
404            .printer
405            .as_ref()
406            .map(|snapshot| snapshot.connection.clone());
407        let terminal = printer_state
408            .clone()
409            .filter(|state| TERMINAL_STATES.contains(state));
410        let image_path = match &event.image {
411            Some(reference) => self.image_path(reference).await,
412            None => None,
413        };
414        let situation = TurnSituation {
415            printer_state,
416            detector_warned: arrival.detection.map(|detection| detection.warning),
417            detector_paused_the_print: arrival
418                .detection
419                .map(|detection| detection.paused_the_print),
420            arrived_while_busy: earlier.into_iter().map(|left| left.event).collect(),
421        };
422        // The turn's credentials are bound to it from here, and revoked the
423        // moment it returns — whatever it returned — and when this future is
424        // abandoned, because dropping what was opened revokes too.
425        let opened = self.open_turn(print.id);
426        let turn = self
427            .agent()
428            .run_turn(
429                TurnRequest {
430                    print_id: print.id,
431                    event: event.clone(),
432                    image_path,
433                    context_command: self.config().context_command_for(print.id),
434                    situation,
435                },
436                opened.access(),
437            )
438            .await;
439        opened.revoke();
440        drop(guard);
441        match turn {
442            Ok(outcome) => {
443                if outcome.phase == SessionPhase::Created {
444                    self.append_system_event(
445                        print.id,
446                        EventBody::of(&SupervisionSessionOpenedPayload {
447                            session_name: outcome.session.session_name.clone(),
448                            harness_identity: outcome.session.harness_identity.clone(),
449                        })?,
450                    )
451                    .await?;
452                }
453                let session_name = outcome.session.session_name.clone();
454                self.stores().sessions.put_session(outcome.session).await?;
455                self.append_system_event(
456                    print.id,
457                    EventBody::of(&AgentAssessmentPayload {
458                        session_name,
459                        assessment: outcome.assessment,
460                    })?,
461                )
462                .await?;
463            }
464            Err(error) => {
465                self.record_port_failure(
466                    print.id,
467                    event.id,
468                    PortFailureSite::SupervisionTurn,
469                    error.to_string(),
470                )
471                .await;
472            }
473        }
474        Ok(terminal.map_or(Supervised::Ran, Supervised::Terminal))
475    }
476
477    /// Gather the current context of one print, including while its
478    /// supervision turn is running.
479    ///
480    /// # Errors
481    ///
482    /// Returns [`CoreError::NoSuchPrint`] when nothing is held under that
483    /// identifier, and the store's own error when the context could not be
484    /// read.
485    pub async fn context(&self, print_id: PrintId) -> Result<PrintContext, CoreError> {
486        let print = self
487            .stores()
488            .prints
489            .print(print_id)
490            .await?
491            .ok_or(CoreError::NoSuchPrint { print_id })?;
492        self.gather_context(&print, None).await
493    }
494
495    /// Read one print's whole context, recording a printer read that fails.
496    ///
497    /// A read failure is recorded against the event being handled when there is
498    /// one; a context read that no event prompted has nowhere to record it and
499    /// carries the absence in the context itself, which is what an absent
500    /// `printer` or `job` means.
501    ///
502    /// The job read settles the open prints exactly as the listing's does
503    /// ([`crate::listing`]) before the rest of the context is read: a job found
504    /// over closes the print, a later job of its file closes it as replaced,
505    /// and a job found to be its own is recorded on it — so the context
506    /// answered is the print as it now stands. Within a turn the turn holds the
507    /// print, and that turn closes it.
508    async fn gather_context(
509        &self,
510        print: &PrintRecord,
511        event_id: Option<printobserver_types::EventId>,
512    ) -> Result<PrintContext, CoreError> {
513        let printer = match self.read_snapshot().await {
514            Ok(snapshot) => Some(snapshot),
515            Err(error) => {
516                self.record_read_failure(
517                    print.id,
518                    event_id,
519                    PortFailureSite::PrinterSnapshot,
520                    error.to_string(),
521                )
522                .await;
523                None
524            }
525        };
526        // The job is read and settled under one hold on resolution, as the
527        // listing's is. A start holds it from the read that chooses its print
528        // until the printer has been asked to start, so a job read before that
529        // hold and settled after it would be the idle machine the start has
530        // since moved, and would close the print the start had just opened.
531        let resolving = self.resolving().await;
532        let job = match self.read_job().await {
533            Ok(job) => Some(job),
534            Err(error) => {
535                self.record_read_failure(
536                    print.id,
537                    event_id,
538                    PortFailureSite::PrinterJob,
539                    error.to_string(),
540                )
541                .await;
542                None
543            }
544        };
545        let print = match &job {
546            Some(job) if print.ended_at.is_none() => self.settle_for_context(print, job).await?,
547            _ => print.clone(),
548        };
549        drop(resolving);
550        let print = &print;
551        let manifest = self.stores().prints.manifest(print.id).await?;
552        let bounds = self.bounds_for(Some(print), print.id).await?;
553        let interventions = self.stores().actions.active_interventions(print.id).await?;
554        let recent_events = self
555            .stores()
556            .events
557            .history(HistoryQuery {
558                print_id: print.id,
559                kinds: Vec::new(),
560                since: None,
561                until: None,
562                limit: Some(self.config().recent_events),
563            })
564            .await?;
565        let latest_image = recent_events.iter().find_map(|record| record.image.clone());
566        Ok(PrintContext {
567            print: print.clone(),
568            printer,
569            job,
570            manifest,
571            bounds: bounds.effective,
572            interventions,
573            recent_events,
574            latest_image,
575        })
576    }
577
578    /// Where one image's bytes are, when the store still has them.
579    pub(crate) async fn image_path(&self, image: &ImageRef) -> Option<std::path::PathBuf> {
580        match self.stores().images.image(image.id).await {
581            Ok(ImageLookup::Found { path, .. }) => Some(path),
582            _ => None,
583        }
584    }
585
586    /// Settle the open prints against the job a context read found, and
587    /// answer the print the context is about as that left it.
588    ///
589    /// The caller holds resolution from before it read that job.
590    async fn settle_for_context(
591        &self,
592        print: &PrintRecord,
593        job: &JobSnapshot,
594    ) -> Result<PrintRecord, CoreError> {
595        let observed = ObservedJob {
596            job: job.clone(),
597            observed_at: self.clock().now(),
598        };
599        let settled = self.settle_open_prints(&observed).await?;
600        match settled.running {
601            Some(running) if running.id == print.id => Ok(running),
602            _ if settled.closed.contains(&print.id) => Ok(self
603                .stores()
604                .prints
605                .print(print.id)
606                .await?
607                .unwrap_or_else(|| print.clone())),
608            _ => Ok(print.clone()),
609        }
610    }
611
612    /// End the print, expire what it had running, and close its session.
613    ///
614    /// The interventions are expired **before** the print is ended, because a
615    /// restoration is an action against the print and a print that has already
616    /// ended is one no action may be taken against.
617    ///
618    /// The caller holds the print's turn, so no turn is acting on it while it
619    /// closes. Answers whether this closed it: a print already ended — by
620    /// another read, or by the turn that held it — is left as it ended.
621    ///
622    /// The print's filament is settled after its interventions are expired
623    /// and before it is ended ([`crate::accounting`]): a crash between the two
624    /// leaves a settled, open print, which the next close-out only ends.
625    /// `closing_job` is the job read that found the print over, when there
626    /// was one; without it the settlement reads the job itself.
627    pub(crate) async fn close_out_print(
628        &self,
629        print_id: PrintId,
630        state: &PrinterState,
631        reason: &str,
632        closing_job: Option<&JobSnapshot>,
633    ) -> Result<bool, CoreError> {
634        let print = match self.stores().prints.print(print_id).await? {
635            Some(print) if print.ended_at.is_none() => print,
636            _ => return Ok(false),
637        };
638        self.forget_detector_pause(print_id);
639        self.expire_all_active(print_id).await?;
640        self.settle_filament(&print, state, reason, closing_job)
641            .await?;
642        self.stores()
643            .prints
644            .end_print(
645                print_id,
646                state.clone(),
647                self.clock().now(),
648                reason.to_owned(),
649            )
650            .await?;
651        let _ = self
652            .agent()
653            .close_session(print_id, reason.to_owned())
654            .await;
655        if let Some(session) = self.stores().sessions.session(print_id).await? {
656            self.append_system_event(
657                print_id,
658                EventBody::of(&SupervisionSessionClosedPayload {
659                    session_name: session.session_name,
660                    close_reason: reason.to_owned(),
661                })?,
662            )
663            .await?;
664        }
665        Ok(true)
666    }
667
668    /// Append one event this system raised itself.
669    pub(crate) async fn append_system_event(
670        &self,
671        print_id: PrintId,
672        body: EventBody,
673    ) -> Result<EventRecord, CoreError> {
674        Ok(self
675            .stores()
676            .events
677            .append_event(EventDraft {
678                print_id: Some(print_id),
679                source: system_source(),
680                received_at: self.clock().now(),
681                body,
682                raw: None,
683            })
684            .await?)
685    }
686
687    /// Record a printer read that failed, when an event prompted the read.
688    async fn record_read_failure(
689        &self,
690        print_id: PrintId,
691        event_id: Option<printobserver_types::EventId>,
692        site: PortFailureSite,
693        detail: String,
694    ) {
695        if let Some(event_id) = event_id {
696            self.record_port_failure(print_id, event_id, site, detail)
697                .await;
698        }
699    }
700
701    /// Record that a port failed while one event was being handled.
702    ///
703    /// The event is already in the history by the time any of these sites is
704    /// reached, which is what gives the failure somewhere to be recorded.
705    /// Nothing is answered to the caller: the loop survives this and goes on.
706    pub(crate) async fn record_port_failure(
707        &self,
708        print_id: PrintId,
709        event_id: printobserver_types::EventId,
710        site: PortFailureSite,
711        detail: String,
712    ) {
713        // A record that will not render is dropped exactly as one the store
714        // refuses is: the failure it was about has already been answered, and
715        // the loop survives not having written it down.
716        let Ok(body) = EventBody::of(&PortFailurePayload {
717            event_id,
718            site,
719            detail,
720        }) else {
721            return;
722        };
723        let _ = self.append_system_event(print_id, body).await;
724    }
725}