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