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//! # Everything a check decides from is in its prompt
26//!
27//! A turn is handed its print's facts — the context read as it begins, its
28//! events cut to those since the agent last answered
29//! ([`crate::context::turn_facts`]) — and the check's image of the
30//! event's frame ([`crate::check_image`]), so a quiet check needs no command to
31//! decide. Its answer's disposition is its acknowledgement: a turn that
32//! acknowledged nothing by command has its event acknowledged from its answer,
33//! as the agent in that turn's session, with the answer's `why` as the reason.
34//!
35//! # One agent per print
36//!
37//! [`Supervisor::receive_event`] writes an event down and claims its print's
38//! turn, or — when a turn is already running for that print — hands the event
39//! to that turn through the print's inbox ([`crate::inbox`]), where its next
40//! look takes it. [`Supervisor::run_supervision`] runs a claimed turn and then
41//! one more, in the same session, for whatever arrived during it that it never
42//! took. A print that has ended starts no turn at all, and its inbox is
43//! released with whatever was still waiting in it.
44
45use crate::records::{AcknowledgementDisposition, Actor, PrintAction, PrintRecord};
46use crate::store::{EventDraft, HistoryQuery, ImageLookup};
47use printobserver_printer_api::{JobSnapshot, PrinterState};
48use printobserver_supervisor_api::{AgentAssessment, Disposition, SessionPhase};
49use printobserver_supervisor_api::{SupervisionSessionOpenedPayload, TurnRequest, TurnSituation};
50use printobserver_types::EventId;
51use printobserver_types::{EventBody, EventRecord, ImageRef, PrintId, Timestamp};
52use printobserver_vision_api::NormalizedAlert;
53
54use crate::check_image::{ImageUse, captured_at_of};
55use crate::context::{AgentContext, PrintContext, Since, newer_than};
56use crate::error::CoreError;
57use crate::inbox::Arrival;
58use crate::kinds::{
59    AgentAssessmentPayload, AgentStopUnactedPayload, PortFailurePayload, PortFailureSite,
60    system_source,
61};
62use crate::listing::{self, ObservedJob, reached_reason};
63use crate::supervisor::Supervisor;
64use crate::watch::{concerns_its_end, noticed_of};
65
66/// One event written down, and the turn it claimed, when it claimed one.
67#[derive(Debug, Clone, PartialEq)]
68pub struct Received {
69    /// The event, as the store holds it.
70    pub event: EventRecord,
71    /// The turn it claimed: absent when it belongs to no print, to a print that
72    /// has ended, or was handed to the turn already running for its print.
73    pub turn: Option<PendingTurn>,
74}
75
76/// What became of one turn.
77enum Supervised {
78    /// It ran, and the printer was not in a terminal state.
79    Ran,
80    /// It ran, and the printer reported this terminal state.
81    Terminal(PrinterState),
82    /// The print had ended by the time the turn held it, so nothing ran.
83    Ended,
84}
85
86/// A turn one event claimed, to be run by [`Supervisor::run_supervision`].
87#[derive(Debug, Clone, PartialEq)]
88pub struct PendingTurn {
89    /// The print the turn is about.
90    print: PrintRecord,
91    /// The event that claimed it.
92    arrival: Arrival,
93    /// What was handed to the print before that event and never taken,
94    /// oldest first.
95    earlier: Vec<Arrival>,
96}
97
98impl PendingTurn {
99    /// The turn one arrival claimed, after what was handed over before it.
100    pub(crate) const fn new(print: PrintRecord, arrival: Arrival, earlier: Vec<Arrival>) -> Self {
101        Self {
102            print,
103            arrival,
104            earlier,
105        }
106    }
107}
108
109/// The print an alert belongs to, and whether resolving it opened one.
110enum Resolution {
111    /// The alert is about no print.
112    NoPrint,
113    /// A print this system already held.
114    Existing(PrintRecord),
115    /// A print opened for it now, which is owed its `print_started`.
116    Opened(PrintRecord),
117}
118
119impl Resolution {
120    /// The print, however it was found.
121    const fn print(&self) -> Option<&PrintRecord> {
122        match self {
123            Self::NoPrint => None,
124            Self::Existing(print) | Self::Opened(print) => Some(print),
125        }
126    }
127}
128
129/// The states a print does not carry on from.
130///
131/// Read off the printer's own reported state rather than inferred from a
132/// notification's wording: the machine is the authority on whether it is still
133/// printing.
134pub const TERMINAL_STATES: [PrinterState; 3] = [
135    PrinterState::Operational,
136    PrinterState::Error,
137    PrinterState::Offline,
138];
139
140impl Supervisor {
141    /// Handle one normalized event, from the store's own append to the turn.
142    ///
143    /// # Errors
144    ///
145    /// Returns the store's own error when the **initial event append** fails,
146    /// which is the one failure this loop cannot record anywhere; no other port
147    /// is called for that event, and a later event whose append succeeds is
148    /// handled to completion. Every other port failure this loop reaches is
149    /// recorded against the event rather than answered here — except the
150    /// writes that come after the event is already in the history and are
151    /// owed the spool ledger: a new print's `print_started`, and what a
152    /// filament-change signal the alert relays charges and marks. Those are
153    /// answered as the store's own error, the alert itself already written.
154    pub async fn handle_event(&self, alert: NormalizedAlert) -> Result<EventRecord, CoreError> {
155        let received = self.receive_event(alert).await?;
156        if let Some(turn) = received.turn {
157            self.run_supervision(turn).await?;
158        }
159        Ok(received.event)
160    }
161
162    /// Write one normalized event down, and say whether it needs a turn of
163    /// its own.
164    ///
165    /// The first half of [`Supervisor::handle_event`], for a caller that runs
166    /// the turn somewhere else so that the next event can be written down
167    /// while this one's turn is still running. An event for a print whose turn
168    /// is already running is handed to that turn and answers no turn of its
169    /// own: one agent per print, and what arrives reaches the agent already
170    /// watching it.
171    ///
172    /// # Errors
173    ///
174    /// Exactly as [`Supervisor::handle_event`]'s.
175    pub async fn receive_event(&self, alert: NormalizedAlert) -> Result<Received, CoreError> {
176        let resolution = self.resolve_print(&alert).await?;
177        let draft = EventDraft {
178            print_id: resolution.print().map(|record| record.id),
179            source: alert.source.clone(),
180            received_at: alert.received_at,
181            body: alert.body.clone(),
182            raw: Some(alert.raw.clone()),
183        };
184        let event = self
185            .stores()
186            .events
187            .append_event(draft)
188            .await
189            .map_err(CoreError::Store)?;
190        let print = match resolution {
191            Resolution::NoPrint => return Ok(Received { event, turn: None }),
192            Resolution::Existing(print) => print,
193            // llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
194            Resolution::Opened(print) => {
195                self.record_print_started(print.id, print.file_name.clone(), None, None)
196                    .await?;
197                print
198            }
199        };
200        if alert.detection.is_some() {
201            // The detector flagged this print, which its status says from now on.
202            self.note_flagged(print.id);
203        }
204        let (image, frame_captured_at) = self
205            .write_image(&print, &event, alert.image_url.clone())
206            .await
207            .map_or((None, None), |(image, at)| (Some(image), Some(at)));
208        if print.ended_at.is_some() {
209            return Ok(Received { event, turn: None });
210        }
211        if let Some(signal) = alert.signal {
212            self.handle_signal(&print, signal, alert.kind()).await?;
213        }
214        let mut carried = event.clone();
215        carried.image = image.or(carried.image);
216        if let Some(detection) = alert.detection
217            && detection.paused_the_print
218        {
219            self.note_detector_pause(print.id, event.id, detection);
220        }
221        let arrival = Arrival {
222            event: carried,
223            detection: alert.detection,
224            frame_captured_at,
225        };
226        let turn = self
227            .inboxes()
228            .claim_or_hand_over(print.id, arrival.clone())
229            .then(|| PendingTurn::new(print, arrival, Vec::new()));
230        Ok(Received { event, turn })
231    }
232
233    /// Run the turn one received event claimed, and one more for whatever
234    /// arrived during it that it never took, until nothing is left.
235    ///
236    /// The detector's pause the agent adjusted the print under is resumed as
237    /// each turn ends, when its grace has not already resumed it.
238    ///
239    /// # Errors
240    ///
241    /// Returns the store's own error when a turn's outcome could not be
242    /// recorded; a turn that fails is recorded rather than answered.
243    pub async fn run_supervision(&self, turn: PendingTurn) -> Result<(), CoreError> {
244        let PendingTurn {
245            print,
246            arrival,
247            earlier,
248        } = turn;
249        let mut next = Some((arrival, earlier));
250        while let Some((arrival, earlier)) = next {
251            let supervised = self.supervise(&print, &arrival, earlier).await;
252            if !matches!(supervised, Ok(Supervised::Ended)) {
253                self.resume_adjusted_detector_pause(print.id).await;
254            }
255            match supervised {
256                Ok(Supervised::Ran) => {}
257                Ok(Supervised::Ended) => {
258                    self.inboxes().release(print.id);
259                    self.forget_detector_pause(print.id);
260                    return Ok(());
261                }
262                Ok(Supervised::Terminal(state)) => {
263                    self.inboxes().release(print.id);
264                    let _turn = self.turns().acquire(print.id).await;
265                    return self
266                        .close_out_print(print.id, &state, &reached_reason(&state), None)
267                        .await
268                        .map(drop);
269                }
270                Err(error) => {
271                    self.inboxes().release(print.id);
272                    return Err(error);
273                }
274            }
275            next = self
276                .inboxes()
277                .next_or_release(print.id)
278                .and_then(|mut left| left.pop().map(|latest| (latest, left)));
279        }
280        Ok(())
281    }
282
283    /// The print an alert belongs to, opened if this system has not seen it.
284    ///
285    /// Correlated on the provider's own identifier the alert carries beside its
286    /// body, and never on the body by kind: which provider raised the alert is
287    /// the adapter's business, and this loop reads nothing an adapter declares.
288    ///
289    /// In order: the print already carrying that identifier; otherwise the most
290    /// recently opened print with no end recorded, no provider identifier, the
291    /// alert's own file name and a job the alert's start may be
292    /// ([`listing::may_have_started_it`]), which is a job somebody found before
293    /// the provider reported on it and which takes the identifier here;
294    /// otherwise a print opened for it. The file name is the one key the two
295    /// sides share — the provider names the job by the file the printer
296    /// reported, and the printer names it by that same file — and the start is
297    /// what tells that job from a later one of the same file.
298    ///
299    /// Nothing here reads the printer: an alert is written down before anything
300    /// is asked of a port, and a print a later job replaced is closed by the
301    /// next read that finds that job, not by an alert about it.
302    ///
303    /// Answers whether this opened it, so that the print's `print_started` is
304    /// written once the alert itself has been.
305    async fn resolve_print(&self, alert: &NormalizedAlert) -> Result<Resolution, CoreError> {
306        let Some(provider_print) = &alert.print else {
307            return Ok(Resolution::NoPrint);
308        };
309        let _resolving = self.resolving().await;
310        if let Some(found) = self
311            .stores()
312            .prints
313            .print_by_provider_id(provider_print.id)
314            .await?
315        {
316            return Ok(Resolution::Existing(found));
317        }
318        if let Some(file_name) = &provider_print.file_name {
319            let unattached = self
320                .stores()
321                .prints
322                .open_prints()
323                .await?
324                .into_iter()
325                .find(|open| {
326                    open.provider_print_id.is_none()
327                        && open.file_name.as_ref() == Some(file_name)
328                        && listing::may_have_started_it(open, provider_print.started_at)
329                });
330            if let Some(found) = unattached {
331                let attached = self
332                    .stores()
333                    .prints
334                    .attach_obico_print(found.id, provider_print.id)
335                    .await?;
336                return Ok(Resolution::Existing(attached));
337            }
338        }
339        let opened = self
340            .stores()
341            .prints
342            .open_print(Some(provider_print.id), provider_print.file_name.clone())
343            .await?;
344        Ok(Resolution::Opened(opened))
345    }
346
347    /// Fetch and store the image an alert names, recording either failure.
348    async fn write_image(
349        &self,
350        print: &PrintRecord,
351        event: &EventRecord,
352        image_url: Option<String>,
353    ) -> Option<(ImageRef, Timestamp)> {
354        let source_url = image_url?;
355        let fetched = match self.vision().fetch_image(source_url.clone()).await {
356            Ok(fetched) => fetched,
357            Err(error) => {
358                self.record_port_failure(
359                    print.id,
360                    event.id,
361                    PortFailureSite::ImageWrite,
362                    error.to_string(),
363                )
364                .await;
365                return None;
366            }
367        };
368        let captured_at = fetched.captured_at.unwrap_or_else(|| self.clock().now());
369        match self
370            .stores()
371            .images
372            .put_image(
373                print.id,
374                event.id,
375                Some(source_url),
376                fetched.content_type,
377                fetched.bytes,
378            )
379            .await
380        {
381            Ok(record) => Some((
382                ImageRef {
383                    id: record.id,
384                    sha256: record.sha256,
385                },
386                captured_at,
387            )),
388            Err(error) => {
389                self.record_port_failure(
390                    print.id,
391                    event.id,
392                    PortFailureSite::ImageWrite,
393                    error.to_string(),
394                )
395                .await;
396                None
397            }
398        }
399    }
400
401    /// Collect the context, run one turn on it, and persist what it answered.
402    ///
403    /// `earlier` is what arrived for the print before `arrival` while an
404    /// earlier turn was running and that turn never took, oldest first.
405    ///
406    /// Answers the terminal state the printer reported, when it reported one,
407    /// and runs nothing for a print that ended — at a read that found its job
408    /// over — before this turn came to hold it.
409    async fn supervise(
410        &self,
411        print: &PrintRecord,
412        arrival: &Arrival,
413        earlier: Vec<Arrival>,
414    ) -> Result<Supervised, CoreError> {
415        let event = &arrival.event;
416        let guard = self.turns().acquire(print.id).await;
417        let Some(held) = self.stores().prints.print(print.id).await? else {
418            return Ok(Supervised::Ended);
419        };
420        let ended = held.ended_at.is_some();
421        if ended && !concerns_its_end(event.kind()) {
422            return Ok(Supervised::Ended);
423        }
424        let context = self.gather_context(print, Some(event.id)).await?;
425        let printer_state = context
426            .printer
427            .as_ref()
428            .map(|snapshot| snapshot.connection.clone());
429        let terminal = printer_state
430            .clone()
431            .filter(|state| TERMINAL_STATES.contains(state));
432        let (image_path, image) = self
433            .check_image_for(print, arrival, context.job.as_ref())
434            .await;
435        let facts = crate::context::turn_facts(&context.for_agent(None));
436        let situation = TurnSituation {
437            printer_state,
438            detector_warned: arrival.detection.map(|detection| detection.warning),
439            detector_paused_the_print: arrival
440                .detection
441                .map(|detection| detection.paused_the_print),
442            arrived_while_busy: earlier.into_iter().map(|left| left.event).collect(),
443            noticed: noticed_of(event),
444            frame_captured_at: arrival.frame_captured_at,
445            image,
446        };
447        // The turn's credentials are bound to it from here, and revoked the
448        // moment it returns — whatever it returned — and when this future is
449        // abandoned, because dropping what was opened revokes too.
450        let opened = self.open_turn(print.id);
451        self.forget_acknowledged_by_turn(print.id);
452        let running = situation.printer_state == Some(PrinterState::Printing);
453        self.forget_stop_asked(print.id);
454        let access = std::sync::Arc::new(StopAware {
455            inner: opened.access(),
456            print_id: print.id,
457            stops: std::sync::Arc::clone(&self.stopped_by_turn),
458        });
459        let turn = self
460            .agent()
461            .run_turn(
462                TurnRequest {
463                    print_id: print.id,
464                    event: event.clone(),
465                    image_path,
466                    context_command: self.config().context_command_for(print.id),
467                    facts,
468                    situation,
469                },
470                access,
471            )
472            .await;
473        opened.revoke();
474        let acknowledged_by_command = self.forget_acknowledged_by_turn(print.id);
475        let asked_to_stop = self.forget_stop_asked(print.id);
476        drop(guard);
477        match turn {
478            Ok(outcome) => {
479                // An answer of `stop` on a print that was running, from a turn
480                // that asked for no pause or cancel, stopped nothing.
481                let stop_unacted = (running
482                    && !asked_to_stop
483                    && outcome.assessment.disposition == Disposition::Stop)
484                    .then(|| {
485                        (
486                            outcome.session.session_name.clone(),
487                            outcome.assessment.summary.clone(),
488                        )
489                    });
490                self.record_answered(print.id, event.id, outcome, acknowledged_by_command)
491                    .await?;
492                if let Some(said) = stop_unacted {
493                    self.record_unacted_stop(print.id, event.id, said).await?;
494                }
495            }
496            Err(error) => {
497                self.record_port_failure(
498                    print.id,
499                    event.id,
500                    PortFailureSite::SupervisionTurn,
501                    error.to_string(),
502                )
503                .await;
504            }
505        }
506        // A print already over has nothing a terminal state could close: its
507        // turn on its end ran, and what was handed to it meanwhile is next.
508        Ok(match terminal {
509            Some(state) if !ended => Supervised::Terminal(state),
510            _ => Supervised::Ran,
511        })
512    }
513
514    /// Write down what an answered turn said — the session it opened, its
515    /// assessment — and acknowledge its event from the answer when the turn
516    /// acknowledged nothing by command.
517    async fn record_answered(
518        &self,
519        print_id: PrintId,
520        event_id: EventId,
521        outcome: printobserver_supervisor_api::TurnOutcome,
522        acknowledged_by_command: bool,
523    ) -> Result<(), CoreError> {
524        if outcome.phase == SessionPhase::Created {
525            self.append_system_event(
526                print_id,
527                EventBody::of(&SupervisionSessionOpenedPayload {
528                    session_name: outcome.session.session_name.clone(),
529                    harness_identity: outcome.session.harness_identity.clone(),
530                })?,
531            )
532            .await?;
533        }
534        let session_name = outcome.session.session_name.clone();
535        self.stores().sessions.put_session(outcome.session).await?;
536        let assessment = outcome.assessment;
537        self.append_system_event(
538            print_id,
539            EventBody::of(&AgentAssessmentPayload {
540                session_name: session_name.clone(),
541                assessment: assessment.clone(),
542            })?,
543        )
544        .await?;
545        if !acknowledged_by_command
546            && let Err(error) = self
547                .acknowledge_from_answer(print_id, event_id, session_name, &assessment)
548                .await
549        {
550            // The turn answered; an acknowledgement that could not be
551            // made is recorded against its event and ends nothing. Only a
552            // store failing mid-turn reaches here, which the real store can
553            // be made to do only by breaking its database under a running
554            // server; the core journey
555            // `an_acknowledgement_the_answer_cannot_make_is_recorded_and_supervision_goes_on`
556            // proves it over a store that fails its history read instead.
557            self.record_port_failure(
558                print_id,
559                event_id,
560                PortFailureSite::SupervisionTurn,
561                format!("the answer's acknowledgement could not be made: {error}"),
562            )
563            .await;
564        }
565        Ok(())
566    }
567
568    /// Write down that the agent answered a running print should stop and
569    /// stopped nothing, when the print is still open: its history is where a
570    /// refused pause is, which is what the person reading it reads.
571    ///
572    /// # Errors
573    ///
574    /// Returns the store's own error when the print or its history could not
575    /// be read or written.
576    async fn record_unacted_stop(
577        &self,
578        print_id: PrintId,
579        event_id: EventId,
580        (session_name, summary): (String, String),
581    ) -> Result<(), CoreError> {
582        let open = self
583            .stores()
584            .prints
585            .print(print_id)
586            .await?
587            .is_some_and(|print| print.ended_at.is_none());
588        if !open {
589            return Ok(());
590        }
591        self.append_system_event(
592            print_id,
593            EventBody::of(&AgentStopUnactedPayload {
594                event_id,
595                session_name,
596                summary,
597            })?,
598        )
599        .await?;
600        Ok(())
601    }
602
603    /// The image a check of one arrival is shown and the line saying what it
604    /// is, made where the job stood in the print's own file: none when the
605    /// arrival carries no frame.
606    async fn check_image_for(
607        &self,
608        print: &PrintRecord,
609        arrival: &Arrival,
610        job: Option<&JobSnapshot>,
611    ) -> (Option<std::path::PathBuf>, Option<String>) {
612        let event = &arrival.event;
613        let Some(reference) = &event.image else {
614            return (None, None);
615        };
616        let plan = self.plan_position(print, job).await;
617        let captured_at = captured_at_of(event, arrival.frame_captured_at);
618        self.shown_image_of(
619            reference,
620            Some(print.id),
621            captured_at,
622            ImageUse::Check,
623            plan,
624        )
625        .await
626        .map_or((None, None), |shown| (Some(shown.path), shown.note))
627    }
628
629    /// Note that the running turn on one print asked to pause or cancel it,
630    /// whatever policy makes of the request: what an answer of `stop` is held
631    /// to.
632    pub(crate) fn note_stop_asked(&self, print_id: PrintId, action: &PrintAction) {
633        if action.actor().class() == crate::records::ActorClass::Agent
634            && matches!(
635                action,
636                PrintAction::Pause { .. } | PrintAction::Cancel { .. }
637            )
638        {
639            self.stopped_by_turn
640                .lock()
641                .unwrap_or_else(std::sync::PoisonError::into_inner)
642                .insert(print_id);
643        }
644    }
645
646    /// Forget whether a turn on one print asked to stop it, answering whether
647    /// one had.
648    fn forget_stop_asked(&self, print_id: PrintId) -> bool {
649        self.stopped_by_turn
650            .lock()
651            .unwrap_or_else(std::sync::PoisonError::into_inner)
652            .remove(&print_id)
653    }
654
655    /// Note that the running turn on one print acknowledged its event by
656    /// command.
657    pub(crate) fn note_acknowledged_by_turn(&self, print_id: PrintId) {
658        self.acknowledged_by_turn
659            .lock()
660            .unwrap_or_else(std::sync::PoisonError::into_inner)
661            .insert(print_id);
662    }
663
664    /// Forget whether a turn on one print acknowledged by command, answering
665    /// whether one had.
666    fn forget_acknowledged_by_turn(&self, print_id: PrintId) -> bool {
667        self.acknowledged_by_turn
668            .lock()
669            .unwrap_or_else(std::sync::PoisonError::into_inner)
670            .remove(&print_id)
671    }
672
673    /// Acknowledge the event a turn was about from the turn's answer, as the
674    /// agent in the session it answered in: the same request, through the same
675    /// policy, as the agent's own command would have made.
676    ///
677    /// A print that has ended by the time the turn answers is not
678    /// acknowledged: its record is closed, and nothing is left to carry on or
679    /// stop.
680    ///
681    /// # Errors
682    ///
683    /// Returns the store's own error when the request could not be recorded. A
684    /// refusal by policy is recorded with the request and is not an error.
685    async fn acknowledge_from_answer(
686        &self,
687        print_id: PrintId,
688        event_id: EventId,
689        session_name: String,
690        assessment: &AgentAssessment,
691    ) -> Result<(), CoreError> {
692        let open = self
693            .stores()
694            .prints
695            .print(print_id)
696            .await?
697            .is_some_and(|print| print.ended_at.is_none());
698        if !open {
699            return Ok(());
700        }
701        let disposition = match assessment.disposition {
702            Disposition::Continue => AcknowledgementDisposition::Continue,
703            Disposition::Watch => AcknowledgementDisposition::Watch,
704            Disposition::Stop => AcknowledgementDisposition::Stop,
705        };
706        self.request_action(
707            print_id,
708            PrintAction::AcknowledgeFailure {
709                event_id,
710                disposition,
711                reason: assessment.why.clone(),
712                actor: Actor::Agent { session_name },
713            },
714        )
715        .await?;
716        Ok(())
717    }
718
719    /// Gather the current context of one print, including while its
720    /// supervision turn is running.
721    ///
722    /// # Errors
723    ///
724    /// Returns [`CoreError::NoSuchPrint`] when nothing is held under that
725    /// identifier, and the store's own error when the context could not be
726    /// read.
727    pub async fn context(&self, print_id: PrintId) -> Result<PrintContext, CoreError> {
728        let print = self
729            .stores()
730            .prints
731            .print(print_id)
732            .await?
733            .ok_or(CoreError::NoSuchPrint { print_id })?;
734        self.gather_context(&print, None).await
735    }
736
737    /// What a supervision turn reads of one print's context, carrying only the
738    /// events newer than `since` when it names one.
739    ///
740    /// Every event newer than the one named is carried, however many the
741    /// recent window would hold: the window is widened to the history's
742    /// largest page when the event is older than it.
743    ///
744    /// # Errors
745    ///
746    /// Answers [`CoreError::NoSuchPrint`] and the store's own error as
747    /// [`Self::context`] does, and [`StoreError::NotFound`] when `since` names
748    /// none of the print's latest [`MAX_HISTORY_LIMIT`] events.
749    ///
750    /// [`StoreError::NotFound`]: crate::store::StoreError::NotFound
751    /// [`MAX_HISTORY_LIMIT`]: crate::store::MAX_HISTORY_LIMIT
752    pub async fn agent_context(
753        &self,
754        print_id: PrintId,
755        since: Option<printobserver_types::EventId>,
756    ) -> Result<AgentContext, CoreError> {
757        let context = self.context(print_id).await?;
758        let Some(event) = since else {
759            return Ok(context.for_agent(None));
760        };
761        let wider;
762        let newer = if let Some(newer) = newer_than(&context.recent_events, event) {
763            newer
764        } else {
765            wider = self
766                .recent_events_of(&context.print, crate::store::MAX_HISTORY_LIMIT)
767                .await?;
768            newer_than(&wider, event).ok_or_else(|| {
769                CoreError::Store(crate::store::StoreError::NotFound {
770                    what: format!(
771                        "event {event} among print {print_id}'s latest {} events",
772                        crate::store::MAX_HISTORY_LIMIT
773                    ),
774                })
775            })?
776        };
777        let agent = context.for_agent(Some(Since { event, newer }));
778        Ok(agent)
779    }
780
781    /// Read one print's whole context, recording a printer read that fails.
782    ///
783    /// A read failure is recorded against the event being handled when there is
784    /// one; a context read that no event prompted has nowhere to record it and
785    /// carries the absence in the context itself, which is what an absent
786    /// `printer` or `job` means.
787    ///
788    /// The job read settles the open prints exactly as the listing's does
789    /// ([`crate::listing`]) before the rest of the context is read: a job found
790    /// over closes the print, a later job of its file closes it as replaced,
791    /// and a job found to be its own is recorded on it — so the context
792    /// answered is the print as it now stands. Within a turn the turn holds the
793    /// print, and that turn closes it.
794    async fn gather_context(
795        &self,
796        print: &PrintRecord,
797        event_id: Option<printobserver_types::EventId>,
798    ) -> Result<PrintContext, CoreError> {
799        let printer = match self.read_snapshot().await {
800            Ok(snapshot) => Some(snapshot),
801            Err(error) => {
802                self.record_read_failure(
803                    print.id,
804                    event_id,
805                    PortFailureSite::PrinterSnapshot,
806                    error.to_string(),
807                )
808                .await;
809                None
810            }
811        };
812        // The job is read and settled under one hold on resolution, as the
813        // listing's is. A start holds it from the read that chooses its print
814        // until the printer has been asked to start, so a job read before that
815        // hold and settled after it would be the idle machine the start has
816        // since moved, and would close the print the start had just opened.
817        let resolving = self.resolving().await;
818        let job = match self.read_job().await {
819            Ok(job) => Some(job),
820            Err(error) => {
821                self.record_read_failure(
822                    print.id,
823                    event_id,
824                    PortFailureSite::PrinterJob,
825                    error.to_string(),
826                )
827                .await;
828                None
829            }
830        };
831        let print = match &job {
832            Some(job) if print.ended_at.is_none() => self.settle_for_context(print, job).await?,
833            _ => print.clone(),
834        };
835        drop(resolving);
836        let print = &print;
837        let manifest = self.stores().prints.manifest(print.id).await?;
838        let bounds = self.bounds_for(Some(print), print.id).await?;
839        let interventions = self.stores().actions.active_interventions(print.id).await?;
840        let recent_events = self
841            .recent_events_of(print, self.config().recent_events)
842            .await?;
843        let latest_image = recent_events.iter().find_map(|record| record.image.clone());
844        let slicer = self
845            .slicer_plan(print, job.as_ref(), &interventions)
846            .await?;
847        Ok(PrintContext {
848            print: print.clone(),
849            printer,
850            job,
851            manifest,
852            bounds: bounds.effective,
853            interventions,
854            recent_events,
855            latest_image,
856            detector: self.detector_health_for(print.id),
857            slicer,
858        })
859    }
860
861    /// One print's most recent events, newest first: its own, and what the
862    /// printer watch recorded of the machine since it opened, which is the
863    /// printer's and carries no print.
864    async fn recent_events_of(
865        &self,
866        print: &PrintRecord,
867        limit: u32,
868    ) -> Result<Vec<EventRecord>, CoreError> {
869        let mut events = self
870            .stores()
871            .events
872            .history(HistoryQuery {
873                print_id: print.id,
874                kinds: Vec::new(),
875                since: None,
876                until: None,
877                limit: Some(limit),
878            })
879            .await?;
880        let kinds = crate::watch::PRINTER_WATCH_KINDS
881            .iter()
882            .filter_map(|kind| printobserver_types::EventKind::new(*kind).ok())
883            .collect();
884        let watched = self
885            .stores()
886            .timeline
887            .timeline(crate::store::TimelineQuery {
888                kinds,
889                since: Some(print.opened_at),
890                until: None,
891                spool_id: None,
892                before: None,
893                limit: Some(limit),
894            })
895            .await?;
896        events.extend(watched.into_iter().filter(|event| event.print_id.is_none()));
897        events.sort_by_key(|event| core::cmp::Reverse((event.received_at, event.id)));
898        events.truncate(usize::try_from(limit).unwrap_or(usize::MAX));
899        Ok(events)
900    }
901
902    /// Where one image's bytes are, when the store still has them.
903    pub(crate) async fn image_path(&self, image: &ImageRef) -> Option<std::path::PathBuf> {
904        match self.stores().images.image(image.id).await {
905            Ok(ImageLookup::Found { path, .. }) => Some(path),
906            _ => None,
907        }
908    }
909
910    /// Settle the open prints against the job a context read found, and
911    /// answer the print the context is about as that left it.
912    ///
913    /// The caller holds resolution from before it read that job.
914    async fn settle_for_context(
915        &self,
916        print: &PrintRecord,
917        job: &JobSnapshot,
918    ) -> Result<PrintRecord, CoreError> {
919        let observed = ObservedJob {
920            job: job.clone(),
921            observed_at: self.clock().now(),
922        };
923        let settled = self.settle_open_prints(&observed).await?;
924        match settled.running {
925            Some(running) if running.id == print.id => Ok(running),
926            _ if settled.closed.contains(&print.id) => Ok(self
927                .stores()
928                .prints
929                .print(print.id)
930                .await?
931                .unwrap_or_else(|| print.clone())),
932            _ => Ok(print.clone()),
933        }
934    }
935
936    /// End the print, expire what it had running, and close its session.
937    ///
938    /// The interventions are expired **before** the print is ended, because a
939    /// restoration is an action against the print and a print that has already
940    /// ended is one no action may be taken against.
941    ///
942    /// The caller holds the print's turn, so no turn is acting on it while it
943    /// closes. Answers whether this closed it: a print already ended — by
944    /// another read, or by the turn that held it — is left as it ended.
945    ///
946    /// The print's filament is settled after its interventions are expired
947    /// and before it is ended ([`crate::accounting`]): a crash between the two
948    /// leaves a settled, open print, which the next close-out only ends.
949    /// `closing_job` is the job read that found the print over, when there
950    /// was one; without it the settlement reads the job itself.
951    pub(crate) async fn close_out_print(
952        &self,
953        print_id: PrintId,
954        state: &PrinterState,
955        reason: &str,
956        closing_job: Option<&JobSnapshot>,
957    ) -> Result<bool, CoreError> {
958        let print = match self.stores().prints.print(print_id).await? {
959            Some(print) if print.ended_at.is_none() => print,
960            _ => return Ok(false),
961        };
962        self.forget_detector_pause(print_id);
963        self.expire_all_active(print_id).await?;
964        self.settle_filament(&print, state, reason, closing_job)
965            .await?;
966        self.stores()
967            .prints
968            .end_print(
969                print_id,
970                state.clone(),
971                self.clock().now(),
972                reason.to_owned(),
973            )
974            .await?;
975        self.close_session_of(print_id, reason).await?;
976        self.drop_gcode_spool(print_id);
977        self.follow_up_end(print_id).await;
978        Ok(true)
979    }
980
981    /// Append one event this system raised itself.
982    pub(crate) async fn append_system_event(
983        &self,
984        print_id: PrintId,
985        body: EventBody,
986    ) -> Result<EventRecord, CoreError> {
987        self.append_system_event_to(Some(print_id), body).await
988    }
989
990    /// Append one event the supervisor itself raised, to a print's history or
991    /// to the printer's when it names none.
992    pub(crate) async fn append_system_event_to(
993        &self,
994        print_id: Option<PrintId>,
995        body: EventBody,
996    ) -> Result<EventRecord, CoreError> {
997        Ok(self
998            .stores()
999            .events
1000            .append_event(EventDraft {
1001                print_id,
1002                source: system_source(),
1003                received_at: self.clock().now(),
1004                body,
1005                raw: None,
1006            })
1007            .await?)
1008    }
1009
1010    /// Record a printer read that failed, when an event prompted the read.
1011    async fn record_read_failure(
1012        &self,
1013        print_id: PrintId,
1014        event_id: Option<printobserver_types::EventId>,
1015        site: PortFailureSite,
1016        detail: String,
1017    ) {
1018        if let Some(event_id) = event_id {
1019            self.record_port_failure(print_id, event_id, site, detail)
1020                .await;
1021        }
1022    }
1023
1024    /// Record that a port failed while one event was being handled.
1025    ///
1026    /// The event is already in the history by the time any of these sites is
1027    /// reached, which is what gives the failure somewhere to be recorded.
1028    /// Nothing is answered to the caller: the loop survives this and goes on.
1029    pub(crate) async fn record_port_failure(
1030        &self,
1031        print_id: PrintId,
1032        event_id: printobserver_types::EventId,
1033        site: PortFailureSite,
1034        detail: String,
1035    ) {
1036        self.record_port_failure_to(Some(print_id), event_id, site, detail)
1037            .await;
1038    }
1039
1040    /// Record that a port failed while one event was being handled, in the
1041    /// history that event is in: a print's, or the printer's when it names
1042    /// none.
1043    pub(crate) async fn record_port_failure_to(
1044        &self,
1045        print_id: Option<PrintId>,
1046        event_id: printobserver_types::EventId,
1047        site: PortFailureSite,
1048        detail: String,
1049    ) {
1050        // A record that will not render is dropped exactly as one the store
1051        // refuses is: the failure it was about has already been answered, and
1052        // the loop survives not having written it down.
1053        let Ok(body) = EventBody::of(&PortFailurePayload {
1054            event_id,
1055            site,
1056            detail,
1057        }) else {
1058            return;
1059        };
1060        let _ = self.append_system_event_to(print_id, body).await;
1061    }
1062}
1063
1064/// One turn's access as its port is handed it, saying too whether the turn
1065/// has asked for its print to be paused or cancelled.
1066struct StopAware {
1067    /// The turn's own issuer.
1068    inner: std::sync::Arc<dyn printobserver_supervisor_api::TurnAccess>,
1069    /// The print the turn is about.
1070    print_id: PrintId,
1071    /// The prints whose running turn has asked to stop them.
1072    stops: std::sync::Arc<std::sync::Mutex<std::collections::BTreeSet<PrintId>>>,
1073}
1074
1075impl printobserver_supervisor_api::TurnAccess for StopAware {
1076    fn issue(
1077        &self,
1078        session: &printobserver_supervisor_api::TurnSession,
1079    ) -> Result<printobserver_supervisor_api::TurnPass, printobserver_supervisor_api::SupervisorError>
1080    {
1081        self.inner.issue(session)
1082    }
1083
1084    fn asked_to_stop(&self) -> bool {
1085        self.stops
1086            .lock()
1087            .unwrap_or_else(std::sync::PoisonError::into_inner)
1088            .contains(&self.print_id)
1089    }
1090}