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 TurnCheckImage, 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 (handed, image_path) = (shown.as_recorded(event.id), 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, handed, 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, the image it was handed — and acknowledge its event from
603 /// the answer when the turn 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 check_image: Option<TurnCheckImage>,
610 acknowledged_by_command: bool,
611 ) -> Result<(), CoreError> {
612 if outcome.phase == SessionPhase::Created {
613 self.append_system_event(
614 print_id,
615 EventBody::of(&SupervisionSessionOpenedPayload {
616 session_name: outcome.session.session_name.clone(),
617 harness_identity: outcome.session.harness_identity.clone(),
618 })?,
619 )
620 .await?;
621 }
622 let session_name = outcome.session.session_name.clone();
623 self.stores().sessions.put_session(outcome.session).await?;
624 let assessment = outcome.assessment;
625 self.append_system_event(
626 print_id,
627 EventBody::of(&AgentAssessmentPayload {
628 session_name: session_name.clone(),
629 assessment: assessment.clone(),
630 check_image,
631 })?,
632 )
633 .await?;
634 if !acknowledged_by_command
635 && let Err(error) = self
636 .acknowledge_from_answer(print_id, event_id, session_name, &assessment)
637 .await
638 {
639 // The turn answered; an acknowledgement that could not be
640 // made is recorded against its event and ends nothing. Only a
641 // store failing mid-turn reaches here, which the real store can
642 // be made to do only by breaking its database under a running
643 // server; the core journey
644 // `an_acknowledgement_the_answer_cannot_make_is_recorded_and_supervision_goes_on`
645 // proves it over a store that fails its history read instead.
646 self.record_port_failure(
647 print_id,
648 event_id,
649 PortFailureSite::SupervisionTurn,
650 format!("the answer's acknowledgement could not be made: {error}"),
651 )
652 .await;
653 }
654 Ok(())
655 }
656
657 /// Write down that the agent answered a running print should stop and
658 /// stopped nothing, when the print is still open: its history is where a
659 /// refused pause is, which is what the person reading it reads.
660 ///
661 /// # Errors
662 ///
663 /// Returns the store's own error when the print or its history could not
664 /// be read or written.
665 async fn record_unacted_stop(
666 &self,
667 print_id: PrintId,
668 event_id: EventId,
669 (session_name, summary): (String, String),
670 ) -> Result<(), CoreError> {
671 let open = self
672 .stores()
673 .prints
674 .print(print_id)
675 .await?
676 .is_some_and(|print| print.ended_at.is_none());
677 if !open {
678 return Ok(());
679 }
680 self.append_system_event(
681 print_id,
682 EventBody::of(&AgentStopUnactedPayload {
683 event_id,
684 session_name,
685 summary,
686 })?,
687 )
688 .await?;
689 Ok(())
690 }
691
692 /// The image a check of one arrival is shown, the line saying what it is,
693 /// which image it is and why, and when the frame it shows was captured,
694 /// made where the job stood in the print's own file: none when the arrival
695 /// carries no frame.
696 ///
697 /// A detector's alert whose camera frame was had is shown that frame's
698 /// three-panel image; where it was not had or not composed, the detector's
699 /// own picture, as any check is shown its frame. Only the camera's own
700 /// frames are judged against its calibration: a detector's picture is not
701 /// necessarily its stream at its size.
702 async fn check_image_for(
703 &self,
704 print: &PrintRecord,
705 arrival: &Arrival,
706 job: Option<&JobSnapshot>,
707 paused: bool,
708 ) -> CheckShown {
709 let event = &arrival.event;
710 let imageless = CheckShown {
711 captured_at: arrival.frame_captured_at,
712 ..CheckShown::default()
713 };
714 let Some(reference) = &event.image else {
715 return imageless;
716 };
717 let plan = self.plan_position(print, job).await;
718 if let AlertCameraFrame::Had { image, captured_at } = &arrival.camera_frame {
719 let shown = self
720 .shown_image_of(
721 image,
722 Some(print.id),
723 *captured_at,
724 ImageUse::Check,
725 plan.clone(),
726 true,
727 paused,
728 )
729 .await;
730 if let Some(shown) = shown.filter(|shown| shown.composite) {
731 self.note_check_frame(print, job, *captured_at);
732 let kind = Some(shown.kind());
733 let note = shown
734 .note
735 .map(|note| format!("{note}; {ALERT_CAMERA_FRAME_NOTE}"));
736 return CheckShown {
737 kind,
738 path: Some(shown.path),
739 note,
740 fallback: shown.fallback,
741 captured_at: Some(*captured_at),
742 };
743 }
744 }
745 let captured_at = captured_at_of(event, arrival.frame_captured_at);
746 self.note_check_frame(print, job, captured_at);
747 let missing = match &arrival.camera_frame {
748 AlertCameraFrame::Missing(why) => Some(why.as_str()),
749 AlertCameraFrame::NotAsked | AlertCameraFrame::Had { .. } => None,
750 };
751 self.shown_image_of(
752 reference,
753 Some(print.id),
754 captured_at,
755 ImageUse::Check,
756 plan,
757 arrival.detection.is_none(),
758 paused,
759 )
760 .await
761 .map_or(imageless, |shown| {
762 let kind = Some(shown.kind());
763 let note = match (shown.note, missing) {
764 (Some(note), Some(why)) => Some(format!(
765 "{note}; the detector's own picture, because the camera gave no frame of its own as the alert arrived: {why}"
766 )),
767 (note, _) => note,
768 };
769 CheckShown {
770 path: Some(shown.path),
771 note,
772 kind,
773 fallback: shown.fallback,
774 captured_at: arrival.frame_captured_at,
775 }
776 })
777 }
778
779 /// Note the frame a check was shown, so the plan's rise can later be
780 /// measured from it, as from a look's.
781 ///
782 /// A check's frame — an alert's as much as an observation's — is one the
783 /// agent was shown. Measured only from observations and looks, a check
784 /// after an alert, a pause and a person's resume was told the rise since
785 /// the print's first frame hours before, and paused a print growing as
786 /// planned for not having risen that far (`warning-after-resume`).
787 fn note_check_frame(
788 &self,
789 print: &PrintRecord,
790 job: Option<&JobSnapshot>,
791 captured_at: Timestamp,
792 ) {
793 if let Some(job) = job
794 && print.ended_at.is_none()
795 && job.file_name.is_some()
796 && job.file_name == print.file_name
797 && let Some(position) = job.file_position_bytes
798 {
799 self.gcode_indexes()
800 .note_look(print.id, captured_at, position, self.clock().now());
801 }
802 }
803
804 /// Note that the running turn on one print asked to pause or cancel it,
805 /// whatever policy makes of the request: what an answer of `stop` is held
806 /// to.
807 pub(crate) fn note_stop_asked(&self, print_id: PrintId, action: &PrintAction) {
808 if action.actor().class() == crate::records::ActorClass::Agent
809 && matches!(
810 action,
811 PrintAction::Pause { .. } | PrintAction::Cancel { .. }
812 )
813 {
814 self.stopped_by_turn
815 .lock()
816 .unwrap_or_else(std::sync::PoisonError::into_inner)
817 .insert(print_id);
818 }
819 }
820
821 /// Forget whether a turn on one print asked to stop it, answering whether
822 /// one had.
823 fn forget_stop_asked(&self, print_id: PrintId) -> bool {
824 self.stopped_by_turn
825 .lock()
826 .unwrap_or_else(std::sync::PoisonError::into_inner)
827 .remove(&print_id)
828 }
829
830 /// Note that the running turn on one print acknowledged its event by
831 /// command.
832 pub(crate) fn note_acknowledged_by_turn(&self, print_id: PrintId) {
833 self.acknowledged_by_turn
834 .lock()
835 .unwrap_or_else(std::sync::PoisonError::into_inner)
836 .insert(print_id);
837 }
838
839 /// Forget whether a turn on one print acknowledged by command, answering
840 /// whether one had.
841 fn forget_acknowledged_by_turn(&self, print_id: PrintId) -> bool {
842 self.acknowledged_by_turn
843 .lock()
844 .unwrap_or_else(std::sync::PoisonError::into_inner)
845 .remove(&print_id)
846 }
847
848 /// Acknowledge the event a turn was about from the turn's answer, as the
849 /// agent in the session it answered in: the same request, through the same
850 /// policy, as the agent's own command would have made.
851 ///
852 /// A print that has ended by the time the turn answers is not
853 /// acknowledged: its record is closed, and nothing is left to carry on or
854 /// stop.
855 ///
856 /// # Errors
857 ///
858 /// Returns the store's own error when the request could not be recorded. A
859 /// refusal by policy is recorded with the request and is not an error.
860 async fn acknowledge_from_answer(
861 &self,
862 print_id: PrintId,
863 event_id: EventId,
864 session_name: String,
865 assessment: &AgentAssessment,
866 ) -> Result<(), CoreError> {
867 let open = self
868 .stores()
869 .prints
870 .print(print_id)
871 .await?
872 .is_some_and(|print| print.ended_at.is_none());
873 if !open {
874 return Ok(());
875 }
876 let disposition = match assessment.disposition {
877 Disposition::Continue => AcknowledgementDisposition::Continue,
878 Disposition::Watch => AcknowledgementDisposition::Watch,
879 Disposition::Stop => AcknowledgementDisposition::Stop,
880 };
881 self.request_action(
882 print_id,
883 PrintAction::AcknowledgeFailure {
884 event_id,
885 disposition,
886 reason: assessment.why.clone(),
887 actor: Actor::Agent { session_name },
888 },
889 )
890 .await?;
891 Ok(())
892 }
893
894 /// Gather the current context of one print, including while its
895 /// supervision turn is running.
896 ///
897 /// # Errors
898 ///
899 /// Returns [`CoreError::NoSuchPrint`] when nothing is held under that
900 /// identifier, and the store's own error when the context could not be
901 /// read.
902 pub async fn context(&self, print_id: PrintId) -> Result<PrintContext, CoreError> {
903 let print = self
904 .stores()
905 .prints
906 .print(print_id)
907 .await?
908 .ok_or(CoreError::NoSuchPrint { print_id })?;
909 self.gather_context(&print, None).await
910 }
911
912 /// What a supervision turn reads of one print's context, carrying only the
913 /// events newer than `since` when it names one.
914 ///
915 /// Every event newer than the one named is carried, however many the
916 /// recent window would hold: the window is widened to the history's
917 /// largest page when the event is older than it.
918 ///
919 /// # Errors
920 ///
921 /// Answers [`CoreError::NoSuchPrint`] and the store's own error as
922 /// [`Self::context`] does, and [`StoreError::NotFound`] when `since` names
923 /// none of the print's latest [`MAX_HISTORY_LIMIT`] events.
924 ///
925 /// [`StoreError::NotFound`]: crate::store::StoreError::NotFound
926 /// [`MAX_HISTORY_LIMIT`]: crate::store::MAX_HISTORY_LIMIT
927 pub async fn agent_context(
928 &self,
929 print_id: PrintId,
930 since: Option<printobserver_types::EventId>,
931 ) -> Result<AgentContext, CoreError> {
932 let context = self.context(print_id).await?;
933 let Some(event) = since else {
934 return Ok(context.for_agent(None));
935 };
936 let wider;
937 let newer = if let Some(newer) = newer_than(&context.recent_events, event) {
938 newer
939 } else {
940 wider = self
941 .recent_events_of(&context.print, crate::store::MAX_HISTORY_LIMIT)
942 .await?;
943 newer_than(&wider, event).ok_or_else(|| {
944 CoreError::Store(crate::store::StoreError::NotFound {
945 what: format!(
946 "event {event} among print {print_id}'s latest {} events",
947 crate::store::MAX_HISTORY_LIMIT
948 ),
949 })
950 })?
951 };
952 let agent = context.for_agent(Some(Since { event, newer }));
953 Ok(agent)
954 }
955
956 /// Read one print's whole context, recording a printer read that fails.
957 ///
958 /// A read failure is recorded against the event being handled when there is
959 /// one; a context read that no event prompted has nowhere to record it and
960 /// carries the absence in the context itself, which is what an absent
961 /// `printer` or `job` means.
962 ///
963 /// The job read settles the open prints exactly as the listing's does
964 /// ([`crate::listing`]) before the rest of the context is read: a job found
965 /// over closes the print, a later job of its file closes it as replaced,
966 /// and a job found to be its own is recorded on it — so the context
967 /// answered is the print as it now stands. Within a turn the turn holds the
968 /// print, and that turn closes it.
969 async fn gather_context(
970 &self,
971 print: &PrintRecord,
972 event_id: Option<printobserver_types::EventId>,
973 ) -> Result<PrintContext, CoreError> {
974 let printer = match self.read_snapshot().await {
975 Ok(snapshot) => Some(snapshot),
976 Err(error) => {
977 self.record_read_failure(
978 print.id,
979 event_id,
980 PortFailureSite::PrinterSnapshot,
981 error.to_string(),
982 )
983 .await;
984 None
985 }
986 };
987 // The job is read and settled under one hold on resolution, as the
988 // listing's is. A start holds it from the read that chooses its print
989 // until the printer has been asked to start, so a job read before that
990 // hold and settled after it would be the idle machine the start has
991 // since moved, and would close the print the start had just opened.
992 let resolving = self.resolving().await;
993 let job = match self.read_job().await {
994 Ok(job) => Some(job),
995 Err(error) => {
996 self.record_read_failure(
997 print.id,
998 event_id,
999 PortFailureSite::PrinterJob,
1000 error.to_string(),
1001 )
1002 .await;
1003 None
1004 }
1005 };
1006 let print = match &job {
1007 Some(job) if print.ended_at.is_none() => self.settle_for_context(print, job).await?,
1008 _ => print.clone(),
1009 };
1010 drop(resolving);
1011 let print = &print;
1012 let manifest = self.stores().prints.manifest(print.id).await?;
1013 let bounds = self.bounds_for(Some(print), print.id).await?;
1014 let interventions = self.stores().actions.active_interventions(print.id).await?;
1015 let recent_events = self
1016 .recent_events_of(print, self.config().recent_events)
1017 .await?;
1018 let latest_image = recent_events.iter().find_map(|record| record.image.clone());
1019 let slicer = self
1020 .slicer_plan(print, job.as_ref(), &interventions)
1021 .await?;
1022 Ok(PrintContext {
1023 print: print.clone(),
1024 printer,
1025 job,
1026 manifest,
1027 bounds: bounds.effective,
1028 interventions,
1029 recent_events,
1030 latest_image,
1031 detector: self.detector_health_for(print.id),
1032 slicer,
1033 })
1034 }
1035
1036 /// One print's most recent events, newest first: its own, and what the
1037 /// printer watch recorded of the machine since it opened, which is the
1038 /// printer's and carries no print.
1039 async fn recent_events_of(
1040 &self,
1041 print: &PrintRecord,
1042 limit: u32,
1043 ) -> Result<Vec<EventRecord>, CoreError> {
1044 let mut events = self
1045 .stores()
1046 .events
1047 .history(HistoryQuery {
1048 print_id: print.id,
1049 kinds: Vec::new(),
1050 since: None,
1051 until: None,
1052 limit: Some(limit),
1053 })
1054 .await?;
1055 let kinds = crate::watch::PRINTER_WATCH_KINDS
1056 .iter()
1057 .filter_map(|kind| printobserver_types::EventKind::new(*kind).ok())
1058 .collect();
1059 let watched = self
1060 .stores()
1061 .timeline
1062 .timeline(crate::store::TimelineQuery {
1063 kinds,
1064 since: Some(print.opened_at),
1065 until: None,
1066 spool_id: None,
1067 before: None,
1068 limit: Some(limit),
1069 })
1070 .await?;
1071 events.extend(watched.into_iter().filter(|event| event.print_id.is_none()));
1072 events.sort_by_key(|event| core::cmp::Reverse((event.received_at, event.id)));
1073 events.truncate(usize::try_from(limit).unwrap_or(usize::MAX));
1074 Ok(events)
1075 }
1076
1077 /// Where one image's bytes are, when the store still has them.
1078 pub(crate) async fn image_path(&self, image: &ImageRef) -> Option<std::path::PathBuf> {
1079 match self.stores().images.image(image.id).await {
1080 Ok(ImageLookup::Found { path, .. }) => Some(path),
1081 _ => None,
1082 }
1083 }
1084
1085 /// Settle the open prints against the job a context read found, and
1086 /// answer the print the context is about as that left it.
1087 ///
1088 /// The caller holds resolution from before it read that job.
1089 async fn settle_for_context(
1090 &self,
1091 print: &PrintRecord,
1092 job: &JobSnapshot,
1093 ) -> Result<PrintRecord, CoreError> {
1094 let observed = ObservedJob {
1095 job: job.clone(),
1096 observed_at: self.clock().now(),
1097 };
1098 let settled = self.settle_open_prints(&observed).await?;
1099 match settled.running {
1100 Some(running) if running.id == print.id => Ok(running),
1101 _ if settled.closed.contains(&print.id) => Ok(self
1102 .stores()
1103 .prints
1104 .print(print.id)
1105 .await?
1106 .unwrap_or_else(|| print.clone())),
1107 _ => Ok(print.clone()),
1108 }
1109 }
1110
1111 /// End the print, expire what it had running, and close its session.
1112 ///
1113 /// The interventions are expired **before** the print is ended, because a
1114 /// restoration is an action against the print and a print that has already
1115 /// ended is one no action may be taken against.
1116 ///
1117 /// The caller holds the print's turn, so no turn is acting on it while it
1118 /// closes. Answers whether this closed it: a print already ended — by
1119 /// another read, or by the turn that held it — is left as it ended.
1120 ///
1121 /// The print's filament is settled after its interventions are expired
1122 /// and before it is ended ([`crate::accounting`]): a crash between the two
1123 /// leaves a settled, open print, which the next close-out only ends.
1124 /// `closing_job` is the job read that found the print over, when there
1125 /// was one; without it the settlement reads the job itself.
1126 pub(crate) async fn close_out_print(
1127 &self,
1128 print_id: PrintId,
1129 state: &PrinterState,
1130 reason: &str,
1131 closing_job: Option<&JobSnapshot>,
1132 ) -> Result<bool, CoreError> {
1133 let print = match self.stores().prints.print(print_id).await? {
1134 Some(print) if print.ended_at.is_none() => print,
1135 _ => return Ok(false),
1136 };
1137 self.forget_detector_pause(print_id);
1138 self.expire_all_active(print_id).await?;
1139 self.settle_filament(&print, state, reason, closing_job)
1140 .await?;
1141 self.stores()
1142 .prints
1143 .end_print(
1144 print_id,
1145 state.clone(),
1146 self.clock().now(),
1147 reason.to_owned(),
1148 )
1149 .await?;
1150 self.close_session_of(print_id, reason).await?;
1151 self.drop_gcode_spool(print_id);
1152 self.forget_planned_changes(print_id);
1153 self.follow_up_end(print_id).await;
1154 Ok(true)
1155 }
1156
1157 /// Append one event this system raised itself.
1158 pub(crate) async fn append_system_event(
1159 &self,
1160 print_id: PrintId,
1161 body: EventBody,
1162 ) -> Result<EventRecord, CoreError> {
1163 self.append_system_event_to(Some(print_id), body).await
1164 }
1165
1166 /// Append one event the supervisor itself raised, to a print's history or
1167 /// to the printer's when it names none.
1168 pub(crate) async fn append_system_event_to(
1169 &self,
1170 print_id: Option<PrintId>,
1171 body: EventBody,
1172 ) -> Result<EventRecord, CoreError> {
1173 Ok(self
1174 .stores()
1175 .events
1176 .append_event(EventDraft {
1177 print_id,
1178 source: system_source(),
1179 received_at: self.clock().now(),
1180 body,
1181 raw: None,
1182 })
1183 .await?)
1184 }
1185
1186 /// Record a printer read that failed, when an event prompted the read.
1187 async fn record_read_failure(
1188 &self,
1189 print_id: PrintId,
1190 event_id: Option<printobserver_types::EventId>,
1191 site: PortFailureSite,
1192 detail: String,
1193 ) {
1194 if let Some(event_id) = event_id {
1195 self.record_port_failure(print_id, event_id, site, detail)
1196 .await;
1197 }
1198 }
1199
1200 /// Record that a port failed while one event was being handled.
1201 ///
1202 /// The event is already in the history by the time any of these sites is
1203 /// reached, which is what gives the failure somewhere to be recorded.
1204 /// Nothing is answered to the caller: the loop survives this and goes on.
1205 pub(crate) async fn record_port_failure(
1206 &self,
1207 print_id: PrintId,
1208 event_id: printobserver_types::EventId,
1209 site: PortFailureSite,
1210 detail: String,
1211 ) {
1212 self.record_port_failure_to(Some(print_id), event_id, site, detail)
1213 .await;
1214 }
1215
1216 /// Record that a port failed while one event was being handled, in the
1217 /// history that event is in: a print's, or the printer's when it names
1218 /// none.
1219 pub(crate) async fn record_port_failure_to(
1220 &self,
1221 print_id: Option<PrintId>,
1222 event_id: printobserver_types::EventId,
1223 site: PortFailureSite,
1224 detail: String,
1225 ) {
1226 // A record that will not render is dropped exactly as one the store
1227 // refuses is: the failure it was about has already been answered, and
1228 // the loop survives not having written it down.
1229 let Ok(body) = EventBody::of(&PortFailurePayload {
1230 event_id,
1231 site,
1232 detail,
1233 }) else {
1234 return;
1235 };
1236 let _ = self.append_system_event_to(print_id, body).await;
1237 }
1238}
1239
1240/// One turn's access as its port is handed it, saying too whether the turn
1241/// has asked for its print to be paused or cancelled.
1242struct StopAware {
1243 /// The turn's own issuer.
1244 inner: std::sync::Arc<dyn printobserver_supervisor_api::TurnAccess>,
1245 /// The print the turn is about.
1246 print_id: PrintId,
1247 /// The prints whose running turn has asked to stop them.
1248 stops: std::sync::Arc<std::sync::Mutex<std::collections::BTreeSet<PrintId>>>,
1249}
1250
1251impl printobserver_supervisor_api::TurnAccess for StopAware {
1252 fn issue(
1253 &self,
1254 session: &printobserver_supervisor_api::TurnSession,
1255 ) -> Result<printobserver_supervisor_api::TurnPass, printobserver_supervisor_api::SupervisorError>
1256 {
1257 self.inner.issue(session)
1258 }
1259
1260 fn asked_to_stop(&self) -> bool {
1261 self.stops
1262 .lock()
1263 .unwrap_or_else(std::sync::PoisonError::into_inner)
1264 .contains(&self.print_id)
1265 }
1266}
1267
1268/// What a check of one arrival was shown: the image, the line saying what it
1269/// is, which image it is and why, and when its frame was captured.
1270#[derive(Debug, Clone, Default)]
1271struct CheckShown {
1272 /// The image's path.
1273 path: Option<std::path::PathBuf>,
1274 /// The line saying what it is.
1275 note: Option<String>,
1276 /// Which image it is.
1277 kind: Option<printobserver_supervisor_api::ImageKind>,
1278 /// Why it is the whole frame.
1279 fallback: Option<printobserver_supervisor_api::ImageFallback>,
1280 /// When the frame it shows was captured, when the turn is told.
1281 captured_at: Option<Timestamp>,
1282}
1283
1284impl CheckShown {
1285 /// What a turn shown this as its check of `event_id` is recorded as
1286 /// having been handed, with its answer, so the operator can open the very
1287 /// image each turn judged: nothing when it was handed no image.
1288 fn as_recorded(&self, event_id: EventId) -> Option<TurnCheckImage> {
1289 self.path.clone().map(|path| TurnCheckImage {
1290 event_id,
1291 path,
1292 note: self.note.clone(),
1293 kind: self.kind,
1294 fallback: self.fallback.clone(),
1295 frame_captured_at: self.captured_at,
1296 })
1297 }
1298}