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::{AgentContext, PrintContext, Since, newer_than};
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    /// What a supervision turn reads of one print's context, carrying only the
506    /// events newer than `since` when it names one.
507    ///
508    /// Every event newer than the one named is carried, however many the
509    /// recent window would hold: the window is widened to the history's
510    /// largest page when the event is older than it.
511    ///
512    /// # Errors
513    ///
514    /// Answers [`CoreError::NoSuchPrint`] and the store's own error as
515    /// [`Self::context`] does, and [`StoreError::NotFound`] when `since` names
516    /// none of the print's latest [`MAX_HISTORY_LIMIT`] events.
517    ///
518    /// [`StoreError::NotFound`]: crate::store::StoreError::NotFound
519    /// [`MAX_HISTORY_LIMIT`]: crate::store::MAX_HISTORY_LIMIT
520    pub async fn agent_context(
521        &self,
522        print_id: PrintId,
523        since: Option<printobserver_types::EventId>,
524    ) -> Result<AgentContext, CoreError> {
525        let context = self.context(print_id).await?;
526        let Some(event) = since else {
527            return Ok(context.for_agent(None));
528        };
529        let wider;
530        let newer = if let Some(newer) = newer_than(&context.recent_events, event) {
531            newer
532        } else {
533            wider = self
534                .recent_events_of(&context.print, crate::store::MAX_HISTORY_LIMIT)
535                .await?;
536            newer_than(&wider, event).ok_or_else(|| {
537                CoreError::Store(crate::store::StoreError::NotFound {
538                    what: format!(
539                        "event {event} among print {print_id}'s latest {} events",
540                        crate::store::MAX_HISTORY_LIMIT
541                    ),
542                })
543            })?
544        };
545        let agent = context.for_agent(Some(Since { event, newer }));
546        Ok(agent)
547    }
548
549    /// Read one print's whole context, recording a printer read that fails.
550    ///
551    /// A read failure is recorded against the event being handled when there is
552    /// one; a context read that no event prompted has nowhere to record it and
553    /// carries the absence in the context itself, which is what an absent
554    /// `printer` or `job` means.
555    ///
556    /// The job read settles the open prints exactly as the listing's does
557    /// ([`crate::listing`]) before the rest of the context is read: a job found
558    /// over closes the print, a later job of its file closes it as replaced,
559    /// and a job found to be its own is recorded on it — so the context
560    /// answered is the print as it now stands. Within a turn the turn holds the
561    /// print, and that turn closes it.
562    async fn gather_context(
563        &self,
564        print: &PrintRecord,
565        event_id: Option<printobserver_types::EventId>,
566    ) -> Result<PrintContext, CoreError> {
567        let printer = match self.read_snapshot().await {
568            Ok(snapshot) => Some(snapshot),
569            Err(error) => {
570                self.record_read_failure(
571                    print.id,
572                    event_id,
573                    PortFailureSite::PrinterSnapshot,
574                    error.to_string(),
575                )
576                .await;
577                None
578            }
579        };
580        // The job is read and settled under one hold on resolution, as the
581        // listing's is. A start holds it from the read that chooses its print
582        // until the printer has been asked to start, so a job read before that
583        // hold and settled after it would be the idle machine the start has
584        // since moved, and would close the print the start had just opened.
585        let resolving = self.resolving().await;
586        let job = match self.read_job().await {
587            Ok(job) => Some(job),
588            Err(error) => {
589                self.record_read_failure(
590                    print.id,
591                    event_id,
592                    PortFailureSite::PrinterJob,
593                    error.to_string(),
594                )
595                .await;
596                None
597            }
598        };
599        let print = match &job {
600            Some(job) if print.ended_at.is_none() => self.settle_for_context(print, job).await?,
601            _ => print.clone(),
602        };
603        drop(resolving);
604        let print = &print;
605        let manifest = self.stores().prints.manifest(print.id).await?;
606        let bounds = self.bounds_for(Some(print), print.id).await?;
607        let interventions = self.stores().actions.active_interventions(print.id).await?;
608        let recent_events = self
609            .recent_events_of(print, self.config().recent_events)
610            .await?;
611        let latest_image = recent_events.iter().find_map(|record| record.image.clone());
612        let slicer = self
613            .slicer_plan(print, job.as_ref(), &interventions)
614            .await?;
615        Ok(PrintContext {
616            print: print.clone(),
617            printer,
618            job,
619            manifest,
620            bounds: bounds.effective,
621            interventions,
622            recent_events,
623            latest_image,
624            detector: self.detector_health(),
625            slicer,
626        })
627    }
628
629    /// One print's most recent events, newest first: its own, and what the
630    /// printer watch recorded of the machine since it opened, which is the
631    /// printer's and carries no print.
632    async fn recent_events_of(
633        &self,
634        print: &PrintRecord,
635        limit: u32,
636    ) -> Result<Vec<EventRecord>, CoreError> {
637        let mut events = self
638            .stores()
639            .events
640            .history(HistoryQuery {
641                print_id: print.id,
642                kinds: Vec::new(),
643                since: None,
644                until: None,
645                limit: Some(limit),
646            })
647            .await?;
648        let kinds = crate::watch::PRINTER_WATCH_KINDS
649            .iter()
650            .filter_map(|kind| printobserver_types::EventKind::new(*kind).ok())
651            .collect();
652        let watched = self
653            .stores()
654            .timeline
655            .timeline(crate::store::TimelineQuery {
656                kinds,
657                since: Some(print.opened_at),
658                until: None,
659                spool_id: None,
660                before: None,
661                limit: Some(limit),
662            })
663            .await?;
664        events.extend(watched.into_iter().filter(|event| event.print_id.is_none()));
665        events.sort_by_key(|event| core::cmp::Reverse((event.received_at, event.id)));
666        events.truncate(usize::try_from(limit).unwrap_or(usize::MAX));
667        Ok(events)
668    }
669
670    /// Where one image's bytes are, when the store still has them.
671    pub(crate) async fn image_path(&self, image: &ImageRef) -> Option<std::path::PathBuf> {
672        match self.stores().images.image(image.id).await {
673            Ok(ImageLookup::Found { path, .. }) => Some(path),
674            _ => None,
675        }
676    }
677
678    /// Settle the open prints against the job a context read found, and
679    /// answer the print the context is about as that left it.
680    ///
681    /// The caller holds resolution from before it read that job.
682    async fn settle_for_context(
683        &self,
684        print: &PrintRecord,
685        job: &JobSnapshot,
686    ) -> Result<PrintRecord, CoreError> {
687        let observed = ObservedJob {
688            job: job.clone(),
689            observed_at: self.clock().now(),
690        };
691        let settled = self.settle_open_prints(&observed).await?;
692        match settled.running {
693            Some(running) if running.id == print.id => Ok(running),
694            _ if settled.closed.contains(&print.id) => Ok(self
695                .stores()
696                .prints
697                .print(print.id)
698                .await?
699                .unwrap_or_else(|| print.clone())),
700            _ => Ok(print.clone()),
701        }
702    }
703
704    /// End the print, expire what it had running, and close its session.
705    ///
706    /// The interventions are expired **before** the print is ended, because a
707    /// restoration is an action against the print and a print that has already
708    /// ended is one no action may be taken against.
709    ///
710    /// The caller holds the print's turn, so no turn is acting on it while it
711    /// closes. Answers whether this closed it: a print already ended — by
712    /// another read, or by the turn that held it — is left as it ended.
713    ///
714    /// The print's filament is settled after its interventions are expired
715    /// and before it is ended ([`crate::accounting`]): a crash between the two
716    /// leaves a settled, open print, which the next close-out only ends.
717    /// `closing_job` is the job read that found the print over, when there
718    /// was one; without it the settlement reads the job itself.
719    pub(crate) async fn close_out_print(
720        &self,
721        print_id: PrintId,
722        state: &PrinterState,
723        reason: &str,
724        closing_job: Option<&JobSnapshot>,
725    ) -> Result<bool, CoreError> {
726        let print = match self.stores().prints.print(print_id).await? {
727            Some(print) if print.ended_at.is_none() => print,
728            _ => return Ok(false),
729        };
730        self.forget_detector_pause(print_id);
731        self.expire_all_active(print_id).await?;
732        self.settle_filament(&print, state, reason, closing_job)
733            .await?;
734        self.stores()
735            .prints
736            .end_print(
737                print_id,
738                state.clone(),
739                self.clock().now(),
740                reason.to_owned(),
741            )
742            .await?;
743        self.close_session_of(print_id, reason).await?;
744        self.follow_up_end(print_id).await;
745        Ok(true)
746    }
747
748    /// Append one event this system raised itself.
749    pub(crate) async fn append_system_event(
750        &self,
751        print_id: PrintId,
752        body: EventBody,
753    ) -> Result<EventRecord, CoreError> {
754        self.append_system_event_to(Some(print_id), body).await
755    }
756
757    /// Append one event the supervisor itself raised, to a print's history or
758    /// to the printer's when it names none.
759    pub(crate) async fn append_system_event_to(
760        &self,
761        print_id: Option<PrintId>,
762        body: EventBody,
763    ) -> Result<EventRecord, CoreError> {
764        Ok(self
765            .stores()
766            .events
767            .append_event(EventDraft {
768                print_id,
769                source: system_source(),
770                received_at: self.clock().now(),
771                body,
772                raw: None,
773            })
774            .await?)
775    }
776
777    /// Record a printer read that failed, when an event prompted the read.
778    async fn record_read_failure(
779        &self,
780        print_id: PrintId,
781        event_id: Option<printobserver_types::EventId>,
782        site: PortFailureSite,
783        detail: String,
784    ) {
785        if let Some(event_id) = event_id {
786            self.record_port_failure(print_id, event_id, site, detail)
787                .await;
788        }
789    }
790
791    /// Record that a port failed while one event was being handled.
792    ///
793    /// The event is already in the history by the time any of these sites is
794    /// reached, which is what gives the failure somewhere to be recorded.
795    /// Nothing is answered to the caller: the loop survives this and goes on.
796    pub(crate) async fn record_port_failure(
797        &self,
798        print_id: PrintId,
799        event_id: printobserver_types::EventId,
800        site: PortFailureSite,
801        detail: String,
802    ) {
803        self.record_port_failure_to(Some(print_id), event_id, site, detail)
804            .await;
805    }
806
807    /// Record that a port failed while one event was being handled, in the
808    /// history that event is in: a print's, or the printer's when it names
809    /// none.
810    pub(crate) async fn record_port_failure_to(
811        &self,
812        print_id: Option<PrintId>,
813        event_id: printobserver_types::EventId,
814        site: PortFailureSite,
815        detail: String,
816    ) {
817        // A record that will not render is dropped exactly as one the store
818        // refuses is: the failure it was about has already been answered, and
819        // the loop survives not having written it down.
820        let Ok(body) = EventBody::of(&PortFailurePayload {
821            event_id,
822            site,
823            detail,
824        }) else {
825            return;
826        };
827        let _ = self.append_system_event_to(print_id, body).await;
828    }
829}