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;
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 = self
186            .write_image(&print, &event, alert.image_url.clone())
187            .await;
188        if print.ended_at.is_some() {
189            return Ok(Received { event, turn: None });
190        }
191        if let Some(signal) = alert.signal {
192            self.handle_signal(&print, signal, alert.kind()).await?;
193        }
194        let mut carried = event.clone();
195        carried.image = image.or(carried.image);
196        if let Some(detection) = alert.detection
197            && detection.paused_the_print
198        {
199            self.note_detector_pause(print.id, event.id, detection);
200        }
201        let arrival = Arrival {
202            event: carried,
203            detection: alert.detection,
204        };
205        let turn = self
206            .inboxes()
207            .claim_or_hand_over(print.id, arrival.clone())
208            .then(|| PendingTurn::new(print, arrival, Vec::new()));
209        Ok(Received { event, turn })
210    }
211
212    /// Run the turn one received event claimed, and one more for whatever
213    /// arrived during it that it never took, until nothing is left.
214    ///
215    /// The detector's pause the agent adjusted the print under is resumed as
216    /// each turn ends, when its grace has not already resumed it.
217    ///
218    /// # Errors
219    ///
220    /// Returns the store's own error when a turn's outcome could not be
221    /// recorded; a turn that fails is recorded rather than answered.
222    pub async fn run_supervision(&self, turn: PendingTurn) -> Result<(), CoreError> {
223        let PendingTurn {
224            print,
225            arrival,
226            earlier,
227        } = turn;
228        let mut next = Some((arrival, earlier));
229        while let Some((arrival, earlier)) = next {
230            let supervised = self.supervise(&print, &arrival, earlier).await;
231            if !matches!(supervised, Ok(Supervised::Ended)) {
232                self.resume_adjusted_detector_pause(print.id).await;
233            }
234            match supervised {
235                Ok(Supervised::Ran) => {}
236                Ok(Supervised::Ended) => {
237                    self.inboxes().release(print.id);
238                    self.forget_detector_pause(print.id);
239                    return Ok(());
240                }
241                Ok(Supervised::Terminal(state)) => {
242                    self.inboxes().release(print.id);
243                    let _turn = self.turns().acquire(print.id).await;
244                    return self
245                        .close_out_print(print.id, &state, &reached_reason(&state), None)
246                        .await
247                        .map(drop);
248                }
249                Err(error) => {
250                    self.inboxes().release(print.id);
251                    return Err(error);
252                }
253            }
254            next = self
255                .inboxes()
256                .next_or_release(print.id)
257                .and_then(|mut left| left.pop().map(|latest| (latest, left)));
258        }
259        Ok(())
260    }
261
262    /// The print an alert belongs to, opened if this system has not seen it.
263    ///
264    /// Correlated on the provider's own identifier the alert carries beside its
265    /// body, and never on the body by kind: which provider raised the alert is
266    /// the adapter's business, and this loop reads nothing an adapter declares.
267    ///
268    /// In order: the print already carrying that identifier; otherwise the most
269    /// recently opened print with no end recorded, no provider identifier, the
270    /// alert's own file name and a job the alert's start may be
271    /// ([`listing::may_have_started_it`]), which is a job somebody found before
272    /// the provider reported on it and which takes the identifier here;
273    /// otherwise a print opened for it. The file name is the one key the two
274    /// sides share — the provider names the job by the file the printer
275    /// reported, and the printer names it by that same file — and the start is
276    /// what tells that job from a later one of the same file.
277    ///
278    /// Nothing here reads the printer: an alert is written down before anything
279    /// is asked of a port, and a print a later job replaced is closed by the
280    /// next read that finds that job, not by an alert about it.
281    ///
282    /// Answers whether this opened it, so that the print's `print_started` is
283    /// written once the alert itself has been.
284    async fn resolve_print(&self, alert: &NormalizedAlert) -> Result<Resolution, CoreError> {
285        let Some(provider_print) = &alert.print else {
286            return Ok(Resolution::NoPrint);
287        };
288        let _resolving = self.resolving().await;
289        if let Some(found) = self
290            .stores()
291            .prints
292            .print_by_provider_id(provider_print.id)
293            .await?
294        {
295            return Ok(Resolution::Existing(found));
296        }
297        if let Some(file_name) = &provider_print.file_name {
298            let unattached = self
299                .stores()
300                .prints
301                .open_prints()
302                .await?
303                .into_iter()
304                .find(|open| {
305                    open.provider_print_id.is_none()
306                        && open.file_name.as_ref() == Some(file_name)
307                        && listing::may_have_started_it(open, provider_print.started_at)
308                });
309            if let Some(found) = unattached {
310                let attached = self
311                    .stores()
312                    .prints
313                    .attach_obico_print(found.id, provider_print.id)
314                    .await?;
315                return Ok(Resolution::Existing(attached));
316            }
317        }
318        let opened = self
319            .stores()
320            .prints
321            .open_print(Some(provider_print.id), provider_print.file_name.clone())
322            .await?;
323        Ok(Resolution::Opened(opened))
324    }
325
326    /// Fetch and store the image an alert names, recording either failure.
327    async fn write_image(
328        &self,
329        print: &PrintRecord,
330        event: &EventRecord,
331        image_url: Option<String>,
332    ) -> Option<ImageRef> {
333        let source_url = image_url?;
334        let fetched = match self.vision().fetch_image(source_url.clone()).await {
335            Ok(fetched) => fetched,
336            Err(error) => {
337                self.record_port_failure(
338                    print.id,
339                    event.id,
340                    PortFailureSite::ImageWrite,
341                    error.to_string(),
342                )
343                .await;
344                return None;
345            }
346        };
347        match self
348            .stores()
349            .images
350            .put_image(
351                print.id,
352                event.id,
353                Some(source_url),
354                fetched.content_type,
355                fetched.bytes,
356            )
357            .await
358        {
359            Ok(record) => Some(ImageRef {
360                id: record.id,
361                sha256: record.sha256,
362            }),
363            Err(error) => {
364                self.record_port_failure(
365                    print.id,
366                    event.id,
367                    PortFailureSite::ImageWrite,
368                    error.to_string(),
369                )
370                .await;
371                None
372            }
373        }
374    }
375
376    /// Collect the context, run one turn on it, and persist what it answered.
377    ///
378    /// `earlier` is what arrived for the print before `arrival` while an
379    /// earlier turn was running and that turn never took, oldest first.
380    ///
381    /// Answers the terminal state the printer reported, when it reported one,
382    /// and runs nothing for a print that ended — at a read that found its job
383    /// over — before this turn came to hold it.
384    async fn supervise(
385        &self,
386        print: &PrintRecord,
387        arrival: &Arrival,
388        earlier: Vec<Arrival>,
389    ) -> Result<Supervised, CoreError> {
390        let event = &arrival.event;
391        let guard = self.turns().acquire(print.id).await;
392        let Some(held) = self.stores().prints.print(print.id).await? else {
393            return Ok(Supervised::Ended);
394        };
395        let ended = held.ended_at.is_some();
396        if ended && !concerns_its_end(event.kind()) {
397            return Ok(Supervised::Ended);
398        }
399        let context = self.gather_context(print, Some(event.id)).await?;
400        let printer_state = context
401            .printer
402            .as_ref()
403            .map(|snapshot| snapshot.connection.clone());
404        let terminal = printer_state
405            .clone()
406            .filter(|state| TERMINAL_STATES.contains(state));
407        let image_path = match &event.image {
408            Some(reference) => self.image_path(reference).await,
409            None => None,
410        };
411        let situation = TurnSituation {
412            printer_state,
413            detector_warned: arrival.detection.map(|detection| detection.warning),
414            detector_paused_the_print: arrival
415                .detection
416                .map(|detection| detection.paused_the_print),
417            arrived_while_busy: earlier.into_iter().map(|left| left.event).collect(),
418            noticed: noticed_of(event),
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        // A print already over has nothing a terminal state could close: its
473        // turn on its end ran, and what was handed to it meanwhile is next.
474        Ok(match terminal {
475            Some(state) if !ended => Supervised::Terminal(state),
476            _ => Supervised::Ran,
477        })
478    }
479
480    /// Gather the current context of one print, including while its
481    /// supervision turn is running.
482    ///
483    /// # Errors
484    ///
485    /// Returns [`CoreError::NoSuchPrint`] when nothing is held under that
486    /// identifier, and the store's own error when the context could not be
487    /// read.
488    pub async fn context(&self, print_id: PrintId) -> Result<PrintContext, CoreError> {
489        let print = self
490            .stores()
491            .prints
492            .print(print_id)
493            .await?
494            .ok_or(CoreError::NoSuchPrint { print_id })?;
495        self.gather_context(&print, None).await
496    }
497
498    /// Read one print's whole context, recording a printer read that fails.
499    ///
500    /// A read failure is recorded against the event being handled when there is
501    /// one; a context read that no event prompted has nowhere to record it and
502    /// carries the absence in the context itself, which is what an absent
503    /// `printer` or `job` means.
504    ///
505    /// The job read settles the open prints exactly as the listing's does
506    /// ([`crate::listing`]) before the rest of the context is read: a job found
507    /// over closes the print, a later job of its file closes it as replaced,
508    /// and a job found to be its own is recorded on it — so the context
509    /// answered is the print as it now stands. Within a turn the turn holds the
510    /// print, and that turn closes it.
511    async fn gather_context(
512        &self,
513        print: &PrintRecord,
514        event_id: Option<printobserver_types::EventId>,
515    ) -> Result<PrintContext, CoreError> {
516        let printer = match self.read_snapshot().await {
517            Ok(snapshot) => Some(snapshot),
518            Err(error) => {
519                self.record_read_failure(
520                    print.id,
521                    event_id,
522                    PortFailureSite::PrinterSnapshot,
523                    error.to_string(),
524                )
525                .await;
526                None
527            }
528        };
529        // The job is read and settled under one hold on resolution, as the
530        // listing's is. A start holds it from the read that chooses its print
531        // until the printer has been asked to start, so a job read before that
532        // hold and settled after it would be the idle machine the start has
533        // since moved, and would close the print the start had just opened.
534        let resolving = self.resolving().await;
535        let job = match self.read_job().await {
536            Ok(job) => Some(job),
537            Err(error) => {
538                self.record_read_failure(
539                    print.id,
540                    event_id,
541                    PortFailureSite::PrinterJob,
542                    error.to_string(),
543                )
544                .await;
545                None
546            }
547        };
548        let print = match &job {
549            Some(job) if print.ended_at.is_none() => self.settle_for_context(print, job).await?,
550            _ => print.clone(),
551        };
552        drop(resolving);
553        let print = &print;
554        let manifest = self.stores().prints.manifest(print.id).await?;
555        let bounds = self.bounds_for(Some(print), print.id).await?;
556        let interventions = self.stores().actions.active_interventions(print.id).await?;
557        let recent_events = self.recent_events_of(print).await?;
558        let latest_image = recent_events.iter().find_map(|record| record.image.clone());
559        Ok(PrintContext {
560            print: print.clone(),
561            printer,
562            job,
563            manifest,
564            bounds: bounds.effective,
565            interventions,
566            recent_events,
567            latest_image,
568            detector: self.detector_health(),
569        })
570    }
571
572    /// One print's most recent events, newest first: its own, and what the
573    /// printer watch recorded of the machine since it opened, which is the
574    /// printer's and carries no print.
575    async fn recent_events_of(&self, print: &PrintRecord) -> Result<Vec<EventRecord>, CoreError> {
576        let limit = self.config().recent_events;
577        let mut events = self
578            .stores()
579            .events
580            .history(HistoryQuery {
581                print_id: print.id,
582                kinds: Vec::new(),
583                since: None,
584                until: None,
585                limit: Some(limit),
586            })
587            .await?;
588        let kinds = crate::watch::PRINTER_WATCH_KINDS
589            .iter()
590            .filter_map(|kind| printobserver_types::EventKind::new(*kind).ok())
591            .collect();
592        let watched = self
593            .stores()
594            .timeline
595            .timeline(crate::store::TimelineQuery {
596                kinds,
597                since: Some(print.opened_at),
598                until: None,
599                spool_id: None,
600                before: None,
601                limit: Some(limit),
602            })
603            .await?;
604        events.extend(watched.into_iter().filter(|event| event.print_id.is_none()));
605        events.sort_by_key(|event| core::cmp::Reverse((event.received_at, event.id)));
606        events.truncate(usize::try_from(limit).unwrap_or(usize::MAX));
607        Ok(events)
608    }
609
610    /// Where one image's bytes are, when the store still has them.
611    pub(crate) async fn image_path(&self, image: &ImageRef) -> Option<std::path::PathBuf> {
612        match self.stores().images.image(image.id).await {
613            Ok(ImageLookup::Found { path, .. }) => Some(path),
614            _ => None,
615        }
616    }
617
618    /// Settle the open prints against the job a context read found, and
619    /// answer the print the context is about as that left it.
620    ///
621    /// The caller holds resolution from before it read that job.
622    async fn settle_for_context(
623        &self,
624        print: &PrintRecord,
625        job: &JobSnapshot,
626    ) -> Result<PrintRecord, CoreError> {
627        let observed = ObservedJob {
628            job: job.clone(),
629            observed_at: self.clock().now(),
630        };
631        let settled = self.settle_open_prints(&observed).await?;
632        match settled.running {
633            Some(running) if running.id == print.id => Ok(running),
634            _ if settled.closed.contains(&print.id) => Ok(self
635                .stores()
636                .prints
637                .print(print.id)
638                .await?
639                .unwrap_or_else(|| print.clone())),
640            _ => Ok(print.clone()),
641        }
642    }
643
644    /// End the print, expire what it had running, and close its session.
645    ///
646    /// The interventions are expired **before** the print is ended, because a
647    /// restoration is an action against the print and a print that has already
648    /// ended is one no action may be taken against.
649    ///
650    /// The caller holds the print's turn, so no turn is acting on it while it
651    /// closes. Answers whether this closed it: a print already ended — by
652    /// another read, or by the turn that held it — is left as it ended.
653    ///
654    /// The print's filament is settled after its interventions are expired
655    /// and before it is ended ([`crate::accounting`]): a crash between the two
656    /// leaves a settled, open print, which the next close-out only ends.
657    /// `closing_job` is the job read that found the print over, when there
658    /// was one; without it the settlement reads the job itself.
659    pub(crate) async fn close_out_print(
660        &self,
661        print_id: PrintId,
662        state: &PrinterState,
663        reason: &str,
664        closing_job: Option<&JobSnapshot>,
665    ) -> Result<bool, CoreError> {
666        let print = match self.stores().prints.print(print_id).await? {
667            Some(print) if print.ended_at.is_none() => print,
668            _ => return Ok(false),
669        };
670        self.forget_detector_pause(print_id);
671        self.expire_all_active(print_id).await?;
672        self.settle_filament(&print, state, reason, closing_job)
673            .await?;
674        self.stores()
675            .prints
676            .end_print(
677                print_id,
678                state.clone(),
679                self.clock().now(),
680                reason.to_owned(),
681            )
682            .await?;
683        self.close_session_of(print_id, reason).await?;
684        self.follow_up_end(print_id).await;
685        Ok(true)
686    }
687
688    /// Append one event this system raised itself.
689    pub(crate) async fn append_system_event(
690        &self,
691        print_id: PrintId,
692        body: EventBody,
693    ) -> Result<EventRecord, CoreError> {
694        self.append_system_event_to(Some(print_id), body).await
695    }
696
697    /// Append one event the supervisor itself raised, to a print's history or
698    /// to the printer's when it names none.
699    pub(crate) async fn append_system_event_to(
700        &self,
701        print_id: Option<PrintId>,
702        body: EventBody,
703    ) -> Result<EventRecord, CoreError> {
704        Ok(self
705            .stores()
706            .events
707            .append_event(EventDraft {
708                print_id,
709                source: system_source(),
710                received_at: self.clock().now(),
711                body,
712                raw: None,
713            })
714            .await?)
715    }
716
717    /// Record a printer read that failed, when an event prompted the read.
718    async fn record_read_failure(
719        &self,
720        print_id: PrintId,
721        event_id: Option<printobserver_types::EventId>,
722        site: PortFailureSite,
723        detail: String,
724    ) {
725        if let Some(event_id) = event_id {
726            self.record_port_failure(print_id, event_id, site, detail)
727                .await;
728        }
729    }
730
731    /// Record that a port failed while one event was being handled.
732    ///
733    /// The event is already in the history by the time any of these sites is
734    /// reached, which is what gives the failure somewhere to be recorded.
735    /// Nothing is answered to the caller: the loop survives this and goes on.
736    pub(crate) async fn record_port_failure(
737        &self,
738        print_id: PrintId,
739        event_id: printobserver_types::EventId,
740        site: PortFailureSite,
741        detail: String,
742    ) {
743        self.record_port_failure_to(Some(print_id), event_id, site, detail)
744            .await;
745    }
746
747    /// Record that a port failed while one event was being handled, in the
748    /// history that event is in: a print's, or the printer's when it names
749    /// none.
750    pub(crate) async fn record_port_failure_to(
751        &self,
752        print_id: Option<PrintId>,
753        event_id: printobserver_types::EventId,
754        site: PortFailureSite,
755        detail: String,
756    ) {
757        // A record that will not render is dropped exactly as one the store
758        // refuses is: the failure it was about has already been answered, and
759        // the loop survives not having written it down.
760        let Ok(body) = EventBody::of(&PortFailurePayload {
761            event_id,
762            site,
763            detail,
764        }) else {
765            return;
766        };
767        let _ = self.append_system_event_to(print_id, body).await;
768    }
769}