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