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