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