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