1use std::time::Duration;
47
48use printobserver_printer_api::{
49 BoxFuture, PrinterErrorReason, PrinterPush, PrinterSnapshot, PrinterState,
50};
51use printobserver_types::contract::Sample;
52use printobserver_types::schemars::JsonSchema;
53use printobserver_types::serde::{Deserialize, Serialize};
54use printobserver_types::{EventKind, EventPayload as _, EventRecord, PrintId, Timestamp};
55
56use crate::error::CoreError;
57use crate::events::PendingTurn;
58use crate::inbox::Arrival;
59use crate::kinds::{
60 DetectorHealthChangedPayload, DetectorStatus, HeatedTool, PrintEndedPayload,
61 PrinterConnectionChangedPayload, PrinterResetPayload, UnattendedPrinterActivityPayload,
62 system_source,
63};
64use crate::listing::ObservedJob;
65use crate::records::{PrintOutcome, PrintRecord};
66use crate::store::HistoryQuery;
67use crate::supervisor::Supervisor;
68
69pub const DEFAULT_PRINTER_POLL: Duration = Duration::from_secs(15);
71
72pub const DEFAULT_UNATTENDED_WINDOW: Duration = Duration::from_secs(3600);
75
76pub const RESET_GRACE: Duration = Duration::from_secs(1);
84
85pub const PUSH_CHANNEL_DOWN: &str =
87 "the printer's push channel was down, so this was read from its state alone";
88
89pub const PRINTER_WATCH_KINDS: [&str; 4] = [
92 PrinterConnectionChangedPayload::KIND,
93 PrinterResetPayload::KIND,
94 UnattendedPrinterActivityPayload::KIND,
95 DetectorHealthChangedPayload::KIND,
96];
97
98#[derive(Debug, Clone, Copy, PartialEq)]
100pub struct HeadPosition {
101 pub x: f64,
103 pub y: f64,
105 pub z: f64,
107}
108
109pub trait PositionProbe: Send + Sync {
114 fn read_position(&self) -> BoxFuture<'_, Option<HeadPosition>>;
116}
117
118pub trait DetectorProbe: Send + Sync {
120 fn check(&self) -> BoxFuture<'_, Result<String, String>>;
123}
124
125#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
127#[serde(
128 crate = "printobserver_types::serde",
129 rename_all = "snake_case",
130 deny_unknown_fields
131)]
132#[schemars(crate = "printobserver_types::schemars")]
133pub enum DetectorHealthStatus {
134 Available,
136 Unavailable,
138 #[default]
141 Unchecked,
142}
143
144#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
152pub enum DetectorHealth {
153 #[default]
156 Unchecked,
157 Available {
159 since: Timestamp,
161 },
162 Unavailable {
164 since: Timestamp,
166 },
167}
168
169impl DetectorHealth {
170 #[must_use]
172 pub const fn status(&self) -> DetectorHealthStatus {
173 match self {
174 Self::Unchecked => DetectorHealthStatus::Unchecked,
175 Self::Available { .. } => DetectorHealthStatus::Available,
176 Self::Unavailable { .. } => DetectorHealthStatus::Unavailable,
177 }
178 }
179}
180
181#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
183#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
184struct DetectorHealthWire {
185 status: DetectorHealthStatus,
187 #[serde(deserialize_with = "present")]
190 since: Option<Timestamp>,
191}
192
193fn present<'de, D: printobserver_types::serde::Deserializer<'de>>(
196 deserializer: D,
197) -> Result<Option<Timestamp>, D::Error> {
198 Option::deserialize(deserializer)
199}
200
201impl From<DetectorHealth> for DetectorHealthWire {
202 fn from(health: DetectorHealth) -> Self {
203 let since = match health {
204 DetectorHealth::Unchecked => None,
205 DetectorHealth::Available { since } | DetectorHealth::Unavailable { since } => {
206 Some(since)
207 }
208 };
209 Self {
210 status: health.status(),
211 since,
212 }
213 }
214}
215
216impl TryFrom<DetectorHealthWire> for DetectorHealth {
217 type Error = &'static str;
218
219 fn try_from(wire: DetectorHealthWire) -> Result<Self, Self::Error> {
220 match (wire.status, wire.since) {
221 (DetectorHealthStatus::Unchecked, None) => Ok(Self::Unchecked),
222 (DetectorHealthStatus::Available, Some(since)) => Ok(Self::Available { since }),
223 (DetectorHealthStatus::Unavailable, Some(since)) => Ok(Self::Unavailable { since }),
224 (DetectorHealthStatus::Unchecked, Some(_)) => {
225 Err("an unchecked detector has no instant it became so")
226 }
227 (_, None) => Err("a checked detector carries the instant it became so"),
228 }
229 }
230}
231
232impl Serialize for DetectorHealth {
233 fn serialize<S: printobserver_types::serde::Serializer>(
234 &self,
235 serializer: S,
236 ) -> Result<S::Ok, S::Error> {
237 DetectorHealthWire::from(*self).serialize(serializer)
238 }
239}
240
241impl<'de> Deserialize<'de> for DetectorHealth {
242 fn deserialize<D: printobserver_types::serde::Deserializer<'de>>(
243 deserializer: D,
244 ) -> Result<Self, D::Error> {
245 let wire = DetectorHealthWire::deserialize(deserializer)?;
246 Self::try_from(wire).map_err(printobserver_types::serde::de::Error::custom)
247 }
248}
249
250fn health_arm(
252 status: &str,
253 doc: &str,
254 since: &printobserver_types::serde_json::Value,
255) -> printobserver_types::serde_json::Value {
256 printobserver_types::serde_json::json!({
257 "type": "object",
258 "description": doc,
259 "properties": {
260 "status": { "type": "string", "const": status },
261 "since": since,
262 },
263 "required": ["status", "since"],
264 "additionalProperties": false,
265 })
266}
267
268impl JsonSchema for DetectorHealth {
271 fn schema_name() -> std::borrow::Cow<'static, str> {
272 std::borrow::Cow::Borrowed("DetectorHealth")
273 }
274
275 fn json_schema(
276 generator: &mut printobserver_types::schemars::SchemaGenerator,
277 ) -> printobserver_types::schemars::Schema {
278 let timestamp =
279 printobserver_types::serde_json::to_value(generator.subschema_for::<Timestamp>())
280 .unwrap_or_default();
281 let schema = printobserver_types::serde_json::json!({
282 "title": "DetectorHealth",
283 "description": "The failure detector's health, and since when it has been so: \
284 `since` is `null` exactly while the status is `unchecked`.",
285 "oneOf": [
286 health_arm(
287 "unchecked",
288 "Nothing checks it: no detector health address is configured, or no \
289 check has been made yet.",
290 &printobserver_types::serde_json::json!({
291 "type": "null",
292 "description": "Nothing: an unchecked detector has no instant it became so.",
293 }),
294 ),
295 health_arm(
296 "available",
297 "It answered its health check, from `since` on.",
298 ×tamp,
299 ),
300 health_arm(
301 "unavailable",
302 "It did not answer its health check, from `since` on.",
303 ×tamp,
304 ),
305 ],
306 });
307 printobserver_types::schemars::Schema::try_from(schema).unwrap_or_default()
308 }
309}
310
311impl Sample for DetectorHealth {
312 fn sample_full() -> Self {
313 Self::Unavailable {
314 since: Timestamp::sample_full(),
315 }
316 }
317
318 fn sample_minimal() -> Self {
319 Self::Unchecked
320 }
321
322 fn sample_alternates() -> Vec<Self> {
323 vec![Self::Available {
324 since: Timestamp::sample_full(),
325 }]
326 }
327}
328
329#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
333pub(crate) struct PushFacts {
334 pub(crate) reset: bool,
336 pub(crate) firmware_error: bool,
338 pub(crate) gap: bool,
341}
342
343#[derive(Debug, Clone, PartialEq)]
345struct Activity {
346 tools: Vec<HeatedTool>,
348 bed: Option<f64>,
350 moved: Option<bool>,
352}
353
354impl Activity {
355 fn is_active(&self) -> bool {
357 !self.tools.is_empty() || self.bed.is_some() || self.moved == Some(true)
358 }
359}
360
361#[derive(Debug, Clone)]
363struct Unattended {
364 print_id: PrintId,
366 began: Duration,
368 recorded: Option<Activity>,
370 position: Option<HeadPosition>,
372 turned_at: Option<Duration>,
375}
376
377#[derive(Debug, Default)]
379pub(crate) struct WatchState {
380 last_state: Option<PrinterState>,
382 pushes: PushFacts,
384 channel: Channel,
386 unattended: Option<Unattended>,
388 detector: DetectorHealth,
390 pending_turns: Vec<PendingTurn>,
392 pending_resets: Vec<PrinterResetPayload>,
394 pending_ends: Vec<PrintId>,
397 pending_claims: Vec<(PrintId, EventRecord)>,
400}
401
402impl WatchState {
403 const fn channel_is_down(&self) -> bool {
405 !matches!(self.channel, Channel::Open)
406 }
407}
408
409#[derive(Debug, Clone, Default, PartialEq, Eq)]
411enum Channel {
412 #[default]
414 Unknown,
415 Open,
417 Down(String),
419}
420
421#[derive(Debug, Default)]
423pub struct Watched {
424 pub turns: Vec<PendingTurn>,
427}
428
429const fn is_down(state: &PrinterState) -> bool {
431 matches!(state, PrinterState::Offline | PrinterState::Error)
432}
433
434const fn job_runs(state: &PrinterState) -> bool {
436 matches!(
437 state,
438 PrinterState::Printing | PrinterState::Paused | PrinterState::Cancelling
439 )
440}
441
442fn heated(snapshot: &PrinterSnapshot) -> (Vec<HeatedTool>, Option<f64>) {
444 let tools = snapshot
445 .tools
446 .iter()
447 .enumerate()
448 .filter_map(|(index, heater)| {
449 let target = heater.target_c.as_ref()?.value();
450 (target > 0.0).then(|| HeatedTool {
451 tool: i64::try_from(index).unwrap_or(i64::MAX),
452 target_c: target,
453 })
454 })
455 .collect();
456 let bed = snapshot
457 .bed
458 .as_ref()
459 .and_then(|bed| bed.target_c.as_ref())
460 .map(printobserver_types::Reported::value)
461 .filter(|target| *target > 0.0);
462 (tools, bed)
463}
464
465fn activity_detail(activity: &Activity, channel_down: bool) -> String {
467 let mut parts: Vec<String> = activity
468 .tools
469 .iter()
470 .map(|tool| format!("tool {} is heating to {} °C", tool.tool, tool.target_c))
471 .collect();
472 if let Some(bed) = activity.bed {
473 parts.push(format!("the bed is heating to {bed} °C"));
474 }
475 match activity.moved {
476 Some(true) => parts.push("the print head moved".to_owned()),
477 Some(false) => {}
478 None => parts.push("the print head's position could not be read".to_owned()),
479 }
480 let mut detail = format!("with no job running, {}", parts.join(", "));
481 if channel_down {
482 detail.push_str("; ");
483 detail.push_str(PUSH_CHANNEL_DOWN);
484 }
485 detail
486}
487
488impl Supervisor {
489 pub(crate) fn watch_state(&self) -> std::sync::MutexGuard<'_, WatchState> {
491 self.watch
492 .lock()
493 .unwrap_or_else(std::sync::PoisonError::into_inner)
494 }
495
496 pub(crate) fn push_facts(&self) -> PushFacts {
498 let state = self.watch_state();
499 let mut facts = state.pushes;
500 facts.gap |= state.channel_is_down();
501 facts
502 }
503
504 pub(crate) async fn pushes_after_a_reset_could_arrive(&self) -> PushFacts {
508 let started = std::time::Instant::now();
511 loop {
512 let facts = self.push_facts();
513 if facts.reset
514 || self.watch_state().channel_is_down()
515 || started.elapsed() >= RESET_GRACE
516 || crate::delay::Delay::new(Duration::from_millis(50))
517 .await
518 .is_err()
519 {
520 return facts;
521 }
522 }
523 }
524
525 pub(crate) fn note_job_running(&self) {
527 self.watch_state().unattended = None;
528 }
529
530 pub(crate) fn forget_pushes(&self) {
533 let mut state = self.watch_state();
534 let gap = state.channel_is_down();
535 state.pushes = PushFacts {
536 gap,
537 ..PushFacts::default()
538 };
539 }
540
541 #[must_use]
543 pub fn detector_health(&self) -> DetectorHealth {
544 self.watch_state().detector
545 }
546
547 pub fn note_push_channel(&self, open: Result<(), String>) {
552 let mut state = self.watch_state();
553 match open {
554 Ok(()) => state.channel = Channel::Open,
555 Err(detail) => {
556 state.channel = Channel::Down(detail);
557 state.pushes.gap = true;
558 }
559 }
560 }
561
562 pub async fn note_push(&self, push: PrinterPush) -> Result<(), CoreError> {
573 match push {
574 PrinterPush::Reset => {
575 self.watch_state().pushes.reset = true;
576 let (during_print, detail) = match self.running_print().await {
579 Ok(Some(print)) => (
580 Some(print.id),
581 format!("the printer pushed a reset during print {}", print.id),
582 ),
583 Ok(None) => (
584 None,
585 "the printer pushed a reset while no print was running".to_owned(),
586 ),
587 Err(error) => (
588 None,
589 format!(
590 "the printer pushed a reset; which print was running could not be \
591 read: {error}"
592 ),
593 ),
594 };
595 let payload = PrinterResetPayload {
596 during_print,
597 detail,
598 };
599 if let Err(error) = self.write_reset(&payload).await {
600 self.watch_state().pending_resets.push(payload);
603 return Err(error);
604 }
605 Ok(())
606 }
607 PrinterPush::Error {
608 reason: PrinterErrorReason::Firmware,
609 } => {
610 self.watch_state().pushes.firmware_error = true;
611 Ok(())
612 }
613 PrinterPush::Error {
614 reason: PrinterErrorReason::Other(_),
615 }
616 | PrinterPush::Log { .. } => Ok(()),
617 }
618 }
619
620 async fn write_reset(&self, payload: &PrinterResetPayload) -> Result<(), CoreError> {
622 let draft = self.draft_of(None, system_source(), payload)?;
623 self.stores().events.append_event(draft).await?;
624 Ok(())
625 }
626
627 async fn catch_up(&self) {
631 let resets = std::mem::take(&mut self.watch_state().pending_resets);
632 for payload in resets {
633 if self.write_reset(&payload).await.is_err() {
634 self.watch_state().pending_resets.push(payload);
635 }
636 }
637 let ends = std::mem::take(&mut self.watch_state().pending_ends);
638 for print_id in ends {
639 if self.after_close_out(print_id).await.is_err() {
640 self.watch_state().pending_ends.push(print_id);
641 }
642 }
643 let claims = std::mem::take(&mut self.watch_state().pending_claims);
644 for (print_id, event) in claims {
645 self.claim_activity_turn(print_id, event).await;
646 }
647 }
648
649 pub(crate) async fn follow_up_end(&self, print_id: PrintId) {
652 if self.after_close_out(print_id).await.is_err() {
653 self.watch_state().pending_ends.push(print_id);
654 }
655 }
656
657 async fn running_print(&self) -> Result<Option<PrintRecord>, CoreError> {
659 Ok(self
660 .stores()
661 .prints
662 .open_prints()
663 .await?
664 .into_iter()
665 .find(|print| self.was_seen_running(print.id)))
666 }
667
668 pub async fn watch_printer(&self, probe: &dyn PositionProbe) -> Result<Watched, CoreError> {
678 self.catch_up().await;
679 let resolving = self.resolving().await;
680 let observed = self.observe_job().await;
681 if let Some(observed) = &observed {
682 self.note_connection(
683 &observed.job.state,
684 observed.job.error.as_ref().map(|error| error.text.as_str()),
685 )
686 .await?;
687 self.settle_and_adopt(observed).await?;
688 }
689 drop(resolving);
690 if let Some(observed) = &observed {
691 self.watch_unattended(observed, probe).await?;
692 }
693 Ok(Watched {
694 turns: std::mem::take(&mut self.watch_state().pending_turns),
695 })
696 }
697
698 async fn note_connection(
701 &self,
702 state: &PrinterState,
703 error: Option<&str>,
704 ) -> Result<(), CoreError> {
705 let (previous, channel_down) = {
706 let held = self.watch_state();
707 (held.last_state.clone(), held.channel_is_down())
708 };
709 let changed = previous
710 .as_ref()
711 .filter(|previous| *previous != state && (is_down(previous) || is_down(state)));
712 if let Some(previous) = changed {
713 let reporting = error
714 .filter(|error| !error.trim().is_empty())
715 .map(|error| format!(", reporting {error:?}"))
716 .unwrap_or_default();
717 let mut detail = format!("the printer went from {previous:?} to {state:?}{reporting}");
718 if channel_down {
719 detail.push_str("; ");
720 detail.push_str(PUSH_CHANNEL_DOWN);
721 }
722 let draft = self.draft_of(
723 None,
724 system_source(),
725 &PrinterConnectionChangedPayload {
726 from: previous.clone(),
727 to: state.clone(),
728 detail,
729 },
730 )?;
731 self.stores().events.append_event(draft).await?;
734 }
735 self.watch_state().last_state = Some(state.clone());
736 Ok(())
737 }
738
739 async fn after_close_out(&self, print_id: PrintId) -> Result<(), CoreError> {
743 self.forget_pushes();
744 let Some(ended) = self
745 .stores()
746 .events
747 .history(HistoryQuery {
748 print_id,
749 kinds: vec![PrintEndedPayload::kind()],
750 since: None,
751 until: None,
752 limit: Some(1),
753 })
754 .await?
755 .into_iter()
756 .next()
757 else {
758 return Ok(());
759 };
760 let Some(Ok(payload)) = ended.payload_as::<PrintEndedPayload>() else {
761 return Ok(());
762 };
763 if !matches!(
764 payload.outcome,
765 PrintOutcome::Interrupted | PrintOutcome::Failed
766 ) {
767 self.watch_state().unattended = None;
768 return Ok(());
769 }
770 self.watch_state().unattended = Some(Unattended {
771 print_id,
772 began: self.clock().elapsed(),
773 recorded: None,
774 position: None,
775 turned_at: None,
776 });
777 self.claim_after_end(print_id, ended).await
778 }
779
780 async fn claim_after_end(
783 &self,
784 print_id: PrintId,
785 event: EventRecord,
786 ) -> Result<(), CoreError> {
787 let Some(print) = self.stores().prints.print(print_id).await? else {
788 return Ok(());
789 };
790 let arrival = Arrival {
791 event,
792 detection: None,
793 };
794 if self.inboxes().claim_or_hand_over(print_id, arrival.clone()) {
795 self.watch_state()
796 .pending_turns
797 .push(PendingTurn::new(print, arrival, Vec::new()));
798 }
799 Ok(())
800 }
801
802 async fn watch_unattended(
805 &self,
806 observed: &ObservedJob,
807 probe: &dyn PositionProbe,
808 ) -> Result<(), CoreError> {
809 let window = self.config().unattended_window;
810 let now = self.clock().elapsed();
811 let (print_id, last_position, channel_down) = {
812 let mut held = self.watch_state();
813 let Some(open) = &held.unattended else {
814 return Ok(());
815 };
816 if now.saturating_sub(open.began) > window {
817 held.unattended = None;
818 return Ok(());
819 }
820 (open.print_id, open.position, held.channel_is_down())
821 };
822 if job_runs(&observed.job.state) || is_down(&observed.job.state) {
823 return Ok(());
824 }
825 let Ok(snapshot) = self.read_snapshot().await else {
826 return Ok(());
827 };
828 if job_runs(&snapshot.connection) || is_down(&snapshot.connection) {
829 return Ok(());
830 }
831 let (tools, bed) = heated(&snapshot);
832 let position = probe.read_position().await;
833 let moved = match (last_position, position) {
834 (_, None) => None,
835 (None, Some(_)) => Some(false),
836 (Some(before), Some(after)) => Some(before != after),
837 };
838 let activity = Activity { tools, bed, moved };
839 let unchanged = {
840 let mut held = self.watch_state();
841 let Some(open) = held
842 .unattended
843 .as_mut()
844 .filter(|open| open.print_id == print_id)
845 else {
846 return Ok(());
847 };
848 if position.is_some() {
849 open.position = position;
850 }
851 if !activity.is_active() {
852 open.recorded = None;
853 return Ok(());
854 }
855 open.recorded.as_ref() == Some(&activity)
856 };
857 if unchanged {
858 return Ok(());
859 }
860 let draft = self.draft_of(
861 None,
862 system_source(),
863 &UnattendedPrinterActivityPayload {
864 last_print_id: print_id,
865 tools: activity.tools.clone(),
866 bed_target_c: activity.bed,
867 moved: activity.moved,
868 detail: activity_detail(&activity, channel_down),
869 },
870 )?;
871 let event = self.stores().events.append_event(draft).await?;
872 let interval = self.config().observation_interval;
873 let turn_due = {
874 let mut held = self.watch_state();
875 let Some(open) = held.unattended.as_mut() else {
876 return Ok(());
877 };
878 open.recorded = Some(activity.clone());
881 open.turned_at
882 .is_none_or(|turned| now.saturating_sub(turned) >= interval)
883 };
884 if turn_due {
885 self.claim_activity_turn(print_id, event).await;
886 }
887 Ok(())
888 }
889
890 async fn claim_activity_turn(&self, print_id: PrintId, event: EventRecord) {
894 if self.claim_after_end(print_id, event.clone()).await.is_err() {
895 self.watch_state().pending_claims.push((print_id, event));
896 return;
897 }
898 let now = self.clock().elapsed();
899 if let Some(open) = self
900 .watch_state()
901 .unattended
902 .as_mut()
903 .filter(|open| open.print_id == print_id)
904 {
905 open.turned_at = Some(now);
906 }
907 }
908
909 pub async fn check_detector(
920 &self,
921 probe: &dyn DetectorProbe,
922 ) -> Result<Option<PendingTurn>, CoreError> {
923 let Some(print) = self.stores().prints.open_prints().await?.into_iter().next() else {
924 return Ok(None);
925 };
926 let (status, detail) = match probe.check().await {
927 Ok(detail) => (DetectorStatus::Available, detail),
928 Err(detail) => (DetectorStatus::Unavailable, detail),
929 };
930 let health = match status {
931 DetectorStatus::Available => DetectorHealthStatus::Available,
932 DetectorStatus::Unavailable => DetectorHealthStatus::Unavailable,
933 };
934 let previous = self.watch_state().detector.status();
935 if previous == health {
936 return Ok(None);
937 }
938 let since = self.clock().now();
939 let found = match status {
940 DetectorStatus::Available => DetectorHealth::Available { since },
941 DetectorStatus::Unavailable => DetectorHealth::Unavailable { since },
942 };
943 if previous == DetectorHealthStatus::Unchecked && health == DetectorHealthStatus::Available
946 {
947 self.watch_state().detector = found;
948 return Ok(None);
949 }
950 let draft = self.draft_of(
951 None,
952 system_source(),
953 &DetectorHealthChangedPayload { status, detail },
954 )?;
955 let event = self.stores().events.append_event(draft).await?;
956 self.watch_state().detector = found;
959 if status != DetectorStatus::Unavailable {
960 return Ok(None);
961 }
962 let arrival = Arrival {
963 event,
964 detection: None,
965 };
966 Ok(self
967 .inboxes()
968 .claim_or_hand_over(print.id, arrival.clone())
969 .then(|| PendingTurn::new(print, arrival, Vec::new())))
970 }
971}
972
973pub(crate) fn concerns_its_end(kind: &EventKind) -> bool {
976 [
977 PrintEndedPayload::KIND,
978 UnattendedPrinterActivityPayload::KIND,
979 ]
980 .contains(&kind.as_str())
981}
982
983pub(crate) fn noticed_of(event: &EventRecord) -> Option<String> {
986 if let Some(Ok(ended)) = event.payload_as::<PrintEndedPayload>() {
987 let outcome = match ended.outcome {
988 PrintOutcome::Interrupted => "interrupted",
989 PrintOutcome::Failed => "failed",
990 PrintOutcome::Completed | PrintOutcome::Cancelled => return None,
991 };
992 return Some(format!(
993 "{}: the print ended {outcome}, the printer reporting {:?} ({})",
994 PrintEndedPayload::KIND,
995 ended.state,
996 ended.reason
997 ));
998 }
999 if let Some(Ok(activity)) = event.payload_as::<UnattendedPrinterActivityPayload>() {
1000 return Some(format!(
1001 "{}: after print {} ended, {}",
1002 UnattendedPrinterActivityPayload::KIND,
1003 activity.last_print_id,
1004 activity.detail
1005 ));
1006 }
1007 if let Some(Ok(degraded)) = event.payload_as::<crate::kinds::CameraDegradedPayload>() {
1008 return Some(format!(
1009 "{}: the camera gave no usable frame in {} attempts, so there is no frame to look \
1010 at: {}",
1011 crate::kinds::CameraDegradedPayload::KIND,
1012 degraded.attempts,
1013 degraded.detail
1014 ));
1015 }
1016 if let Some(Ok(health)) = event.payload_as::<DetectorHealthChangedPayload>() {
1017 return Some(format!(
1018 "{}: the failure detector is {:?}, so nothing is watching the print for failures: {}",
1019 DetectorHealthChangedPayload::KIND,
1020 health.status,
1021 health.detail
1022 ));
1023 }
1024 None
1025}