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//! # The context a turn reads is the one the loop collected
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`]. While
20//! a turn is running, that call answers the context the loop collected for the
21//! event that prompted it rather than a fresh read: what the agent reasons
22//! about is the state the event was handled at, not whatever the machine has
23//! drifted to since. A look ([`crate::look`]) is how it sees the machine as it
24//! is now.
25//!
26//! # One agent per print
27//!
28//! [`Supervisor::receive_event`] writes an event down and claims its print's
29//! turn, or — when a turn is already running for that print — hands the event
30//! to that turn through the print's inbox ([`crate::inbox`]), where its next
31//! look takes it. [`Supervisor::run_supervision`] runs a claimed turn and then
32//! one more, in the same session, for whatever arrived during it that it never
33//! took. A print that has ended starts no turn at all, and its inbox is
34//! released with whatever was still waiting in it.
35
36use crate::records::PrintRecord;
37use crate::store::{EventDraft, HistoryQuery, ImageLookup};
38use printobserver_printer_api::{JobSnapshot, PrinterState};
39use printobserver_supervisor_api::SessionPhase;
40use printobserver_supervisor_api::{
41 SupervisionSessionClosedPayload, SupervisionSessionOpenedPayload, TurnRequest, TurnSituation,
42};
43use printobserver_types::{EventBody, EventRecord, ImageRef, PrintId};
44use printobserver_vision_api::NormalizedAlert;
45
46use crate::context::PrintContext;
47use crate::error::CoreError;
48use crate::inbox::Arrival;
49use crate::kinds::{AgentAssessmentPayload, PortFailurePayload, PortFailureSite, system_source};
50use crate::listing::{self, ObservedJob, reached_reason};
51use crate::supervisor::Supervisor;
52
53/// One event written down, and the turn it claimed, when it claimed one.
54#[derive(Debug, Clone, PartialEq)]
55pub struct Received {
56 /// The event, as the store holds it.
57 pub event: EventRecord,
58 /// The turn it claimed: absent when it belongs to no print, to a print that
59 /// has ended, or was handed to the turn already running for its print.
60 pub turn: Option<PendingTurn>,
61}
62
63/// What became of one turn.
64enum Supervised {
65 /// It ran, and the printer was not in a terminal state.
66 Ran,
67 /// It ran, and the printer reported this terminal state.
68 Terminal(PrinterState),
69 /// The print had ended by the time the turn held it, so nothing ran.
70 Ended,
71}
72
73/// A turn one event claimed, to be run by [`Supervisor::run_supervision`].
74#[derive(Debug, Clone, PartialEq)]
75pub struct PendingTurn {
76 /// The print the turn is about.
77 print: PrintRecord,
78 /// The event that claimed it.
79 arrival: Arrival,
80 /// What was handed to the print before that event and never taken,
81 /// oldest first.
82 earlier: Vec<Arrival>,
83}
84
85impl PendingTurn {
86 /// The turn one arrival claimed, after what was handed over before it.
87 pub(crate) const fn new(print: PrintRecord, arrival: Arrival, earlier: Vec<Arrival>) -> Self {
88 Self {
89 print,
90 arrival,
91 earlier,
92 }
93 }
94}
95
96/// One printer state in the printer contract's own spelling.
97fn state_name(state: &PrinterState) -> Option<String> {
98 printobserver_types::serde_json::to_value(state)
99 .ok()
100 .and_then(|value| value.as_str().map(str::to_owned))
101}
102
103/// The print an alert belongs to, and whether resolving it opened one.
104enum Resolution {
105 /// The alert is about no print.
106 NoPrint,
107 /// A print this system already held.
108 Existing(PrintRecord),
109 /// A print opened for it now, which is owed its `print_started`.
110 Opened(PrintRecord),
111}
112
113impl Resolution {
114 /// The print, however it was found.
115 const fn print(&self) -> Option<&PrintRecord> {
116 match self {
117 Self::NoPrint => None,
118 Self::Existing(print) | Self::Opened(print) => Some(print),
119 }
120 }
121}
122
123/// The states a print does not carry on from.
124///
125/// Read off the printer's own reported state rather than inferred from a
126/// notification's wording: the machine is the authority on whether it is still
127/// printing.
128pub const TERMINAL_STATES: [PrinterState; 3] = [
129 PrinterState::Operational,
130 PrinterState::Error,
131 PrinterState::Offline,
132];
133
134impl Supervisor {
135 /// Handle one normalized event, from the store's own append to the turn.
136 ///
137 /// # Errors
138 ///
139 /// Returns the store's own error when the **initial event append** fails,
140 /// which is the one failure this loop cannot record anywhere; no other port
141 /// is called for that event, and a later event whose append succeeds is
142 /// handled to completion. Every other port failure this loop reaches is
143 /// recorded against the event rather than answered here — except the
144 /// writes that come after the event is already in the history and are
145 /// owed the spool ledger: a new print's `print_started`, and what a
146 /// filament-change signal the alert relays charges and marks. Those are
147 /// answered as the store's own error, the alert itself already written.
148 pub async fn handle_event(&self, alert: NormalizedAlert) -> Result<EventRecord, CoreError> {
149 let received = self.receive_event(alert).await?;
150 if let Some(turn) = received.turn {
151 self.run_supervision(turn).await?;
152 }
153 Ok(received.event)
154 }
155
156 /// Write one normalized event down, and say whether it needs a turn of
157 /// its own.
158 ///
159 /// The first half of [`Supervisor::handle_event`], for a caller that runs
160 /// the turn somewhere else so that the next event can be written down
161 /// while this one's turn is still running. An event for a print whose turn
162 /// is already running is handed to that turn and answers no turn of its
163 /// own: one agent per print, and what arrives reaches the agent already
164 /// watching it.
165 ///
166 /// # Errors
167 ///
168 /// Exactly as [`Supervisor::handle_event`]'s.
169 pub async fn receive_event(&self, alert: NormalizedAlert) -> Result<Received, CoreError> {
170 let resolution = self.resolve_print(&alert).await?;
171 let draft = EventDraft {
172 print_id: resolution.print().map(|record| record.id),
173 source: alert.source.clone(),
174 received_at: alert.received_at,
175 body: alert.body.clone(),
176 raw: Some(alert.raw.clone()),
177 };
178 let event = self
179 .stores()
180 .events
181 .append_event(draft)
182 .await
183 .map_err(CoreError::Store)?;
184 let print = match resolution {
185 Resolution::NoPrint => return Ok(Received { event, turn: None }),
186 Resolution::Existing(print) => print,
187 // llmlint: ignore[changed_behavior_has_e2e] suppressions.toml has the reason.
188 Resolution::Opened(print) => {
189 self.record_print_started(print.id, print.file_name.clone(), None, None)
190 .await?;
191 print
192 }
193 };
194 let image = self
195 .write_image(&print, &event, alert.image_url.clone())
196 .await;
197 if print.ended_at.is_some() {
198 return Ok(Received { event, turn: None });
199 }
200 if let Some(signal) = alert.signal {
201 self.handle_signal(&print, signal, alert.kind()).await?;
202 }
203 let mut carried = event.clone();
204 carried.image = image.or(carried.image);
205 if let Some(detection) = alert.detection
206 && detection.paused_the_print
207 {
208 self.note_detector_pause(print.id, event.id, detection);
209 }
210 let arrival = Arrival {
211 event: carried,
212 detection: alert.detection,
213 };
214 let turn = self
215 .inboxes()
216 .claim_or_hand_over(print.id, arrival.clone())
217 .then(|| PendingTurn::new(print, arrival, Vec::new()));
218 Ok(Received { event, turn })
219 }
220
221 /// Run the turn one received event claimed, and one more for whatever
222 /// arrived during it that it never took, until nothing is left.
223 ///
224 /// The detector's pause the agent adjusted the print under is resumed as
225 /// each turn ends, when its grace has not already resumed it.
226 ///
227 /// # Errors
228 ///
229 /// Returns the store's own error when a turn's outcome could not be
230 /// recorded; a turn that fails is recorded rather than answered.
231 pub async fn run_supervision(&self, turn: PendingTurn) -> Result<(), CoreError> {
232 let PendingTurn {
233 print,
234 arrival,
235 earlier,
236 } = turn;
237 let mut next = Some((arrival, earlier));
238 while let Some((arrival, earlier)) = next {
239 let supervised = self.supervise(&print, &arrival, earlier).await;
240 if !matches!(supervised, Ok(Supervised::Ended)) {
241 self.resume_adjusted_detector_pause(print.id).await;
242 }
243 match supervised {
244 Ok(Supervised::Ran) => {}
245 Ok(Supervised::Ended) => {
246 self.inboxes().release(print.id);
247 self.forget_detector_pause(print.id);
248 return Ok(());
249 }
250 Ok(Supervised::Terminal(state)) => {
251 self.inboxes().release(print.id);
252 let _turn = self.turns().acquire(print.id).await;
253 return self
254 .close_out_print(print.id, &state, &reached_reason(&state), None)
255 .await
256 .map(drop);
257 }
258 Err(error) => {
259 self.inboxes().release(print.id);
260 return Err(error);
261 }
262 }
263 next = self
264 .inboxes()
265 .next_or_release(print.id)
266 .and_then(|mut left| left.pop().map(|latest| (latest, left)));
267 }
268 Ok(())
269 }
270
271 /// The print an alert belongs to, opened if this system has not seen it.
272 ///
273 /// Correlated on the provider's own identifier the alert carries beside its
274 /// body, and never on the body by kind: which provider raised the alert is
275 /// the adapter's business, and this loop reads nothing an adapter declares.
276 ///
277 /// In order: the print already carrying that identifier; otherwise the most
278 /// recently opened print with no end recorded, no provider identifier, the
279 /// alert's own file name and a job the alert's start may be
280 /// ([`listing::may_have_started_it`]), which is a job somebody found before
281 /// the provider reported on it and which takes the identifier here;
282 /// otherwise a print opened for it. The file name is the one key the two
283 /// sides share — the provider names the job by the file the printer
284 /// reported, and the printer names it by that same file — and the start is
285 /// what tells that job from a later one of the same file.
286 ///
287 /// Nothing here reads the printer: an alert is written down before anything
288 /// is asked of a port, and a print a later job replaced is closed by the
289 /// next read that finds that job, not by an alert about it.
290 ///
291 /// Answers whether this opened it, so that the print's `print_started` is
292 /// written once the alert itself has been.
293 async fn resolve_print(&self, alert: &NormalizedAlert) -> Result<Resolution, CoreError> {
294 let Some(provider_print) = &alert.print else {
295 return Ok(Resolution::NoPrint);
296 };
297 let _resolving = self.resolving().await;
298 if let Some(found) = self
299 .stores()
300 .prints
301 .print_by_provider_id(provider_print.id)
302 .await?
303 {
304 return Ok(Resolution::Existing(found));
305 }
306 if let Some(file_name) = &provider_print.file_name {
307 let unattached = self
308 .stores()
309 .prints
310 .open_prints()
311 .await?
312 .into_iter()
313 .find(|open| {
314 open.provider_print_id.is_none()
315 && open.file_name.as_ref() == Some(file_name)
316 && listing::may_have_started_it(open, provider_print.started_at)
317 });
318 if let Some(found) = unattached {
319 let attached = self
320 .stores()
321 .prints
322 .attach_obico_print(found.id, provider_print.id)
323 .await?;
324 return Ok(Resolution::Existing(attached));
325 }
326 }
327 let opened = self
328 .stores()
329 .prints
330 .open_print(Some(provider_print.id), provider_print.file_name.clone())
331 .await?;
332 Ok(Resolution::Opened(opened))
333 }
334
335 /// Fetch and store the image an alert names, recording either failure.
336 async fn write_image(
337 &self,
338 print: &PrintRecord,
339 event: &EventRecord,
340 image_url: Option<String>,
341 ) -> Option<ImageRef> {
342 let source_url = image_url?;
343 let fetched = match self.vision().fetch_image(source_url.clone()).await {
344 Ok(fetched) => fetched,
345 Err(error) => {
346 self.record_port_failure(
347 print.id,
348 event.id,
349 PortFailureSite::ImageWrite,
350 error.to_string(),
351 )
352 .await;
353 return None;
354 }
355 };
356 match self
357 .stores()
358 .images
359 .put_image(
360 print.id,
361 event.id,
362 Some(source_url),
363 fetched.content_type,
364 fetched.bytes,
365 )
366 .await
367 {
368 Ok(record) => Some(ImageRef {
369 id: record.id,
370 sha256: record.sha256,
371 }),
372 Err(error) => {
373 self.record_port_failure(
374 print.id,
375 event.id,
376 PortFailureSite::ImageWrite,
377 error.to_string(),
378 )
379 .await;
380 None
381 }
382 }
383 }
384
385 /// Collect the context, run one turn on it, and persist what it answered.
386 ///
387 /// `earlier` is what arrived for the print before `arrival` while an
388 /// earlier turn was running and that turn never took, oldest first.
389 ///
390 /// Answers the terminal state the printer reported, when it reported one,
391 /// and runs nothing for a print that ended — at a read that found its job
392 /// over — before this turn came to hold it.
393 async fn supervise(
394 &self,
395 print: &PrintRecord,
396 arrival: &Arrival,
397 earlier: Vec<Arrival>,
398 ) -> Result<Supervised, CoreError> {
399 let event = &arrival.event;
400 let guard = self.turns().acquire(print.id).await;
401 if self
402 .stores()
403 .prints
404 .print(print.id)
405 .await?
406 .is_none_or(|held| held.ended_at.is_some())
407 {
408 return Ok(Supervised::Ended);
409 }
410 let context = self.gather_context(print, Some(event.id)).await?;
411 let printer_state = context
412 .printer
413 .as_ref()
414 .map(|snapshot| snapshot.connection.clone());
415 let terminal = printer_state
416 .clone()
417 .filter(|state| TERMINAL_STATES.contains(state));
418 let image_path = match &event.image {
419 Some(reference) => self.image_path(reference).await,
420 None => None,
421 };
422 let situation = TurnSituation {
423 printer_state: printer_state.as_ref().and_then(state_name),
424 detector_warned: arrival.detection.map(|detection| detection.warning),
425 detector_paused_the_print: arrival
426 .detection
427 .map(|detection| detection.paused_the_print),
428 arrived_while_busy: earlier.into_iter().map(|left| left.event).collect(),
429 };
430 self.hold_context(print.id, context);
431 // The turn's credentials are bound to it from here, and revoked the
432 // moment it returns — whatever it returned — and when this future is
433 // abandoned, because dropping what was opened revokes too.
434 let opened = self.open_turn(print.id);
435 let turn = self
436 .agent()
437 .run_turn(
438 TurnRequest {
439 print_id: print.id,
440 event: event.clone(),
441 image_path,
442 context_command: self.config().context_command_for(print.id),
443 situation,
444 },
445 opened.access(),
446 )
447 .await;
448 opened.revoke();
449 self.drop_context(print.id);
450 drop(guard);
451 match turn {
452 Ok(outcome) => {
453 if outcome.phase == SessionPhase::Created {
454 self.append_system_event(
455 print.id,
456 EventBody::of(&SupervisionSessionOpenedPayload {
457 session_name: outcome.session.session_name.clone(),
458 harness_identity: outcome.session.harness_identity.clone(),
459 })?,
460 )
461 .await?;
462 }
463 let session_name = outcome.session.session_name.clone();
464 self.stores().sessions.put_session(outcome.session).await?;
465 self.append_system_event(
466 print.id,
467 EventBody::of(&AgentAssessmentPayload {
468 session_name,
469 assessment: outcome.assessment,
470 })?,
471 )
472 .await?;
473 }
474 Err(error) => {
475 self.record_port_failure(
476 print.id,
477 event.id,
478 PortFailureSite::SupervisionTurn,
479 error.to_string(),
480 )
481 .await;
482 }
483 }
484 Ok(terminal.map_or(Supervised::Ran, Supervised::Terminal))
485 }
486
487 /// Everything a supervision turn is given about one print.
488 ///
489 /// While a turn is running for the print, this answers the context the loop
490 /// collected for the event that prompted it.
491 ///
492 /// # Errors
493 ///
494 /// Returns [`CoreError::NoSuchPrint`] when nothing is held under that
495 /// identifier, and the store's own error when the context could not be
496 /// read.
497 pub async fn context(&self, print_id: PrintId) -> Result<PrintContext, CoreError> {
498 if let Some(held) = self.held_context(print_id) {
499 return Ok(held);
500 }
501 let print = self
502 .stores()
503 .prints
504 .print(print_id)
505 .await?
506 .ok_or(CoreError::NoSuchPrint { print_id })?;
507 self.gather_context(&print, None).await
508 }
509
510 /// Read one print's whole context, recording a printer read that fails.
511 ///
512 /// A read failure is recorded against the event being handled when there is
513 /// one; a context read that no event prompted has nowhere to record it and
514 /// carries the absence in the context itself, which is what an absent
515 /// `printer` or `job` means.
516 ///
517 /// The job read settles the open prints exactly as the listing's does
518 /// ([`crate::listing`]) before the rest of the context is read: a job found
519 /// over closes the print, a later job of its file closes it as replaced,
520 /// and a job found to be its own is recorded on it — so the context
521 /// answered is the print as it now stands. Within a turn the turn holds the
522 /// print, and that turn closes it.
523 async fn gather_context(
524 &self,
525 print: &PrintRecord,
526 event_id: Option<printobserver_types::EventId>,
527 ) -> Result<PrintContext, CoreError> {
528 let printer = match self.read_snapshot().await {
529 Ok(snapshot) => Some(snapshot),
530 Err(error) => {
531 self.record_read_failure(
532 print.id,
533 event_id,
534 PortFailureSite::PrinterSnapshot,
535 error.to_string(),
536 )
537 .await;
538 None
539 }
540 };
541 // The job is read and settled under one hold on resolution, as the
542 // listing's is. A start holds it from the read that chooses its print
543 // until the printer has been asked to start, so a job read before that
544 // hold and settled after it would be the idle machine the start has
545 // since moved, and would close the print the start had just opened.
546 let resolving = self.resolving().await;
547 let job = match self.read_job().await {
548 Ok(job) => Some(job),
549 Err(error) => {
550 self.record_read_failure(
551 print.id,
552 event_id,
553 PortFailureSite::PrinterJob,
554 error.to_string(),
555 )
556 .await;
557 None
558 }
559 };
560 let print = match &job {
561 Some(job) if print.ended_at.is_none() => self.settle_for_context(print, job).await?,
562 _ => print.clone(),
563 };
564 drop(resolving);
565 let print = &print;
566 let manifest = self.stores().prints.manifest(print.id).await?;
567 let bounds = self.bounds_for(Some(print), print.id).await?;
568 let interventions = self.stores().actions.active_interventions(print.id).await?;
569 let recent_events = self
570 .stores()
571 .events
572 .history(HistoryQuery {
573 print_id: print.id,
574 kinds: Vec::new(),
575 since: None,
576 until: None,
577 limit: Some(self.config().recent_events),
578 })
579 .await?;
580 let latest_image = recent_events.iter().find_map(|record| record.image.clone());
581 Ok(PrintContext {
582 print: print.clone(),
583 printer,
584 job,
585 manifest,
586 bounds: bounds.effective,
587 interventions,
588 recent_events,
589 latest_image,
590 })
591 }
592
593 /// Where one image's bytes are, when the store still has them.
594 pub(crate) async fn image_path(&self, image: &ImageRef) -> Option<std::path::PathBuf> {
595 match self.stores().images.image(image.id).await {
596 Ok(ImageLookup::Found { path, .. }) => Some(path),
597 _ => None,
598 }
599 }
600
601 /// Settle the open prints against the job a context read found, and
602 /// answer the print the context is about as that left it.
603 ///
604 /// The caller holds resolution from before it read that job.
605 async fn settle_for_context(
606 &self,
607 print: &PrintRecord,
608 job: &JobSnapshot,
609 ) -> Result<PrintRecord, CoreError> {
610 let observed = ObservedJob {
611 job: job.clone(),
612 observed_at: self.clock().now(),
613 };
614 let settled = self.settle_open_prints(&observed).await?;
615 match settled.running {
616 Some(running) if running.id == print.id => Ok(running),
617 _ if settled.closed.contains(&print.id) => Ok(self
618 .stores()
619 .prints
620 .print(print.id)
621 .await?
622 .unwrap_or_else(|| print.clone())),
623 _ => Ok(print.clone()),
624 }
625 }
626
627 /// End the print, expire what it had running, and close its session.
628 ///
629 /// The interventions are expired **before** the print is ended, because a
630 /// restoration is an action against the print and a print that has already
631 /// ended is one no action may be taken against.
632 ///
633 /// The caller holds the print's turn, so no turn is acting on it while it
634 /// closes. Answers whether this closed it: a print already ended — by
635 /// another read, or by the turn that held it — is left as it ended.
636 ///
637 /// The print's filament is settled after its interventions are expired
638 /// and before it is ended ([`crate::accounting`]): a crash between the two
639 /// leaves a settled, open print, which the next close-out only ends.
640 /// `closing_job` is the job read that found the print over, when there
641 /// was one; without it the settlement reads the job itself.
642 pub(crate) async fn close_out_print(
643 &self,
644 print_id: PrintId,
645 state: &PrinterState,
646 reason: &str,
647 closing_job: Option<&JobSnapshot>,
648 ) -> Result<bool, CoreError> {
649 let print = match self.stores().prints.print(print_id).await? {
650 Some(print) if print.ended_at.is_none() => print,
651 _ => return Ok(false),
652 };
653 self.forget_detector_pause(print_id);
654 self.expire_all_active(print_id).await?;
655 self.settle_filament(&print, state, reason, closing_job)
656 .await?;
657 self.stores()
658 .prints
659 .end_print(
660 print_id,
661 state.clone(),
662 self.clock().now(),
663 reason.to_owned(),
664 )
665 .await?;
666 let _ = self
667 .agent()
668 .close_session(print_id, reason.to_owned())
669 .await;
670 if let Some(session) = self.stores().sessions.session(print_id).await? {
671 self.append_system_event(
672 print_id,
673 EventBody::of(&SupervisionSessionClosedPayload {
674 session_name: session.session_name,
675 close_reason: reason.to_owned(),
676 })?,
677 )
678 .await?;
679 }
680 Ok(true)
681 }
682
683 /// Append one event this system raised itself.
684 pub(crate) async fn append_system_event(
685 &self,
686 print_id: PrintId,
687 body: EventBody,
688 ) -> Result<EventRecord, CoreError> {
689 Ok(self
690 .stores()
691 .events
692 .append_event(EventDraft {
693 print_id: Some(print_id),
694 source: system_source(),
695 received_at: self.clock().now(),
696 body,
697 raw: None,
698 })
699 .await?)
700 }
701
702 /// Record a printer read that failed, when an event prompted the read.
703 async fn record_read_failure(
704 &self,
705 print_id: PrintId,
706 event_id: Option<printobserver_types::EventId>,
707 site: PortFailureSite,
708 detail: String,
709 ) {
710 if let Some(event_id) = event_id {
711 self.record_port_failure(print_id, event_id, site, detail)
712 .await;
713 }
714 }
715
716 /// Record that a port failed while one event was being handled.
717 ///
718 /// The event is already in the history by the time any of these sites is
719 /// reached, which is what gives the failure somewhere to be recorded.
720 /// Nothing is answered to the caller: the loop survives this and goes on.
721 pub(crate) async fn record_port_failure(
722 &self,
723 print_id: PrintId,
724 event_id: printobserver_types::EventId,
725 site: PortFailureSite,
726 detail: String,
727 ) {
728 // A record that will not render is dropped exactly as one the store
729 // refuses is: the failure it was about has already been answered, and
730 // the loop survives not having written it down.
731 let Ok(body) = EventBody::of(&PortFailurePayload {
732 event_id,
733 site,
734 detail,
735 }) else {
736 return;
737 };
738 let _ = self.append_system_event(print_id, body).await;
739 }
740}