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        // A check's frame — an alert's as much as an observation's — is one the
619        // agent was shown, so the plan's rise can later be measured from it, as
620        // from a look's. Measured only from observations and looks, a check
621        // after an alert, a pause and a person's resume was told the rise since
622        // the print's first frame hours before, and paused a print growing as
623        // planned for not having risen that far (`warning-after-resume`).
624        if let Some(job) = job
625            && print.ended_at.is_none()
626            && job.file_name.is_some()
627            && job.file_name == print.file_name
628            && let Some(position) = job.file_position_bytes
629        {
630            self.gcode_indexes()
631                .note_look(print.id, captured_at, position, self.clock().now());
632        }
633        self.shown_image_of(
634            reference,
635            Some(print.id),
636            captured_at,
637            ImageUse::Check,
638            plan,
639        )
640        .await
641        .map_or((None, None), |shown| (Some(shown.path), shown.note))
642    }
643
644    /// Note that the running turn on one print asked to pause or cancel it,
645    /// whatever policy makes of the request: what an answer of `stop` is held
646    /// to.
647    pub(crate) fn note_stop_asked(&self, print_id: PrintId, action: &PrintAction) {
648        if action.actor().class() == crate::records::ActorClass::Agent
649            && matches!(
650                action,
651                PrintAction::Pause { .. } | PrintAction::Cancel { .. }
652            )
653        {
654            self.stopped_by_turn
655                .lock()
656                .unwrap_or_else(std::sync::PoisonError::into_inner)
657                .insert(print_id);
658        }
659    }
660
661    /// Forget whether a turn on one print asked to stop it, answering whether
662    /// one had.
663    fn forget_stop_asked(&self, print_id: PrintId) -> bool {
664        self.stopped_by_turn
665            .lock()
666            .unwrap_or_else(std::sync::PoisonError::into_inner)
667            .remove(&print_id)
668    }
669
670    /// Note that the running turn on one print acknowledged its event by
671    /// command.
672    pub(crate) fn note_acknowledged_by_turn(&self, print_id: PrintId) {
673        self.acknowledged_by_turn
674            .lock()
675            .unwrap_or_else(std::sync::PoisonError::into_inner)
676            .insert(print_id);
677    }
678
679    /// Forget whether a turn on one print acknowledged by command, answering
680    /// whether one had.
681    fn forget_acknowledged_by_turn(&self, print_id: PrintId) -> bool {
682        self.acknowledged_by_turn
683            .lock()
684            .unwrap_or_else(std::sync::PoisonError::into_inner)
685            .remove(&print_id)
686    }
687
688    /// Acknowledge the event a turn was about from the turn's answer, as the
689    /// agent in the session it answered in: the same request, through the same
690    /// policy, as the agent's own command would have made.
691    ///
692    /// A print that has ended by the time the turn answers is not
693    /// acknowledged: its record is closed, and nothing is left to carry on or
694    /// stop.
695    ///
696    /// # Errors
697    ///
698    /// Returns the store's own error when the request could not be recorded. A
699    /// refusal by policy is recorded with the request and is not an error.
700    async fn acknowledge_from_answer(
701        &self,
702        print_id: PrintId,
703        event_id: EventId,
704        session_name: String,
705        assessment: &AgentAssessment,
706    ) -> Result<(), CoreError> {
707        let open = self
708            .stores()
709            .prints
710            .print(print_id)
711            .await?
712            .is_some_and(|print| print.ended_at.is_none());
713        if !open {
714            return Ok(());
715        }
716        let disposition = match assessment.disposition {
717            Disposition::Continue => AcknowledgementDisposition::Continue,
718            Disposition::Watch => AcknowledgementDisposition::Watch,
719            Disposition::Stop => AcknowledgementDisposition::Stop,
720        };
721        self.request_action(
722            print_id,
723            PrintAction::AcknowledgeFailure {
724                event_id,
725                disposition,
726                reason: assessment.why.clone(),
727                actor: Actor::Agent { session_name },
728            },
729        )
730        .await?;
731        Ok(())
732    }
733
734    /// Gather the current context of one print, including while its
735    /// supervision turn is running.
736    ///
737    /// # Errors
738    ///
739    /// Returns [`CoreError::NoSuchPrint`] when nothing is held under that
740    /// identifier, and the store's own error when the context could not be
741    /// read.
742    pub async fn context(&self, print_id: PrintId) -> Result<PrintContext, CoreError> {
743        let print = self
744            .stores()
745            .prints
746            .print(print_id)
747            .await?
748            .ok_or(CoreError::NoSuchPrint { print_id })?;
749        self.gather_context(&print, None).await
750    }
751
752    /// What a supervision turn reads of one print's context, carrying only the
753    /// events newer than `since` when it names one.
754    ///
755    /// Every event newer than the one named is carried, however many the
756    /// recent window would hold: the window is widened to the history's
757    /// largest page when the event is older than it.
758    ///
759    /// # Errors
760    ///
761    /// Answers [`CoreError::NoSuchPrint`] and the store's own error as
762    /// [`Self::context`] does, and [`StoreError::NotFound`] when `since` names
763    /// none of the print's latest [`MAX_HISTORY_LIMIT`] events.
764    ///
765    /// [`StoreError::NotFound`]: crate::store::StoreError::NotFound
766    /// [`MAX_HISTORY_LIMIT`]: crate::store::MAX_HISTORY_LIMIT
767    pub async fn agent_context(
768        &self,
769        print_id: PrintId,
770        since: Option<printobserver_types::EventId>,
771    ) -> Result<AgentContext, CoreError> {
772        let context = self.context(print_id).await?;
773        let Some(event) = since else {
774            return Ok(context.for_agent(None));
775        };
776        let wider;
777        let newer = if let Some(newer) = newer_than(&context.recent_events, event) {
778            newer
779        } else {
780            wider = self
781                .recent_events_of(&context.print, crate::store::MAX_HISTORY_LIMIT)
782                .await?;
783            newer_than(&wider, event).ok_or_else(|| {
784                CoreError::Store(crate::store::StoreError::NotFound {
785                    what: format!(
786                        "event {event} among print {print_id}'s latest {} events",
787                        crate::store::MAX_HISTORY_LIMIT
788                    ),
789                })
790            })?
791        };
792        let agent = context.for_agent(Some(Since { event, newer }));
793        Ok(agent)
794    }
795
796    /// Read one print's whole context, recording a printer read that fails.
797    ///
798    /// A read failure is recorded against the event being handled when there is
799    /// one; a context read that no event prompted has nowhere to record it and
800    /// carries the absence in the context itself, which is what an absent
801    /// `printer` or `job` means.
802    ///
803    /// The job read settles the open prints exactly as the listing's does
804    /// ([`crate::listing`]) before the rest of the context is read: a job found
805    /// over closes the print, a later job of its file closes it as replaced,
806    /// and a job found to be its own is recorded on it — so the context
807    /// answered is the print as it now stands. Within a turn the turn holds the
808    /// print, and that turn closes it.
809    async fn gather_context(
810        &self,
811        print: &PrintRecord,
812        event_id: Option<printobserver_types::EventId>,
813    ) -> Result<PrintContext, CoreError> {
814        let printer = match self.read_snapshot().await {
815            Ok(snapshot) => Some(snapshot),
816            Err(error) => {
817                self.record_read_failure(
818                    print.id,
819                    event_id,
820                    PortFailureSite::PrinterSnapshot,
821                    error.to_string(),
822                )
823                .await;
824                None
825            }
826        };
827        // The job is read and settled under one hold on resolution, as the
828        // listing's is. A start holds it from the read that chooses its print
829        // until the printer has been asked to start, so a job read before that
830        // hold and settled after it would be the idle machine the start has
831        // since moved, and would close the print the start had just opened.
832        let resolving = self.resolving().await;
833        let job = match self.read_job().await {
834            Ok(job) => Some(job),
835            Err(error) => {
836                self.record_read_failure(
837                    print.id,
838                    event_id,
839                    PortFailureSite::PrinterJob,
840                    error.to_string(),
841                )
842                .await;
843                None
844            }
845        };
846        let print = match &job {
847            Some(job) if print.ended_at.is_none() => self.settle_for_context(print, job).await?,
848            _ => print.clone(),
849        };
850        drop(resolving);
851        let print = &print;
852        let manifest = self.stores().prints.manifest(print.id).await?;
853        let bounds = self.bounds_for(Some(print), print.id).await?;
854        let interventions = self.stores().actions.active_interventions(print.id).await?;
855        let recent_events = self
856            .recent_events_of(print, self.config().recent_events)
857            .await?;
858        let latest_image = recent_events.iter().find_map(|record| record.image.clone());
859        let slicer = self
860            .slicer_plan(print, job.as_ref(), &interventions)
861            .await?;
862        Ok(PrintContext {
863            print: print.clone(),
864            printer,
865            job,
866            manifest,
867            bounds: bounds.effective,
868            interventions,
869            recent_events,
870            latest_image,
871            detector: self.detector_health_for(print.id),
872            slicer,
873        })
874    }
875
876    /// One print's most recent events, newest first: its own, and what the
877    /// printer watch recorded of the machine since it opened, which is the
878    /// printer's and carries no print.
879    async fn recent_events_of(
880        &self,
881        print: &PrintRecord,
882        limit: u32,
883    ) -> Result<Vec<EventRecord>, CoreError> {
884        let mut events = self
885            .stores()
886            .events
887            .history(HistoryQuery {
888                print_id: print.id,
889                kinds: Vec::new(),
890                since: None,
891                until: None,
892                limit: Some(limit),
893            })
894            .await?;
895        let kinds = crate::watch::PRINTER_WATCH_KINDS
896            .iter()
897            .filter_map(|kind| printobserver_types::EventKind::new(*kind).ok())
898            .collect();
899        let watched = self
900            .stores()
901            .timeline
902            .timeline(crate::store::TimelineQuery {
903                kinds,
904                since: Some(print.opened_at),
905                until: None,
906                spool_id: None,
907                before: None,
908                limit: Some(limit),
909            })
910            .await?;
911        events.extend(watched.into_iter().filter(|event| event.print_id.is_none()));
912        events.sort_by_key(|event| core::cmp::Reverse((event.received_at, event.id)));
913        events.truncate(usize::try_from(limit).unwrap_or(usize::MAX));
914        Ok(events)
915    }
916
917    /// Where one image's bytes are, when the store still has them.
918    pub(crate) async fn image_path(&self, image: &ImageRef) -> Option<std::path::PathBuf> {
919        match self.stores().images.image(image.id).await {
920            Ok(ImageLookup::Found { path, .. }) => Some(path),
921            _ => None,
922        }
923    }
924
925    /// Settle the open prints against the job a context read found, and
926    /// answer the print the context is about as that left it.
927    ///
928    /// The caller holds resolution from before it read that job.
929    async fn settle_for_context(
930        &self,
931        print: &PrintRecord,
932        job: &JobSnapshot,
933    ) -> Result<PrintRecord, CoreError> {
934        let observed = ObservedJob {
935            job: job.clone(),
936            observed_at: self.clock().now(),
937        };
938        let settled = self.settle_open_prints(&observed).await?;
939        match settled.running {
940            Some(running) if running.id == print.id => Ok(running),
941            _ if settled.closed.contains(&print.id) => Ok(self
942                .stores()
943                .prints
944                .print(print.id)
945                .await?
946                .unwrap_or_else(|| print.clone())),
947            _ => Ok(print.clone()),
948        }
949    }
950
951    /// End the print, expire what it had running, and close its session.
952    ///
953    /// The interventions are expired **before** the print is ended, because a
954    /// restoration is an action against the print and a print that has already
955    /// ended is one no action may be taken against.
956    ///
957    /// The caller holds the print's turn, so no turn is acting on it while it
958    /// closes. Answers whether this closed it: a print already ended — by
959    /// another read, or by the turn that held it — is left as it ended.
960    ///
961    /// The print's filament is settled after its interventions are expired
962    /// and before it is ended ([`crate::accounting`]): a crash between the two
963    /// leaves a settled, open print, which the next close-out only ends.
964    /// `closing_job` is the job read that found the print over, when there
965    /// was one; without it the settlement reads the job itself.
966    pub(crate) async fn close_out_print(
967        &self,
968        print_id: PrintId,
969        state: &PrinterState,
970        reason: &str,
971        closing_job: Option<&JobSnapshot>,
972    ) -> Result<bool, CoreError> {
973        let print = match self.stores().prints.print(print_id).await? {
974            Some(print) if print.ended_at.is_none() => print,
975            _ => return Ok(false),
976        };
977        self.forget_detector_pause(print_id);
978        self.expire_all_active(print_id).await?;
979        self.settle_filament(&print, state, reason, closing_job)
980            .await?;
981        self.stores()
982            .prints
983            .end_print(
984                print_id,
985                state.clone(),
986                self.clock().now(),
987                reason.to_owned(),
988            )
989            .await?;
990        self.close_session_of(print_id, reason).await?;
991        self.drop_gcode_spool(print_id);
992        self.follow_up_end(print_id).await;
993        Ok(true)
994    }
995
996    /// Append one event this system raised itself.
997    pub(crate) async fn append_system_event(
998        &self,
999        print_id: PrintId,
1000        body: EventBody,
1001    ) -> Result<EventRecord, CoreError> {
1002        self.append_system_event_to(Some(print_id), body).await
1003    }
1004
1005    /// Append one event the supervisor itself raised, to a print's history or
1006    /// to the printer's when it names none.
1007    pub(crate) async fn append_system_event_to(
1008        &self,
1009        print_id: Option<PrintId>,
1010        body: EventBody,
1011    ) -> Result<EventRecord, CoreError> {
1012        Ok(self
1013            .stores()
1014            .events
1015            .append_event(EventDraft {
1016                print_id,
1017                source: system_source(),
1018                received_at: self.clock().now(),
1019                body,
1020                raw: None,
1021            })
1022            .await?)
1023    }
1024
1025    /// Record a printer read that failed, when an event prompted the read.
1026    async fn record_read_failure(
1027        &self,
1028        print_id: PrintId,
1029        event_id: Option<printobserver_types::EventId>,
1030        site: PortFailureSite,
1031        detail: String,
1032    ) {
1033        if let Some(event_id) = event_id {
1034            self.record_port_failure(print_id, event_id, site, detail)
1035                .await;
1036        }
1037    }
1038
1039    /// Record that a port failed while one event was being handled.
1040    ///
1041    /// The event is already in the history by the time any of these sites is
1042    /// reached, which is what gives the failure somewhere to be recorded.
1043    /// Nothing is answered to the caller: the loop survives this and goes on.
1044    pub(crate) async fn record_port_failure(
1045        &self,
1046        print_id: PrintId,
1047        event_id: printobserver_types::EventId,
1048        site: PortFailureSite,
1049        detail: String,
1050    ) {
1051        self.record_port_failure_to(Some(print_id), event_id, site, detail)
1052            .await;
1053    }
1054
1055    /// Record that a port failed while one event was being handled, in the
1056    /// history that event is in: a print's, or the printer's when it names
1057    /// none.
1058    pub(crate) async fn record_port_failure_to(
1059        &self,
1060        print_id: Option<PrintId>,
1061        event_id: printobserver_types::EventId,
1062        site: PortFailureSite,
1063        detail: String,
1064    ) {
1065        // A record that will not render is dropped exactly as one the store
1066        // refuses is: the failure it was about has already been answered, and
1067        // the loop survives not having written it down.
1068        let Ok(body) = EventBody::of(&PortFailurePayload {
1069            event_id,
1070            site,
1071            detail,
1072        }) else {
1073            return;
1074        };
1075        let _ = self.append_system_event_to(print_id, body).await;
1076    }
1077}
1078
1079/// One turn's access as its port is handed it, saying too whether the turn
1080/// has asked for its print to be paused or cancelled.
1081struct StopAware {
1082    /// The turn's own issuer.
1083    inner: std::sync::Arc<dyn printobserver_supervisor_api::TurnAccess>,
1084    /// The print the turn is about.
1085    print_id: PrintId,
1086    /// The prints whose running turn has asked to stop them.
1087    stops: std::sync::Arc<std::sync::Mutex<std::collections::BTreeSet<PrintId>>>,
1088}
1089
1090impl printobserver_supervisor_api::TurnAccess for StopAware {
1091    fn issue(
1092        &self,
1093        session: &printobserver_supervisor_api::TurnSession,
1094    ) -> Result<printobserver_supervisor_api::TurnPass, printobserver_supervisor_api::SupervisorError>
1095    {
1096        self.inner.issue(session)
1097    }
1098
1099    fn asked_to_stop(&self) -> bool {
1100        self.stops
1101            .lock()
1102            .unwrap_or_else(std::sync::PoisonError::into_inner)
1103            .contains(&self.print_id)
1104    }
1105}