printobserver_core/events.rs
1//! The loop: one normalized event becomes one supervised turn.
2//!
3//! The order is the contract. **The store's event append is the first thing the
4//! loop does**, before the image is written, before the printer is read and
5//! before a supervision turn is run, so that a failure of any of those is
6//! recorded against an event that is already in the history. The one failure
7//! that cannot be covered that way is the append itself: the store is where the
8//! record lives, so when the append fails there is nowhere to record it. The
9//! loop then calls no other port for that event, answers the store's own error
10//! to its caller rather than swallowing it, and goes on to handle the next
11//! event. Losing the alert that way is an availability failure; acting on the
12//! printer with no record behind it would be a safety one, and this crate takes
13//! the first over the second.
14//!
15//! # Context reads gather the print's current state
16//!
17//! A turn reads its print's context by running the command
18//! [`CoreConfig::context_command_for`](crate::CoreConfig::context_command_for)
19//! names, and that command reads it back through [`Supervisor::context`]. Each
20//! read gathers the current printer, job and interventions, even while a turn
21//! is running, so an operator's completed action is visible immediately. The
22//! turn's event and situation still describe what prompted it; a look
23//! ([`crate::look`]) also takes a fresh camera frame.
24//!
25//! # Everything a check decides from is in its prompt
26//!
27//! A turn is handed its print's facts — the context read as it begins, its
28//! events cut to those since the agent last answered
29//! ([`crate::context::turn_facts`]) — and the check's image of the
30//! event's frame ([`crate::check_image`]), so a quiet check needs no command to
31//! decide. Its answer's disposition is its acknowledgement: a turn that
32//! acknowledged nothing by command has its event acknowledged from its answer,
33//! as the agent in that turn's session, with the answer's `why` as the reason.
34//!
35//! # One agent per print
36//!
37//! [`Supervisor::receive_event`] writes an event down and claims its print's
38//! turn, or — when a turn is already running for that print — hands the event
39//! to that turn through the print's inbox ([`crate::inbox`]), where its next
40//! look takes it. [`Supervisor::run_supervision`] runs a claimed turn and then
41//! one more, in the same session, for whatever arrived during it that it never
42//! took. A print that has ended starts no turn at all, and its inbox is
43//! released with whatever was still waiting in it.
44
45use crate::records::{AcknowledgementDisposition, Actor, PrintAction, PrintRecord};
46use crate::store::{EventDraft, HistoryQuery, ImageLookup};
47use printobserver_printer_api::{JobSnapshot, PrinterState};
48use printobserver_supervisor_api::{AgentAssessment, Disposition, SessionPhase};
49use printobserver_supervisor_api::{SupervisionSessionOpenedPayload, TurnRequest, TurnSituation};
50use printobserver_types::EventId;
51use printobserver_types::{EventBody, EventRecord, ImageRef, PrintId, Timestamp};
52use printobserver_vision_api::NormalizedAlert;
53
54use crate::check_image::{ImageUse, captured_at_of};
55use crate::context::{AgentContext, PrintContext, Since, newer_than};
56use crate::error::CoreError;
57use crate::inbox::{AlertCameraFrame, Arrival};
58use crate::kinds::{
59 AgentAssessmentPayload, AgentStopUnactedPayload, PortFailurePayload, PortFailureSite,
60 system_source,
61};
62use crate::listing::{self, ObservedJob, reached_reason};
63use crate::look::Frame;
64use crate::supervisor::Supervisor;
65use crate::watch::{concerns_its_end, noticed_of};
66
67/// One event written down, and the turn it claimed, when it claimed one.
68#[derive(Debug, Clone, PartialEq)]
69pub struct Received {
70 /// The event, as the store holds it.
71 pub event: EventRecord,
72 /// The turn it claimed: absent when it belongs to no print, to a print that
73 /// has ended, or was handed to the turn already running for its print.
74 pub turn: Option<PendingTurn>,
75}
76
77/// What became of one turn.
78enum Supervised {
79 /// It ran, and the printer was not in a terminal state.
80 Ran,
81 /// It ran, and the printer reported this terminal state.
82 Terminal(PrinterState),
83 /// The print had ended by the time the turn held it, so nothing ran.
84 Ended,
85}
86
87/// A turn one event claimed, to be run by [`Supervisor::run_supervision`].
88#[derive(Debug, Clone, PartialEq)]
89pub struct PendingTurn {
90 /// The print the turn is about.
91 print: PrintRecord,
92 /// The event that claimed it.
93 arrival: Arrival,
94 /// What was handed to the print before that event and never taken,
95 /// oldest first.
96 earlier: Vec<Arrival>,
97}
98
99impl PendingTurn {
100 /// The turn one arrival claimed, after what was handed over before it.
101 pub(crate) const fn new(print: PrintRecord, arrival: Arrival, earlier: Vec<Arrival>) -> Self {
102 Self {
103 print,
104 arrival,
105 earlier,
106 }
107 }
108}
109
110/// The print an alert belongs to, and whether resolving it opened one.
111enum Resolution {
112 /// The alert is about no print.
113 NoPrint,
114 /// A print this system already held.
115 Existing(PrintRecord),
116 /// A print opened for it now, which is owed its `print_started`.
117 Opened(PrintRecord),
118}
119
120impl Resolution {
121 /// The print, however it was found.
122 const fn print(&self) -> Option<&PrintRecord> {
123 match self {
124 Self::NoPrint => None,
125 Self::Existing(print) | Self::Opened(print) => Some(print),
126 }
127 }
128}
129
130/// The states a print does not carry on from.
131///
132/// Read off the printer's own reported state rather than inferred from a
133/// notification's wording: the machine is the authority on whether it is still
134/// printing.
135pub const TERMINAL_STATES: [PrinterState; 3] = [
136 PrinterState::Operational,
137 PrinterState::Error,
138 PrinterState::Offline,
139];
140
141/// What an alert's three-panel image says of its first panel's frame: the
142/// printer's camera's, taken as the alert arrived, rather than the detector's
143/// picture the event carries.
144pub const ALERT_CAMERA_FRAME_NOTE: &str = "panel 1 is the printer's camera's own frame, taken as the detector's alert arrived, not the detector's picture";
145
146impl Supervisor {
147 /// Handle one normalized event, from the store's own append to the turn.
148 ///
149 /// # Errors
150 ///
151 /// Returns the store's own error when the **initial event append** fails,
152 /// which is the one failure this loop cannot record anywhere; no other port
153 /// is called for that event, and a later event whose append succeeds is
154 /// handled to completion. Every other port failure this loop reaches is
155 /// recorded against the event rather than answered here — except the
156 /// writes that come after the event is already in the history and are
157 /// owed the spool ledger: a new print's `print_started`, and what a
158 /// filament-change signal the alert relays charges and marks. Those are
159 /// answered as the store's own error, the alert itself already written.
160 pub async fn handle_event(&self, alert: NormalizedAlert) -> Result<EventRecord, CoreError> {
161 let received = self.receive_event(alert).await?;
162 if let Some(turn) = received.turn {
163 self.run_supervision(turn).await?;
164 }
165 Ok(received.event)
166 }
167
168 /// Write one normalized event down, and say whether it needs a turn of
169 /// its own.
170 ///
171 /// The first half of [`Supervisor::handle_event`], for a caller that runs
172 /// the turn somewhere else so that the next event can be written down
173 /// while this one's turn is still running. An event for a print whose turn
174 /// is already running is handed to that turn and answers no turn of its
175 /// own: one agent per print, and what arrives reaches the agent already
176 /// watching it.
177 ///
178 /// # Errors
179 ///
180 /// Exactly as [`Supervisor::handle_event`]'s.
181 pub async fn receive_event(&self, alert: NormalizedAlert) -> Result<Received, CoreError> {
182 let resolution = self.resolve_print(&alert).await?;
183 let draft = EventDraft {
184 print_id: resolution.print().map(|record| record.id),
185 source: alert.source.clone(),
186 received_at: alert.received_at,
187 body: alert.body.clone(),
188 raw: Some(alert.raw.clone()),
189 };
190 let event = self
191 .stores()
192 .events
193 .append_event(draft)
194 .await
195 .map_err(CoreError::Store)?;
196 let print = match resolution {
197 Resolution::NoPrint => return Ok(Received { event, turn: None }),
198 Resolution::Existing(print) => print,
199 // llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
200 Resolution::Opened(print) => {
201 self.record_print_started(print.id, print.file_name.clone(), None, None)
202 .await?;
203 print
204 }
205 };
206 if alert.detection.is_some() {
207 // The detector flagged this print, which its status says from now on.
208 self.note_flagged(print.id);
209 }
210 let (image, frame_captured_at) = self
211 .write_image(&print, &event, alert.image_url.clone())
212 .await
213 .map_or((None, None), |(image, at)| (Some(image), Some(at)));
214 if print.ended_at.is_some() {
215 return Ok(Received { event, turn: None });
216 }
217 if let Some(signal) = alert.signal {
218 self.handle_signal(&print, signal, alert.kind()).await?;
219 }
220 // 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 (image_path, image, frame_captured_at) = self
513 .check_image_for(print, arrival, context.job.as_ref())
514 .await;
515 let facts = crate::context::turn_facts(&context.for_agent(None));
516 let situation = TurnSituation {
517 printer_state,
518 detector_warned: arrival.detection.map(|detection| detection.warning),
519 detector_paused_the_print: arrival
520 .detection
521 .map(|detection| detection.paused_the_print),
522 arrived_while_busy: earlier.into_iter().map(|left| left.event).collect(),
523 noticed: noticed_of(event),
524 frame_captured_at,
525 image,
526 };
527 // The turn's credentials are bound to it from here, and revoked the
528 // moment it returns — whatever it returned — and when this future is
529 // abandoned, because dropping what was opened revokes too.
530 let opened = self.open_turn(print.id, image_path.is_some());
531 self.forget_acknowledged_by_turn(print.id);
532 let running = situation.printer_state == Some(PrinterState::Printing);
533 self.forget_stop_asked(print.id);
534 let access = std::sync::Arc::new(StopAware {
535 inner: opened.access(),
536 print_id: print.id,
537 stops: std::sync::Arc::clone(&self.stopped_by_turn),
538 });
539 let turn = self
540 .agent()
541 .run_turn(
542 TurnRequest {
543 print_id: print.id,
544 event: event.clone(),
545 image_path,
546 context_command: self.config().context_command_for(print.id),
547 facts,
548 situation,
549 },
550 access,
551 )
552 .await;
553 opened.revoke();
554 let acknowledged_by_command = self.forget_acknowledged_by_turn(print.id);
555 let asked_to_stop = self.forget_stop_asked(print.id);
556 drop(guard);
557 match turn {
558 Ok(outcome) => {
559 // An answer of `stop` on a print that was running, from a turn
560 // that asked for no pause or cancel, stopped nothing.
561 let stop_unacted = (running
562 && !asked_to_stop
563 && outcome.assessment.disposition == Disposition::Stop)
564 .then(|| {
565 (
566 outcome.session.session_name.clone(),
567 outcome.assessment.summary.clone(),
568 )
569 });
570 self.record_answered(print.id, event.id, outcome, acknowledged_by_command)
571 .await?;
572 if let Some(said) = stop_unacted {
573 self.record_unacted_stop(print.id, event.id, said).await?;
574 }
575 }
576 Err(error) => {
577 self.record_port_failure(
578 print.id,
579 event.id,
580 PortFailureSite::SupervisionTurn,
581 error.to_string(),
582 )
583 .await;
584 }
585 }
586 // A print already over has nothing a terminal state could close: its
587 // turn on its end ran, and what was handed to it meanwhile is next.
588 Ok(match terminal {
589 Some(state) if !ended => Supervised::Terminal(state),
590 _ => Supervised::Ran,
591 })
592 }
593
594 /// Write down what an answered turn said — the session it opened, its
595 /// assessment — and acknowledge its event from the answer when the turn
596 /// acknowledged nothing by command.
597 async fn record_answered(
598 &self,
599 print_id: PrintId,
600 event_id: EventId,
601 outcome: printobserver_supervisor_api::TurnOutcome,
602 acknowledged_by_command: bool,
603 ) -> Result<(), CoreError> {
604 if outcome.phase == SessionPhase::Created {
605 self.append_system_event(
606 print_id,
607 EventBody::of(&SupervisionSessionOpenedPayload {
608 session_name: outcome.session.session_name.clone(),
609 harness_identity: outcome.session.harness_identity.clone(),
610 })?,
611 )
612 .await?;
613 }
614 let session_name = outcome.session.session_name.clone();
615 self.stores().sessions.put_session(outcome.session).await?;
616 let assessment = outcome.assessment;
617 self.append_system_event(
618 print_id,
619 EventBody::of(&AgentAssessmentPayload {
620 session_name: session_name.clone(),
621 assessment: assessment.clone(),
622 })?,
623 )
624 .await?;
625 if !acknowledged_by_command
626 && let Err(error) = self
627 .acknowledge_from_answer(print_id, event_id, session_name, &assessment)
628 .await
629 {
630 // The turn answered; an acknowledgement that could not be
631 // made is recorded against its event and ends nothing. Only a
632 // store failing mid-turn reaches here, which the real store can
633 // be made to do only by breaking its database under a running
634 // server; the core journey
635 // `an_acknowledgement_the_answer_cannot_make_is_recorded_and_supervision_goes_on`
636 // proves it over a store that fails its history read instead.
637 self.record_port_failure(
638 print_id,
639 event_id,
640 PortFailureSite::SupervisionTurn,
641 format!("the answer's acknowledgement could not be made: {error}"),
642 )
643 .await;
644 }
645 Ok(())
646 }
647
648 /// Write down that the agent answered a running print should stop and
649 /// stopped nothing, when the print is still open: its history is where a
650 /// refused pause is, which is what the person reading it reads.
651 ///
652 /// # Errors
653 ///
654 /// Returns the store's own error when the print or its history could not
655 /// be read or written.
656 async fn record_unacted_stop(
657 &self,
658 print_id: PrintId,
659 event_id: EventId,
660 (session_name, summary): (String, String),
661 ) -> Result<(), CoreError> {
662 let open = self
663 .stores()
664 .prints
665 .print(print_id)
666 .await?
667 .is_some_and(|print| print.ended_at.is_none());
668 if !open {
669 return Ok(());
670 }
671 self.append_system_event(
672 print_id,
673 EventBody::of(&AgentStopUnactedPayload {
674 event_id,
675 session_name,
676 summary,
677 })?,
678 )
679 .await?;
680 Ok(())
681 }
682
683 /// The image a check of one arrival is shown, the line saying what it is,
684 /// and when the frame it shows was captured, made where the job stood in
685 /// the print's own file: none when the arrival carries no frame.
686 ///
687 /// A detector's alert whose camera frame was had is shown that frame's
688 /// three-panel image; where it was not had or not composed, the detector's
689 /// own picture, as any check is shown its frame.
690 async fn check_image_for(
691 &self,
692 print: &PrintRecord,
693 arrival: &Arrival,
694 job: Option<&JobSnapshot>,
695 ) -> (
696 Option<std::path::PathBuf>,
697 Option<String>,
698 Option<Timestamp>,
699 ) {
700 let event = &arrival.event;
701 let Some(reference) = &event.image else {
702 return (None, None, arrival.frame_captured_at);
703 };
704 let plan = self.plan_position(print, job).await;
705 if let AlertCameraFrame::Had { image, captured_at } = &arrival.camera_frame {
706 let shown = self
707 .shown_image_of(
708 image,
709 Some(print.id),
710 *captured_at,
711 ImageUse::Check,
712 plan.clone(),
713 )
714 .await;
715 if let Some(shown) = shown.filter(|shown| shown.composite) {
716 self.note_check_frame(print, job, *captured_at);
717 let note = shown
718 .note
719 .map(|note| format!("{note}; {ALERT_CAMERA_FRAME_NOTE}"));
720 return (Some(shown.path), note, Some(*captured_at));
721 }
722 }
723 let captured_at = captured_at_of(event, arrival.frame_captured_at);
724 self.note_check_frame(print, job, captured_at);
725 let missing = match &arrival.camera_frame {
726 AlertCameraFrame::Missing(why) => Some(why.as_str()),
727 AlertCameraFrame::NotAsked | AlertCameraFrame::Had { .. } => None,
728 };
729 self.shown_image_of(
730 reference,
731 Some(print.id),
732 captured_at,
733 ImageUse::Check,
734 plan,
735 )
736 .await
737 .map_or((None, None, arrival.frame_captured_at), |shown| {
738 let note = match (shown.note, missing) {
739 (Some(note), Some(why)) => Some(format!(
740 "{note}; the detector's own picture, because the camera gave no frame of its own as the alert arrived: {why}"
741 )),
742 (note, _) => note,
743 };
744 (Some(shown.path), note, arrival.frame_captured_at)
745 })
746 }
747
748 /// Note the frame a check was shown, so the plan's rise can later be
749 /// measured from it, as from a look's.
750 ///
751 /// A check's frame — an alert's as much as an observation's — is one the
752 /// agent was shown. Measured only from observations and looks, a check
753 /// after an alert, a pause and a person's resume was told the rise since
754 /// the print's first frame hours before, and paused a print growing as
755 /// planned for not having risen that far (`warning-after-resume`).
756 fn note_check_frame(
757 &self,
758 print: &PrintRecord,
759 job: Option<&JobSnapshot>,
760 captured_at: Timestamp,
761 ) {
762 if let Some(job) = job
763 && print.ended_at.is_none()
764 && job.file_name.is_some()
765 && job.file_name == print.file_name
766 && let Some(position) = job.file_position_bytes
767 {
768 self.gcode_indexes()
769 .note_look(print.id, captured_at, position, self.clock().now());
770 }
771 }
772
773 /// Note that the running turn on one print asked to pause or cancel it,
774 /// whatever policy makes of the request: what an answer of `stop` is held
775 /// to.
776 pub(crate) fn note_stop_asked(&self, print_id: PrintId, action: &PrintAction) {
777 if action.actor().class() == crate::records::ActorClass::Agent
778 && matches!(
779 action,
780 PrintAction::Pause { .. } | PrintAction::Cancel { .. }
781 )
782 {
783 self.stopped_by_turn
784 .lock()
785 .unwrap_or_else(std::sync::PoisonError::into_inner)
786 .insert(print_id);
787 }
788 }
789
790 /// Forget whether a turn on one print asked to stop it, answering whether
791 /// one had.
792 fn forget_stop_asked(&self, print_id: PrintId) -> bool {
793 self.stopped_by_turn
794 .lock()
795 .unwrap_or_else(std::sync::PoisonError::into_inner)
796 .remove(&print_id)
797 }
798
799 /// Note that the running turn on one print acknowledged its event by
800 /// command.
801 pub(crate) fn note_acknowledged_by_turn(&self, print_id: PrintId) {
802 self.acknowledged_by_turn
803 .lock()
804 .unwrap_or_else(std::sync::PoisonError::into_inner)
805 .insert(print_id);
806 }
807
808 /// Forget whether a turn on one print acknowledged by command, answering
809 /// whether one had.
810 fn forget_acknowledged_by_turn(&self, print_id: PrintId) -> bool {
811 self.acknowledged_by_turn
812 .lock()
813 .unwrap_or_else(std::sync::PoisonError::into_inner)
814 .remove(&print_id)
815 }
816
817 /// Acknowledge the event a turn was about from the turn's answer, as the
818 /// agent in the session it answered in: the same request, through the same
819 /// policy, as the agent's own command would have made.
820 ///
821 /// A print that has ended by the time the turn answers is not
822 /// acknowledged: its record is closed, and nothing is left to carry on or
823 /// stop.
824 ///
825 /// # Errors
826 ///
827 /// Returns the store's own error when the request could not be recorded. A
828 /// refusal by policy is recorded with the request and is not an error.
829 async fn acknowledge_from_answer(
830 &self,
831 print_id: PrintId,
832 event_id: EventId,
833 session_name: String,
834 assessment: &AgentAssessment,
835 ) -> Result<(), CoreError> {
836 let open = self
837 .stores()
838 .prints
839 .print(print_id)
840 .await?
841 .is_some_and(|print| print.ended_at.is_none());
842 if !open {
843 return Ok(());
844 }
845 let disposition = match assessment.disposition {
846 Disposition::Continue => AcknowledgementDisposition::Continue,
847 Disposition::Watch => AcknowledgementDisposition::Watch,
848 Disposition::Stop => AcknowledgementDisposition::Stop,
849 };
850 self.request_action(
851 print_id,
852 PrintAction::AcknowledgeFailure {
853 event_id,
854 disposition,
855 reason: assessment.why.clone(),
856 actor: Actor::Agent { session_name },
857 },
858 )
859 .await?;
860 Ok(())
861 }
862
863 /// Gather the current context of one print, including while its
864 /// supervision turn is running.
865 ///
866 /// # Errors
867 ///
868 /// Returns [`CoreError::NoSuchPrint`] when nothing is held under that
869 /// identifier, and the store's own error when the context could not be
870 /// read.
871 pub async fn context(&self, print_id: PrintId) -> Result<PrintContext, CoreError> {
872 let print = self
873 .stores()
874 .prints
875 .print(print_id)
876 .await?
877 .ok_or(CoreError::NoSuchPrint { print_id })?;
878 self.gather_context(&print, None).await
879 }
880
881 /// What a supervision turn reads of one print's context, carrying only the
882 /// events newer than `since` when it names one.
883 ///
884 /// Every event newer than the one named is carried, however many the
885 /// recent window would hold: the window is widened to the history's
886 /// largest page when the event is older than it.
887 ///
888 /// # Errors
889 ///
890 /// Answers [`CoreError::NoSuchPrint`] and the store's own error as
891 /// [`Self::context`] does, and [`StoreError::NotFound`] when `since` names
892 /// none of the print's latest [`MAX_HISTORY_LIMIT`] events.
893 ///
894 /// [`StoreError::NotFound`]: crate::store::StoreError::NotFound
895 /// [`MAX_HISTORY_LIMIT`]: crate::store::MAX_HISTORY_LIMIT
896 pub async fn agent_context(
897 &self,
898 print_id: PrintId,
899 since: Option<printobserver_types::EventId>,
900 ) -> Result<AgentContext, CoreError> {
901 let context = self.context(print_id).await?;
902 let Some(event) = since else {
903 return Ok(context.for_agent(None));
904 };
905 let wider;
906 let newer = if let Some(newer) = newer_than(&context.recent_events, event) {
907 newer
908 } else {
909 wider = self
910 .recent_events_of(&context.print, crate::store::MAX_HISTORY_LIMIT)
911 .await?;
912 newer_than(&wider, event).ok_or_else(|| {
913 CoreError::Store(crate::store::StoreError::NotFound {
914 what: format!(
915 "event {event} among print {print_id}'s latest {} events",
916 crate::store::MAX_HISTORY_LIMIT
917 ),
918 })
919 })?
920 };
921 let agent = context.for_agent(Some(Since { event, newer }));
922 Ok(agent)
923 }
924
925 /// Read one print's whole context, recording a printer read that fails.
926 ///
927 /// A read failure is recorded against the event being handled when there is
928 /// one; a context read that no event prompted has nowhere to record it and
929 /// carries the absence in the context itself, which is what an absent
930 /// `printer` or `job` means.
931 ///
932 /// The job read settles the open prints exactly as the listing's does
933 /// ([`crate::listing`]) before the rest of the context is read: a job found
934 /// over closes the print, a later job of its file closes it as replaced,
935 /// and a job found to be its own is recorded on it — so the context
936 /// answered is the print as it now stands. Within a turn the turn holds the
937 /// print, and that turn closes it.
938 async fn gather_context(
939 &self,
940 print: &PrintRecord,
941 event_id: Option<printobserver_types::EventId>,
942 ) -> Result<PrintContext, CoreError> {
943 let printer = match self.read_snapshot().await {
944 Ok(snapshot) => Some(snapshot),
945 Err(error) => {
946 self.record_read_failure(
947 print.id,
948 event_id,
949 PortFailureSite::PrinterSnapshot,
950 error.to_string(),
951 )
952 .await;
953 None
954 }
955 };
956 // The job is read and settled under one hold on resolution, as the
957 // listing's is. A start holds it from the read that chooses its print
958 // until the printer has been asked to start, so a job read before that
959 // hold and settled after it would be the idle machine the start has
960 // since moved, and would close the print the start had just opened.
961 let resolving = self.resolving().await;
962 let job = match self.read_job().await {
963 Ok(job) => Some(job),
964 Err(error) => {
965 self.record_read_failure(
966 print.id,
967 event_id,
968 PortFailureSite::PrinterJob,
969 error.to_string(),
970 )
971 .await;
972 None
973 }
974 };
975 let print = match &job {
976 Some(job) if print.ended_at.is_none() => self.settle_for_context(print, job).await?,
977 _ => print.clone(),
978 };
979 drop(resolving);
980 let print = &print;
981 let manifest = self.stores().prints.manifest(print.id).await?;
982 let bounds = self.bounds_for(Some(print), print.id).await?;
983 let interventions = self.stores().actions.active_interventions(print.id).await?;
984 let recent_events = self
985 .recent_events_of(print, self.config().recent_events)
986 .await?;
987 let latest_image = recent_events.iter().find_map(|record| record.image.clone());
988 let slicer = self
989 .slicer_plan(print, job.as_ref(), &interventions)
990 .await?;
991 Ok(PrintContext {
992 print: print.clone(),
993 printer,
994 job,
995 manifest,
996 bounds: bounds.effective,
997 interventions,
998 recent_events,
999 latest_image,
1000 detector: self.detector_health_for(print.id),
1001 slicer,
1002 })
1003 }
1004
1005 /// One print's most recent events, newest first: its own, and what the
1006 /// printer watch recorded of the machine since it opened, which is the
1007 /// printer's and carries no print.
1008 async fn recent_events_of(
1009 &self,
1010 print: &PrintRecord,
1011 limit: u32,
1012 ) -> Result<Vec<EventRecord>, CoreError> {
1013 let mut events = self
1014 .stores()
1015 .events
1016 .history(HistoryQuery {
1017 print_id: print.id,
1018 kinds: Vec::new(),
1019 since: None,
1020 until: None,
1021 limit: Some(limit),
1022 })
1023 .await?;
1024 let kinds = crate::watch::PRINTER_WATCH_KINDS
1025 .iter()
1026 .filter_map(|kind| printobserver_types::EventKind::new(*kind).ok())
1027 .collect();
1028 let watched = self
1029 .stores()
1030 .timeline
1031 .timeline(crate::store::TimelineQuery {
1032 kinds,
1033 since: Some(print.opened_at),
1034 until: None,
1035 spool_id: None,
1036 before: None,
1037 limit: Some(limit),
1038 })
1039 .await?;
1040 events.extend(watched.into_iter().filter(|event| event.print_id.is_none()));
1041 events.sort_by_key(|event| core::cmp::Reverse((event.received_at, event.id)));
1042 events.truncate(usize::try_from(limit).unwrap_or(usize::MAX));
1043 Ok(events)
1044 }
1045
1046 /// Where one image's bytes are, when the store still has them.
1047 pub(crate) async fn image_path(&self, image: &ImageRef) -> Option<std::path::PathBuf> {
1048 match self.stores().images.image(image.id).await {
1049 Ok(ImageLookup::Found { path, .. }) => Some(path),
1050 _ => None,
1051 }
1052 }
1053
1054 /// Settle the open prints against the job a context read found, and
1055 /// answer the print the context is about as that left it.
1056 ///
1057 /// The caller holds resolution from before it read that job.
1058 async fn settle_for_context(
1059 &self,
1060 print: &PrintRecord,
1061 job: &JobSnapshot,
1062 ) -> Result<PrintRecord, CoreError> {
1063 let observed = ObservedJob {
1064 job: job.clone(),
1065 observed_at: self.clock().now(),
1066 };
1067 let settled = self.settle_open_prints(&observed).await?;
1068 match settled.running {
1069 Some(running) if running.id == print.id => Ok(running),
1070 _ if settled.closed.contains(&print.id) => Ok(self
1071 .stores()
1072 .prints
1073 .print(print.id)
1074 .await?
1075 .unwrap_or_else(|| print.clone())),
1076 _ => Ok(print.clone()),
1077 }
1078 }
1079
1080 /// End the print, expire what it had running, and close its session.
1081 ///
1082 /// The interventions are expired **before** the print is ended, because a
1083 /// restoration is an action against the print and a print that has already
1084 /// ended is one no action may be taken against.
1085 ///
1086 /// The caller holds the print's turn, so no turn is acting on it while it
1087 /// closes. Answers whether this closed it: a print already ended — by
1088 /// another read, or by the turn that held it — is left as it ended.
1089 ///
1090 /// The print's filament is settled after its interventions are expired
1091 /// and before it is ended ([`crate::accounting`]): a crash between the two
1092 /// leaves a settled, open print, which the next close-out only ends.
1093 /// `closing_job` is the job read that found the print over, when there
1094 /// was one; without it the settlement reads the job itself.
1095 pub(crate) async fn close_out_print(
1096 &self,
1097 print_id: PrintId,
1098 state: &PrinterState,
1099 reason: &str,
1100 closing_job: Option<&JobSnapshot>,
1101 ) -> Result<bool, CoreError> {
1102 let print = match self.stores().prints.print(print_id).await? {
1103 Some(print) if print.ended_at.is_none() => print,
1104 _ => return Ok(false),
1105 };
1106 self.forget_detector_pause(print_id);
1107 self.expire_all_active(print_id).await?;
1108 self.settle_filament(&print, state, reason, closing_job)
1109 .await?;
1110 self.stores()
1111 .prints
1112 .end_print(
1113 print_id,
1114 state.clone(),
1115 self.clock().now(),
1116 reason.to_owned(),
1117 )
1118 .await?;
1119 self.close_session_of(print_id, reason).await?;
1120 self.drop_gcode_spool(print_id);
1121 self.forget_planned_changes(print_id);
1122 self.follow_up_end(print_id).await;
1123 Ok(true)
1124 }
1125
1126 /// Append one event this system raised itself.
1127 pub(crate) async fn append_system_event(
1128 &self,
1129 print_id: PrintId,
1130 body: EventBody,
1131 ) -> Result<EventRecord, CoreError> {
1132 self.append_system_event_to(Some(print_id), body).await
1133 }
1134
1135 /// Append one event the supervisor itself raised, to a print's history or
1136 /// to the printer's when it names none.
1137 pub(crate) async fn append_system_event_to(
1138 &self,
1139 print_id: Option<PrintId>,
1140 body: EventBody,
1141 ) -> Result<EventRecord, CoreError> {
1142 Ok(self
1143 .stores()
1144 .events
1145 .append_event(EventDraft {
1146 print_id,
1147 source: system_source(),
1148 received_at: self.clock().now(),
1149 body,
1150 raw: None,
1151 })
1152 .await?)
1153 }
1154
1155 /// Record a printer read that failed, when an event prompted the read.
1156 async fn record_read_failure(
1157 &self,
1158 print_id: PrintId,
1159 event_id: Option<printobserver_types::EventId>,
1160 site: PortFailureSite,
1161 detail: String,
1162 ) {
1163 if let Some(event_id) = event_id {
1164 self.record_port_failure(print_id, event_id, site, detail)
1165 .await;
1166 }
1167 }
1168
1169 /// Record that a port failed while one event was being handled.
1170 ///
1171 /// The event is already in the history by the time any of these sites is
1172 /// reached, which is what gives the failure somewhere to be recorded.
1173 /// Nothing is answered to the caller: the loop survives this and goes on.
1174 pub(crate) async fn record_port_failure(
1175 &self,
1176 print_id: PrintId,
1177 event_id: printobserver_types::EventId,
1178 site: PortFailureSite,
1179 detail: String,
1180 ) {
1181 self.record_port_failure_to(Some(print_id), event_id, site, detail)
1182 .await;
1183 }
1184
1185 /// Record that a port failed while one event was being handled, in the
1186 /// history that event is in: a print's, or the printer's when it names
1187 /// none.
1188 pub(crate) async fn record_port_failure_to(
1189 &self,
1190 print_id: Option<PrintId>,
1191 event_id: printobserver_types::EventId,
1192 site: PortFailureSite,
1193 detail: String,
1194 ) {
1195 // A record that will not render is dropped exactly as one the store
1196 // refuses is: the failure it was about has already been answered, and
1197 // the loop survives not having written it down.
1198 let Ok(body) = EventBody::of(&PortFailurePayload {
1199 event_id,
1200 site,
1201 detail,
1202 }) else {
1203 return;
1204 };
1205 let _ = self.append_system_event_to(print_id, body).await;
1206 }
1207}
1208
1209/// One turn's access as its port is handed it, saying too whether the turn
1210/// has asked for its print to be paused or cancelled.
1211struct StopAware {
1212 /// The turn's own issuer.
1213 inner: std::sync::Arc<dyn printobserver_supervisor_api::TurnAccess>,
1214 /// The print the turn is about.
1215 print_id: PrintId,
1216 /// The prints whose running turn has asked to stop them.
1217 stops: std::sync::Arc<std::sync::Mutex<std::collections::BTreeSet<PrintId>>>,
1218}
1219
1220impl printobserver_supervisor_api::TurnAccess for StopAware {
1221 fn issue(
1222 &self,
1223 session: &printobserver_supervisor_api::TurnSession,
1224 ) -> Result<printobserver_supervisor_api::TurnPass, printobserver_supervisor_api::SupervisorError>
1225 {
1226 self.inner.issue(session)
1227 }
1228
1229 fn asked_to_stop(&self) -> bool {
1230 self.stops
1231 .lock()
1232 .unwrap_or_else(std::sync::PoisonError::into_inner)
1233 .contains(&self.print_id)
1234 }
1235}