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