Skip to main content

printobserver_core/
watch.rs

1//! The printer watch: what changed under a print while nobody asked.
2//!
3//! Every other read of the printer here is somebody's — a listing, a status, a
4//! turn's context. The watch is nobody's: the server asks it to read the
5//! machine every [`CoreConfig::printer_poll`](crate::CoreConfig::printer_poll),
6//! whether or not a print is active, and it records what changed.
7//!
8//! * **The connection.** A read finding the printer's state changed into or
9//!   out of `offline` or `error` — a serial disconnect, a reconnect, a printer
10//!   error — is a [`PrinterConnectionChangedPayload`]. The printer's state is
11//!   read from its job, never from a refusal: a printer that is not
12//!   operational refuses a read of its own state, and that refusal is the
13//!   adapter's to read as `offline`, never one recorded as a port failure.
14//! * **How a print ended.** The watch's read settles the open prints as every
15//!   other read does ([`crate::listing`]), and the close-out decides the
16//!   outcome from what the printer pushed during the stop as well as from what
17//!   a read shows ([`crate::accounting`]). An `interrupted` or `failed` ending
18//!   gives the print's agent a turn on its `print_ended`, and opens the
19//!   unattended window.
20//! * **The printer acting on its own.** Within
21//!   [`CoreConfig::unattended_window`](crate::CoreConfig::unattended_window)
22//!   of an `interrupted` or `failed` ending, a read finding a heater target
23//!   above zero, or the head moved, while no job runs is an
24//!   [`UnattendedPrinterActivityPayload`]: once when it begins, and again only
25//!   when what it reports changes. The head's position is asked for through a
26//!   [`PositionProbe`] the server supplies, and only after this read found no
27//!   job running. The print's agent gets a turn on it, at most one per
28//!   [`CoreConfig::observation_interval`](crate::CoreConfig::observation_interval);
29//!   one recorded inside that interval reaches the agent through its next
30//!   turn's recent events.
31//! * **A reset.** The printer's push channel says when it reset, one while
32//!   idle included, which no read shows; each is a [`PrinterResetPayload`]
33//!   ([`Supervisor::note_push`]).
34//! * **The detector.** During a print, a [`DetectorProbe`] the server supplies
35//!   is asked whether the failure detector is answering, and each change is a
36//!   [`DetectorHealthChangedPayload`]; going unavailable gives the active
37//!   print's agent a turn. The last status is what the status and context
38//!   reads answer as [`DetectorHealth`].
39//!
40//! # Nothing here commands the machine
41//!
42//! The watch reads. A position is asked for through the probe, which is the
43//! server's own: this crate names no method of the printer port but its reads,
44//! and the chokepoint stands as [`crate::supervisor`] states it.
45
46use 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, PortFailureSite, 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
69/// How often the printer watch reads the machine, when nothing configures it.
70pub const DEFAULT_PRINTER_POLL: Duration = Duration::from_secs(15);
71
72/// How long after an `interrupted` or `failed` ending the printer acting on
73/// its own is recorded, when nothing configures it.
74pub const DEFAULT_UNATTENDED_WINDOW: Duration = Duration::from_secs(3600);
75
76/// How long a return to idle that would read as a cancel waits for the reset
77/// the printer may still be pushing for it.
78///
79/// `OctoPrint` pushes a reset within about a third of a second of the
80/// printer's own, and moves its state to idle within about two thirds; a read
81/// can land between the two, and without the reset a firmware reset reads as
82/// a cancel made at the printer.
83pub const RESET_GRACE: Duration = Duration::from_secs(1);
84
85/// What a detail says while the push channel is down.
86pub const PUSH_CHANNEL_DOWN: &str =
87    "the printer's push channel was down, so this was read from its state alone";
88
89/// The kinds the printer watch writes with no print: the printer's own, read
90/// into a print's recent events from the moment it opened.
91pub const PRINTER_WATCH_KINDS: [&str; 4] = [
92    PrinterConnectionChangedPayload::KIND,
93    PrinterResetPayload::KIND,
94    UnattendedPrinterActivityPayload::KIND,
95    DetectorHealthChangedPayload::KIND,
96];
97
98/// Where the print head is.
99#[derive(Debug, Clone, Copy, PartialEq)]
100pub struct HeadPosition {
101    /// X, in millimetres.
102    pub x: f64,
103    /// Y, in millimetres.
104    pub y: f64,
105    /// Z, in millimetres.
106    pub z: f64,
107}
108
109/// What reads the print head's position for the watch.
110///
111/// The server's own: it asks the printer and reads the answer off the push
112/// channel. Answers nothing when no position could be read.
113pub trait PositionProbe: Send + Sync {
114    /// Read where the head is now.
115    fn read_position(&self) -> BoxFuture<'_, Option<HeadPosition>>;
116}
117
118/// What asks the failure detector whether it is answering.
119pub trait DetectorProbe: Send + Sync {
120    /// Answers what it was told: `Ok` when the detector answered its health
121    /// check, `Err` when it did not, each in words.
122    fn check(&self) -> BoxFuture<'_, Result<String, String>>;
123}
124
125/// The failure detector's status, as the status and context reads answer it.
126#[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    /// The detector is scoring the print, and no failure alert of its own has
135    /// arrived for it.
136    ScoringNothingFlagged,
137    /// The detector is scoring the print, and a failure alert of its own has
138    /// arrived for it.
139    ScoringFlagged,
140    /// No evidence that it is scoring the print, and it answered its health
141    /// check: available, with no scores yet.
142    Available,
143    /// No evidence that it is scoring the print, and it did not answer its
144    /// health check.
145    Unavailable,
146    /// No evidence of any kind: no detector health address is configured, or
147    /// no check has been made yet, and nothing shows it scoring.
148    #[default]
149    Unchecked,
150}
151
152/// The failure detector's status, and since when it has been so.
153///
154/// Evidence that the detector is scoring the print comes first: while its own
155/// record of the print's live prediction moved between two of this server's
156/// reads within the last two observation intervals, it is scoring, whatever
157/// its health check answers. Without that evidence its health check decides.
158///
159/// On the wire it is the object the status and context reads answer —
160/// `status`; `since`, `null` exactly when the status is `unchecked`; the failing
161/// health check named beside a scoring status as `probe_failure`; and, beside
162/// any other status, why the detector's scoring is not being read as
163/// `scoring_unread` — and an object pairing them any other way is refused
164/// rather than read.
165#[derive(Debug, Clone, PartialEq, Eq)]
166pub enum DetectorHealth {
167    /// No evidence of any kind: no detector health address is configured, or
168    /// no check has been made yet, and nothing shows it scoring.
169    Unchecked {
170        /// Why the detector's scoring is not being read, when it is not.
171        scoring_unread: Option<String>,
172    },
173    /// No evidence that it is scoring the print, and it answered its health
174    /// check, from this instant on.
175    Available {
176        /// When it was first found answering.
177        since: Timestamp,
178        /// Why the detector's scoring is not being read, when it is not.
179        scoring_unread: Option<String>,
180    },
181    /// No evidence that it is scoring the print, and it did not answer its
182    /// health check, from this instant on.
183    Unavailable {
184        /// When it was first found not answering.
185        since: Timestamp,
186        /// Why the detector's scoring is not being read, when it is not.
187        scoring_unread: Option<String>,
188    },
189    /// The detector is scoring the print, from this instant on.
190    Scoring {
191        /// When it was first found scoring it.
192        since: Timestamp,
193        /// Whether a failure alert of its own has arrived for the print.
194        verdict: ScoringVerdict,
195        /// What the detector's health check answered, when it is failing
196        /// while the detector scores.
197        probe_failure: Option<String>,
198    },
199}
200
201/// What a detector scoring a print has said of it so far.
202#[derive(Debug, Clone, Copy, PartialEq, Eq)]
203pub enum ScoringVerdict {
204    /// No failure alert of its own has arrived for the print.
205    NothingFlagged,
206    /// A failure alert of its own has arrived for the print.
207    Flagged,
208}
209
210impl Default for DetectorHealth {
211    fn default() -> Self {
212        Self::Unchecked {
213            scoring_unread: None,
214        }
215    }
216}
217
218impl DetectorHealth {
219    /// The status this is.
220    #[must_use]
221    pub const fn status(&self) -> DetectorHealthStatus {
222        match self {
223            Self::Unchecked { .. } => DetectorHealthStatus::Unchecked,
224            Self::Available { .. } => DetectorHealthStatus::Available,
225            Self::Unavailable { .. } => DetectorHealthStatus::Unavailable,
226            Self::Scoring {
227                verdict: ScoringVerdict::NothingFlagged,
228                ..
229            } => DetectorHealthStatus::ScoringNothingFlagged,
230            Self::Scoring {
231                verdict: ScoringVerdict::Flagged,
232                ..
233            } => DetectorHealthStatus::ScoringFlagged,
234        }
235    }
236}
237
238/// The failure detector's status as the wire carries it.
239#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
240#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
241struct DetectorHealthWire {
242    /// What it is.
243    status: DetectorHealthStatus,
244    /// When the status became what it is, `null` exactly while unchecked —
245    /// and always present, as the schema requires.
246    #[serde(deserialize_with = "present")]
247    since: Option<Timestamp>,
248    /// The failing health check, beside a scoring status.
249    #[serde(default, skip_serializing_if = "Option::is_none")]
250    probe_failure: Option<String>,
251    /// Why the detector's scoring is not being read, beside any other status.
252    #[serde(default, skip_serializing_if = "Option::is_none")]
253    scoring_unread: Option<String>,
254}
255
256/// Read a value that may be `null` but may not be missing: serde reads a
257/// missing optional as `None` unless it is read through a function of its own.
258fn present<'de, D: printobserver_types::serde::Deserializer<'de>>(
259    deserializer: D,
260) -> Result<Option<Timestamp>, D::Error> {
261    Option::deserialize(deserializer)
262}
263
264impl From<DetectorHealth> for DetectorHealthWire {
265    fn from(health: DetectorHealth) -> Self {
266        let status = health.status();
267        let (since, probe_failure, scoring_unread) = match health {
268            DetectorHealth::Unchecked { scoring_unread } => (None, None, scoring_unread),
269            DetectorHealth::Available {
270                since,
271                scoring_unread,
272            }
273            | DetectorHealth::Unavailable {
274                since,
275                scoring_unread,
276            } => (Some(since), None, scoring_unread),
277            DetectorHealth::Scoring {
278                since,
279                probe_failure,
280                ..
281            } => (Some(since), probe_failure, None),
282        };
283        Self {
284            status,
285            since,
286            probe_failure,
287            scoring_unread,
288        }
289    }
290}
291
292impl TryFrom<DetectorHealthWire> for DetectorHealth {
293    type Error = &'static str;
294
295    fn try_from(wire: DetectorHealthWire) -> Result<Self, Self::Error> {
296        let DetectorHealthWire {
297            status,
298            since,
299            probe_failure,
300            scoring_unread,
301        } = wire;
302        let scoring = matches!(
303            status,
304            DetectorHealthStatus::ScoringNothingFlagged | DetectorHealthStatus::ScoringFlagged
305        );
306        if scoring && scoring_unread.is_some() {
307            return Err("a scoring detector's scoring is being read");
308        }
309        if !scoring && probe_failure.is_some() {
310            return Err("only a scoring detector names its failing health check beside it");
311        }
312        match (status, since) {
313            (DetectorHealthStatus::Unchecked, None) => Ok(Self::Unchecked { scoring_unread }),
314            (DetectorHealthStatus::Available, Some(since)) => Ok(Self::Available {
315                since,
316                scoring_unread,
317            }),
318            (DetectorHealthStatus::Unavailable, Some(since)) => Ok(Self::Unavailable {
319                since,
320                scoring_unread,
321            }),
322            (DetectorHealthStatus::ScoringNothingFlagged, Some(since)) => Ok(Self::Scoring {
323                since,
324                verdict: ScoringVerdict::NothingFlagged,
325                probe_failure,
326            }),
327            (DetectorHealthStatus::ScoringFlagged, Some(since)) => Ok(Self::Scoring {
328                since,
329                verdict: ScoringVerdict::Flagged,
330                probe_failure,
331            }),
332            (DetectorHealthStatus::Unchecked, Some(_)) => {
333                Err("an unchecked detector has no instant it became so")
334            }
335            (_, None) => Err("a checked detector carries the instant it became so"),
336        }
337    }
338}
339
340impl Serialize for DetectorHealth {
341    fn serialize<S: printobserver_types::serde::Serializer>(
342        &self,
343        serializer: S,
344    ) -> Result<S::Ok, S::Error> {
345        DetectorHealthWire::from(self.clone()).serialize(serializer)
346    }
347}
348
349impl<'de> Deserialize<'de> for DetectorHealth {
350    fn deserialize<D: printobserver_types::serde::Deserializer<'de>>(
351        deserializer: D,
352    ) -> Result<Self, D::Error> {
353        let wire = DetectorHealthWire::deserialize(deserializer)?;
354        Self::try_from(wire).map_err(printobserver_types::serde::de::Error::custom)
355    }
356}
357
358/// One arm of the detector's status as a schema: its status, its `since`, and
359/// the one optional text it may carry beside them.
360fn health_arm(
361    status: &str,
362    doc: &str,
363    since: &printobserver_types::serde_json::Value,
364    beside: (&str, &str),
365) -> printobserver_types::serde_json::Value {
366    let (field, field_doc) = beside;
367    let mut properties = printobserver_types::serde_json::Map::new();
368    properties.insert(
369        "status".to_owned(),
370        printobserver_types::serde_json::json!({ "type": "string", "const": status }),
371    );
372    properties.insert("since".to_owned(), since.clone());
373    properties.insert(
374        field.to_owned(),
375        printobserver_types::serde_json::json!({ "type": "string", "description": field_doc }),
376    );
377    printobserver_types::serde_json::json!({
378        "type": "object",
379        "description": doc,
380        "properties": properties,
381        "required": ["status", "since"],
382        "additionalProperties": false,
383    })
384}
385
386/// What `scoring_unread` says, in the schema.
387const SCORING_UNREAD_DOC: &str = "Why the detector's scoring of the print is not being read, \
388    when it is not: no Obico API is configured, no Obico printer is known yet, or the last read \
389    failed.";
390
391/// What `probe_failure` says, in the schema.
392const PROBE_FAILURE_DOC: &str = "What the detector's health check answered, when it is \
393    failing while the detector scores the print.";
394
395/// The schema describes the five states as arms tagged by `status`, so a
396/// generated client cannot pair a status with the wrong `since` either.
397impl JsonSchema for DetectorHealth {
398    fn schema_name() -> std::borrow::Cow<'static, str> {
399        std::borrow::Cow::Borrowed("DetectorHealth")
400    }
401
402    fn json_schema(
403        generator: &mut printobserver_types::schemars::SchemaGenerator,
404    ) -> printobserver_types::schemars::Schema {
405        let timestamp =
406            printobserver_types::serde_json::to_value(generator.subschema_for::<Timestamp>())
407                .unwrap_or_default();
408        let unread = ("scoring_unread", SCORING_UNREAD_DOC);
409        let failing = ("probe_failure", PROBE_FAILURE_DOC);
410        let schema = printobserver_types::serde_json::json!({
411            "title": "DetectorHealth",
412            "description": "The failure detector's status, and since when it has been so: \
413                `since` is `null` exactly while the status is `unchecked`. Evidence that the \
414                detector is scoring the print comes before its health check.",
415            "oneOf": [
416                health_arm(
417                    "scoring_nothing_flagged",
418                    "The detector is scoring the print, from `since` on, and no failure alert \
419                     of its own has arrived for it.",
420                    &timestamp,
421                    failing,
422                ),
423                health_arm(
424                    "scoring_flagged",
425                    "The detector is scoring the print, from `since` on, and a failure alert \
426                     of its own has arrived for it.",
427                    &timestamp,
428                    failing,
429                ),
430                health_arm(
431                    "available",
432                    "No evidence that the detector is scoring the print, and it answered its \
433                     health check, from `since` on: available, with no scores yet.",
434                    &timestamp,
435                    unread,
436                ),
437                health_arm(
438                    "unavailable",
439                    "No evidence that the detector is scoring the print, and it did not answer \
440                     its health check, from `since` on.",
441                    &timestamp,
442                    unread,
443                ),
444                health_arm(
445                    "unchecked",
446                    "No evidence of any kind: no detector health address is configured, or no \
447                     check has been made yet, and nothing shows the detector scoring.",
448                    &printobserver_types::serde_json::json!({
449                        "type": "null",
450                        "description": "Nothing: an unchecked detector has no instant it became so.",
451                    }),
452                    unread,
453                ),
454            ],
455        });
456        printobserver_types::schemars::Schema::try_from(schema).unwrap_or_default()
457    }
458}
459
460impl Sample for DetectorHealth {
461    fn sample_full() -> Self {
462        Self::Scoring {
463            since: Timestamp::sample_full(),
464            verdict: ScoringVerdict::NothingFlagged,
465            probe_failure: Some("the detector's health check answered 503".to_owned()),
466        }
467    }
468
469    fn sample_minimal() -> Self {
470        Self::Unchecked {
471            scoring_unread: None,
472        }
473    }
474
475    fn sample_alternates() -> Vec<Self> {
476        vec![
477            Self::Scoring {
478                since: Timestamp::sample_full(),
479                verdict: ScoringVerdict::Flagged,
480                probe_failure: None,
481            },
482            Self::Available {
483                since: Timestamp::sample_full(),
484                scoring_unread: Some(
485                    "no Obico printer is known yet: no [obico] printer_id is configured and Obico \
486                     has posted nothing naming one since this server started"
487                        .to_owned(),
488                ),
489            },
490            Self::Unavailable {
491                since: Timestamp::sample_full(),
492                scoring_unread: None,
493            },
494            Self::Unchecked {
495                scoring_unread: Some(
496                    "no [obico] url and access_token are configured, so Obico's record of the \
497                     print is not read"
498                        .to_owned(),
499                ),
500            },
501        ]
502    }
503}
504
505/// What the detector's health check last found, with what it was answered.
506#[derive(Debug, Clone, Default, PartialEq, Eq)]
507pub(crate) enum ProbeHealth {
508    /// Nothing has checked it.
509    #[default]
510    Unchecked,
511    /// It answered, from this instant on.
512    Available {
513        /// When it was first found answering.
514        since: Timestamp,
515    },
516    /// It did not, from this instant on.
517    Unavailable {
518        /// When it was first found not answering.
519        since: Timestamp,
520        /// What it was answered, in words.
521        detail: String,
522    },
523}
524
525impl ProbeHealth {
526    /// The status the check alone gives.
527    const fn status(&self) -> DetectorHealthStatus {
528        match self {
529            Self::Unchecked => DetectorHealthStatus::Unchecked,
530            Self::Available { .. } => DetectorHealthStatus::Available,
531            Self::Unavailable { .. } => DetectorHealthStatus::Unavailable,
532        }
533    }
534}
535
536/// What the printer pushed since the last print started or was closed out:
537/// a stop's push and the read that finds the stop can arrive in either order,
538/// so what a print's run pushed is kept for its whole run.
539#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
540pub(crate) struct PushFacts {
541    /// It pushed a reset.
542    pub(crate) reset: bool,
543    /// It pushed an error of its own.
544    pub(crate) firmware_error: bool,
545    /// The push channel was down at some point, so what it pushed is not the
546    /// whole of what happened.
547    pub(crate) gap: bool,
548}
549
550/// What the printer was doing on its own, as one read found it.
551#[derive(Debug, Clone, PartialEq)]
552struct Activity {
553    /// Every tool whose target is above zero.
554    tools: Vec<HeatedTool>,
555    /// The bed's target, when above zero.
556    bed: Option<f64>,
557    /// Whether the head moved since the last position read.
558    moved: Option<bool>,
559}
560
561impl Activity {
562    /// Whether this is activity at all.
563    fn is_active(&self) -> bool {
564        !self.tools.is_empty() || self.bed.is_some() || self.moved == Some(true)
565    }
566}
567
568/// The window after an unfinished ending in which activity is recorded.
569#[derive(Debug, Clone)]
570struct Unattended {
571    /// The print that ended.
572    print_id: PrintId,
573    /// When, on the clock nothing steps, it ended.
574    began: Duration,
575    /// The activity last recorded, absent when none is under way.
576    recorded: Option<Activity>,
577    /// The position last read.
578    position: Option<HeadPosition>,
579    /// When, on the clock nothing steps, its agent was last given a turn on
580    /// activity.
581    turned_at: Option<Duration>,
582}
583
584/// What the watch holds between reads.
585#[derive(Debug, Default)]
586pub(crate) struct WatchState {
587    /// The printer's state the last read found.
588    last_state: Option<PrinterState>,
589    /// What the printer pushed since the last print started or was closed out.
590    pushes: PushFacts,
591    /// The push channel.
592    channel: Channel,
593    /// The unattended window, while one is open.
594    unattended: Option<Unattended>,
595    /// What the detector's health check last found.
596    pub(crate) probe: ProbeHealth,
597    /// What the reads of the detector's own record of the print have found.
598    pub(crate) scoring: crate::scoring::ScoringState,
599    /// Turns an ending claimed, for the next watch round to answer.
600    pending_turns: Vec<PendingTurn>,
601    /// Resets the store refused to write down, for the next round to write.
602    pending_resets: Vec<PrinterResetPayload>,
603    /// Prints closed out whose ending was not yet followed up, because the
604    /// store would not answer, for the next round to follow up.
605    pending_ends: Vec<PrintId>,
606    /// Activity turns the store would not answer for, for the next round to
607    /// claim.
608    pending_claims: Vec<(PrintId, EventRecord)>,
609}
610
611impl WatchState {
612    /// Whether the push channel is anything but open now.
613    const fn channel_is_down(&self) -> bool {
614        !matches!(self.channel, Channel::Open)
615    }
616}
617
618/// The printer's push channel, as the server last reported it.
619#[derive(Debug, Clone, Default, PartialEq, Eq)]
620enum Channel {
621    /// Nothing has reported on it yet.
622    #[default]
623    Unknown,
624    /// It is open.
625    Open,
626    /// It is down, and why.
627    Down(String),
628}
629
630/// What one round of the watch claimed.
631#[derive(Debug, Default)]
632pub struct Watched {
633    /// The turns it claimed, each to be run by
634    /// [`Supervisor::run_supervision`].
635    pub turns: Vec<PendingTurn>,
636    /// The open print the printer's job is, and the file position the read
637    /// found it at; absent when no job is running or it could not be read.
638    pub active: Option<ActiveJob>,
639}
640
641/// The open print a read found the printer running, and how far into its
642/// file the job was.
643#[derive(Debug, Clone, Copy, PartialEq, Eq)]
644pub struct ActiveJob {
645    /// The print.
646    pub print_id: PrintId,
647    /// The job's file position, when the printer reported one.
648    pub file_position_bytes: Option<i64>,
649}
650
651/// Whether a state is one a connection change is recorded into or out of.
652const fn is_down(state: &PrinterState) -> bool {
653    matches!(state, PrinterState::Offline | PrinterState::Error)
654}
655
656/// Whether a job in this state is one the printer is running.
657const fn job_runs(state: &PrinterState) -> bool {
658    matches!(
659        state,
660        PrinterState::Printing | PrinterState::Paused | PrinterState::Cancelling
661    )
662}
663
664/// What one snapshot says the heaters are driving towards.
665fn heated(snapshot: &PrinterSnapshot) -> (Vec<HeatedTool>, Option<f64>) {
666    let tools = snapshot
667        .tools
668        .iter()
669        .enumerate()
670        .filter_map(|(index, heater)| {
671            let target = heater.target_c.as_ref()?.value();
672            (target > 0.0).then(|| HeatedTool {
673                tool: i64::try_from(index).unwrap_or(i64::MAX),
674                target_c: target,
675            })
676        })
677        .collect();
678    let bed = snapshot
679        .bed
680        .as_ref()
681        .and_then(|bed| bed.target_c.as_ref())
682        .map(printobserver_types::Reported::value)
683        .filter(|target| *target > 0.0);
684    (tools, bed)
685}
686
687/// One activity in words.
688fn activity_detail(activity: &Activity, channel_down: bool) -> String {
689    let mut parts: Vec<String> = activity
690        .tools
691        .iter()
692        .map(|tool| format!("tool {} is heating to {} °C", tool.tool, tool.target_c))
693        .collect();
694    if let Some(bed) = activity.bed {
695        parts.push(format!("the bed is heating to {bed} °C"));
696    }
697    match activity.moved {
698        Some(true) => parts.push("the print head moved".to_owned()),
699        Some(false) => {}
700        None => parts.push("the print head's position could not be read".to_owned()),
701    }
702    let mut detail = format!("with no job running, {}", parts.join(", "));
703    if channel_down {
704        detail.push_str("; ");
705        detail.push_str(PUSH_CHANNEL_DOWN);
706    }
707    detail
708}
709
710impl Supervisor {
711    /// What the watch holds, held for one read or write.
712    pub(crate) fn watch_state(&self) -> std::sync::MutexGuard<'_, WatchState> {
713        self.watch
714            .lock()
715            .unwrap_or_else(std::sync::PoisonError::into_inner)
716    }
717
718    /// What the printer pushed since the last print started or was closed out.
719    pub(crate) fn push_facts(&self) -> PushFacts {
720        let state = self.watch_state();
721        let mut facts = state.pushes;
722        facts.gap |= state.channel_is_down();
723        facts
724    }
725
726    /// What the printer pushed, once a reset it may still be pushing for a
727    /// return to idle has had [`RESET_GRACE`] to arrive — at once when the
728    /// push channel is down, since nothing would arrive.
729    pub(crate) async fn pushes_after_a_reset_could_arrive(&self) -> PushFacts {
730        // A wait for something a real socket delivers, so it is measured on
731        // the host's own clock rather than the one supervision is driven by.
732        let started = std::time::Instant::now();
733        loop {
734            let facts = self.push_facts();
735            if facts.reset
736                || self.watch_state().channel_is_down()
737                || started.elapsed() >= RESET_GRACE
738                || crate::delay::Delay::new(Duration::from_millis(50))
739                    .await
740                    .is_err()
741            {
742                return facts;
743            }
744        }
745    }
746
747    /// Close any unattended window: a job is running.
748    pub(crate) fn note_job_running(&self) {
749        self.watch_state().unattended = None;
750    }
751
752    /// Forget what the printer pushed: a print starts, or one's close-out has
753    /// read it.
754    pub(crate) fn forget_pushes(&self) {
755        let mut state = self.watch_state();
756        let gap = state.channel_is_down();
757        state.pushes = PushFacts {
758            gap,
759            ..PushFacts::default()
760        };
761    }
762
763    /// The failure detector's status, for whichever print it is scoring.
764    ///
765    /// Evidence that the detector is scoring a print comes first
766    /// ([`crate::scoring`]); without it, what its health check last found.
767    #[must_use]
768    pub fn detector_health(&self) -> DetectorHealth {
769        self.detector_health_of(None)
770    }
771
772    /// The failure detector's status, as one print's status and context reads
773    /// answer it: scoring only when the evidence is of that print.
774    #[must_use]
775    pub fn detector_health_for(&self, print_id: PrintId) -> DetectorHealth {
776        self.detector_health_of(Some(print_id))
777    }
778
779    /// The failure detector's status, for one print or for whichever print it
780    /// is scoring.
781    fn detector_health_of(&self, print_id: Option<PrintId>) -> DetectorHealth {
782        let window = self
783            .config()
784            .observation_interval
785            .saturating_mul(crate::scoring::EVIDENCE_INTERVALS);
786        let now = self.clock().elapsed();
787        let held = self.watch_state();
788        if let Some(scoring) = held.scoring.scoring(print_id, now, window) {
789            return DetectorHealth::Scoring {
790                since: scoring.since,
791                verdict: scoring.verdict,
792                probe_failure: match &held.probe {
793                    ProbeHealth::Unavailable { detail, .. } => Some(detail.clone()),
794                    ProbeHealth::Unchecked | ProbeHealth::Available { .. } => None,
795                },
796            };
797        }
798        let scoring_unread = held.scoring.unread().map(str::to_owned);
799        match &held.probe {
800            ProbeHealth::Unchecked => DetectorHealth::Unchecked { scoring_unread },
801            ProbeHealth::Available { since } => DetectorHealth::Available {
802                since: *since,
803                scoring_unread,
804            },
805            ProbeHealth::Unavailable { since, .. } => DetectorHealth::Unavailable {
806                since: *since,
807                scoring_unread,
808            },
809        }
810    }
811
812    /// Report that the printer's push channel opened, or why it is down.
813    ///
814    /// While it is down an ending is decided from the printer's state alone,
815    /// and every event the watch writes says so.
816    pub fn note_push_channel(&self, open: Result<(), String>) {
817        let mut state = self.watch_state();
818        match open {
819            Ok(()) => state.channel = Channel::Open,
820            Err(detail) => {
821                state.channel = Channel::Down(detail);
822                state.pushes.gap = true;
823            }
824        }
825    }
826
827    /// Take one thing the printer pushed.
828    ///
829    /// A reset is recorded at once as a [`PrinterResetPayload`], naming the
830    /// print it happened during when one was running; it and an error of the
831    /// printer's own are kept for the close-out of the print they stopped.
832    /// Terminal lines are the server's to read, and are ignored here.
833    ///
834    /// # Errors
835    ///
836    /// Returns the store's own error when the reset could not be recorded.
837    pub async fn note_push(&self, push: PrinterPush) -> Result<(), CoreError> {
838        match push {
839            PrinterPush::Reset => {
840                // A reset forgets where every axis is.
841                self.distrust_z("the printer pushed a reset, and a reset forgets where Z is");
842                // Which print was running is read before the close-out is told
843                // of the reset: told first, it can close that print while the
844                // read is still waiting on the store, and the reset would then
845                // name no print. A close-out that reads the machine idle first
846                // waits `RESET_GRACE` for this flag, so setting it a moment
847                // later still reaches it.
848                let running = self.running_print().await;
849                self.watch_state().pushes.reset = true;
850                // A reset is recorded whatever the store answers about which
851                // print was running: the push is not sent again.
852                let (during_print, detail) = match running {
853                    Ok(Some(print)) => (
854                        Some(print.id),
855                        format!("the printer pushed a reset during print {}", print.id),
856                    ),
857                    Ok(None) => (
858                        None,
859                        "the printer pushed a reset while no print was running".to_owned(),
860                    ),
861                    Err(error) => (
862                        None,
863                        format!(
864                            "the printer pushed a reset; which print was running could not be \
865                             read: {error}"
866                        ),
867                    ),
868                };
869                let payload = PrinterResetPayload {
870                    during_print,
871                    detail,
872                };
873                if let Err(error) = self.write_reset(&payload).await {
874                    // The push is not sent again, so what it said is kept for
875                    // the next round to write down.
876                    self.watch_state().pending_resets.push(payload);
877                    return Err(error);
878                }
879                Ok(())
880            }
881            PrinterPush::Error {
882                reason: PrinterErrorReason::Firmware,
883            } => {
884                self.watch_state().pushes.firmware_error = true;
885                Ok(())
886            }
887            PrinterPush::Error {
888                reason: PrinterErrorReason::Other(_),
889            }
890            | PrinterPush::Log { .. } => Ok(()),
891        }
892    }
893
894    /// Write one reset down.
895    async fn write_reset(&self, payload: &PrinterResetPayload) -> Result<(), CoreError> {
896        let draft = self.draft_of(None, system_source(), payload)?;
897        self.stores().events.append_event(draft).await?;
898        Ok(())
899    }
900
901    /// Write down what an earlier round could not: the resets the store
902    /// refused, the follow-up of endings and the activity turns it would not
903    /// answer for. Each still refused is kept for the round after.
904    async fn catch_up(&self) {
905        let resets = std::mem::take(&mut self.watch_state().pending_resets);
906        for payload in resets {
907            if self.write_reset(&payload).await.is_err() {
908                self.watch_state().pending_resets.push(payload);
909            }
910        }
911        let ends = std::mem::take(&mut self.watch_state().pending_ends);
912        for print_id in ends {
913            if self.after_close_out(print_id).await.is_err() {
914                self.watch_state().pending_ends.push(print_id);
915            }
916        }
917        let claims = std::mem::take(&mut self.watch_state().pending_claims);
918        for (print_id, event) in claims {
919            self.claim_activity_turn(print_id, event).await;
920        }
921    }
922
923    /// Follow up one print's close-out, or keep it for the next round when the
924    /// store will not answer.
925    pub(crate) async fn follow_up_end(&self, print_id: PrintId) {
926        if self.after_close_out(print_id).await.is_err() {
927            self.watch_state().pending_ends.push(print_id);
928        }
929    }
930
931    /// The open print this supervisor last saw running, when there is one.
932    async fn running_print(&self) -> Result<Option<PrintRecord>, CoreError> {
933        Ok(self
934            .stores()
935            .prints
936            .open_prints()
937            .await?
938            .into_iter()
939            .find(|print| self.was_seen_running(print.id)))
940    }
941
942    /// Read the machine once, record what changed, and answer the turns that
943    /// claimed.
944    ///
945    /// A printer whose job cannot be read changes nothing: an instance that
946    /// does not answer says nothing about the machine behind it.
947    ///
948    /// # Errors
949    ///
950    /// Returns the store's own error when what changed could not be recorded.
951    pub async fn watch_printer(&self, probe: &dyn PositionProbe) -> Result<Watched, CoreError> {
952        self.catch_up().await;
953        let resolving = self.resolving().await;
954        let observed = self.observe_job().await;
955        let mut active = None;
956        if let Some(observed) = &observed {
957            self.note_connection(
958                &observed.job.state,
959                observed.job.error.as_ref().map(|error| error.text.as_str()),
960            )
961            .await?;
962            active = self
963                .settle_and_adopt(observed)
964                .await?
965                .map(|print_id| ActiveJob {
966                    print_id,
967                    file_position_bytes: observed.job.file_position_bytes,
968                });
969        }
970        drop(resolving);
971        if let Some(observed) = &observed {
972            self.watch_unattended(observed, probe).await?;
973            if let Some(active) = &active
974                && let Some(print) = self.stores().prints.print(active.print_id).await?
975                && let Some(turn) = self
976                    .follow_planned_changes(&print, &observed.job, true)
977                    .await?
978            {
979                self.watch_state().pending_turns.push(turn);
980            }
981        }
982        Ok(Watched {
983            turns: std::mem::take(&mut self.watch_state().pending_turns),
984            active,
985        })
986    }
987
988    /// Record a change of the printer's state into or out of `offline` or
989    /// `error`.
990    async fn note_connection(
991        &self,
992        state: &PrinterState,
993        error: Option<&str>,
994    ) -> Result<(), CoreError> {
995        let (previous, channel_down) = {
996            let held = self.watch_state();
997            (held.last_state.clone(), held.channel_is_down())
998        };
999        if is_down(state) && previous.as_ref() != Some(state) {
1000            // A printer that went offline or into error may have been
1001            // reset, moved or powered off since: where Z is is unknown.
1002            self.distrust_z(format!(
1003                "the printer went {state:?}, and Z may have moved since"
1004            ));
1005        }
1006        let changed = previous
1007            .as_ref()
1008            .filter(|previous| *previous != state && (is_down(previous) || is_down(state)));
1009        if let Some(previous) = changed {
1010            let reporting = error
1011                .filter(|error| !error.trim().is_empty())
1012                .map(|error| format!(", reporting {error:?}"))
1013                .unwrap_or_default();
1014            let mut detail = format!("the printer went from {previous:?} to {state:?}{reporting}");
1015            if channel_down {
1016                detail.push_str("; ");
1017                detail.push_str(PUSH_CHANNEL_DOWN);
1018            }
1019            let draft = self.draft_of(
1020                None,
1021                system_source(),
1022                &PrinterConnectionChangedPayload {
1023                    from: previous.clone(),
1024                    to: state.clone(),
1025                    detail,
1026                },
1027            )?;
1028            // Remembered only once it is written down: a change the store
1029            // refused is found again by the next read.
1030            self.stores().events.append_event(draft).await?;
1031        }
1032        self.watch_state().last_state = Some(state.clone());
1033        Ok(())
1034    }
1035
1036    /// What follows a print's close-out: an `interrupted` or `failed` ending
1037    /// opens the unattended window and claims its agent a turn on the
1038    /// `print_ended`; any other ending closes the window.
1039    async fn after_close_out(&self, print_id: PrintId) -> Result<(), CoreError> {
1040        self.forget_pushes();
1041        let Some(ended) = self
1042            .stores()
1043            .events
1044            .history(HistoryQuery {
1045                print_id,
1046                kinds: vec![PrintEndedPayload::kind()],
1047                since: None,
1048                until: None,
1049                limit: Some(1),
1050            })
1051            .await?
1052            .into_iter()
1053            .next()
1054        else {
1055            return Ok(());
1056        };
1057        let Some(Ok(payload)) = ended.payload_as::<PrintEndedPayload>() else {
1058            return Ok(());
1059        };
1060        if !matches!(
1061            payload.outcome,
1062            PrintOutcome::Interrupted | PrintOutcome::Failed
1063        ) {
1064            self.watch_state().unattended = None;
1065            return Ok(());
1066        }
1067        self.distrust_z(format!(
1068            "print {print_id} ended {}, and where it left Z is unknown",
1069            if payload.outcome == PrintOutcome::Failed {
1070                "failed"
1071            } else {
1072                "interrupted"
1073            }
1074        ));
1075        self.watch_state().unattended = Some(Unattended {
1076            print_id,
1077            began: self.clock().elapsed(),
1078            recorded: None,
1079            position: None,
1080            turned_at: None,
1081        });
1082        self.claim_after_end(print_id, ended).await
1083    }
1084
1085    /// Claim one ended print's agent a turn on one event about its end, or
1086    /// hand the event to the turn already running for it.
1087    async fn claim_after_end(
1088        &self,
1089        print_id: PrintId,
1090        event: EventRecord,
1091    ) -> Result<(), CoreError> {
1092        let Some(print) = self.stores().prints.print(print_id).await? else {
1093            return Ok(());
1094        };
1095        let arrival = Arrival {
1096            frame_captured_at: None,
1097            event,
1098            detection: None,
1099            camera_frame: crate::inbox::AlertCameraFrame::NotAsked,
1100        };
1101        if self.inboxes().claim_or_hand_over(print_id, arrival.clone()) {
1102            self.watch_state()
1103                .pending_turns
1104                .push(PendingTurn::new(print, arrival, Vec::new()));
1105        }
1106        Ok(())
1107    }
1108
1109    /// Record the printer acting on its own, while the unattended window is
1110    /// open and no job runs.
1111    async fn watch_unattended(
1112        &self,
1113        observed: &ObservedJob,
1114        probe: &dyn PositionProbe,
1115    ) -> Result<(), CoreError> {
1116        let window = self.config().unattended_window;
1117        let now = self.clock().elapsed();
1118        let (print_id, last_position, channel_down) = {
1119            let mut held = self.watch_state();
1120            let Some(open) = &held.unattended else {
1121                return Ok(());
1122            };
1123            if now.saturating_sub(open.began) > window {
1124                held.unattended = None;
1125                return Ok(());
1126            }
1127            (open.print_id, open.position, held.channel_is_down())
1128        };
1129        if job_runs(&observed.job.state) || is_down(&observed.job.state) {
1130            return Ok(());
1131        }
1132        let Ok(snapshot) = self.read_snapshot().await else {
1133            return Ok(());
1134        };
1135        if job_runs(&snapshot.connection) || is_down(&snapshot.connection) {
1136            return Ok(());
1137        }
1138        let (tools, bed) = heated(&snapshot);
1139        let position = probe.read_position().await;
1140        let moved = match (last_position, position) {
1141            (_, None) => None,
1142            (None, Some(_)) => Some(false),
1143            (Some(before), Some(after)) => Some(before != after),
1144        };
1145        let activity = Activity { tools, bed, moved };
1146        let unchanged = {
1147            let mut held = self.watch_state();
1148            let Some(open) = held
1149                .unattended
1150                .as_mut()
1151                .filter(|open| open.print_id == print_id)
1152            else {
1153                return Ok(());
1154            };
1155            if position.is_some() {
1156                open.position = position;
1157            }
1158            if !activity.is_active() {
1159                open.recorded = None;
1160                return Ok(());
1161            }
1162            open.recorded.as_ref() == Some(&activity)
1163        };
1164        if unchanged {
1165            return Ok(());
1166        }
1167        let draft = self.draft_of(
1168            None,
1169            system_source(),
1170            &UnattendedPrinterActivityPayload {
1171                last_print_id: print_id,
1172                tools: activity.tools.clone(),
1173                bed_target_c: activity.bed,
1174                moved: activity.moved,
1175                detail: activity_detail(&activity, channel_down),
1176            },
1177        )?;
1178        let event = self.stores().events.append_event(draft).await?;
1179        let interval = self.config().observation_interval;
1180        let turn_due = {
1181            let mut held = self.watch_state();
1182            let Some(open) = held.unattended.as_mut() else {
1183                return Ok(());
1184            };
1185            // Remembered only once it is written down: activity the store
1186            // refused is found again by the next read.
1187            open.recorded = Some(activity.clone());
1188            open.turned_at
1189                .is_none_or(|turned| now.saturating_sub(turned) >= interval)
1190        };
1191        if turn_due {
1192            self.claim_activity_turn(print_id, event).await;
1193        }
1194        Ok(())
1195    }
1196
1197    /// Claim the turn one activity owes its print's agent, counting it against
1198    /// the interval once it is claimed; one the store would not answer for is
1199    /// kept for the next round to claim.
1200    async fn claim_activity_turn(&self, print_id: PrintId, event: EventRecord) {
1201        if self.claim_after_end(print_id, event.clone()).await.is_err() {
1202            self.watch_state().pending_claims.push((print_id, event));
1203            return;
1204        }
1205        let now = self.clock().elapsed();
1206        if let Some(open) = self
1207            .watch_state()
1208            .unattended
1209            .as_mut()
1210            .filter(|open| open.print_id == print_id)
1211        {
1212            open.turned_at = Some(now);
1213        }
1214    }
1215
1216    /// Ask the failure detector whether it is answering, during a print, and
1217    /// record each change; going unavailable claims the active print's agent a
1218    /// turn — unless the detector is scoring that print, when its failing
1219    /// health check is recorded as a port failure against the change instead,
1220    /// and the print is still watched.
1221    ///
1222    /// No print open, no check: a detector nobody needs is not one to
1223    /// record.
1224    ///
1225    /// # Errors
1226    ///
1227    /// Returns the store's own error when a change could not be recorded.
1228    pub async fn check_detector(
1229        &self,
1230        probe: &dyn DetectorProbe,
1231    ) -> Result<Option<PendingTurn>, CoreError> {
1232        let Some(print) = self.stores().prints.open_prints().await?.into_iter().next() else {
1233            return Ok(None);
1234        };
1235        let (status, detail) = match probe.check().await {
1236            Ok(detail) => (DetectorStatus::Available, detail),
1237            Err(detail) => (DetectorStatus::Unavailable, detail),
1238        };
1239        let health = match status {
1240            DetectorStatus::Available => DetectorHealthStatus::Available,
1241            DetectorStatus::Unavailable => DetectorHealthStatus::Unavailable,
1242        };
1243        let previous = self.watch_state().probe.status();
1244        if previous == health {
1245            // The failure the status names beside a scoring detector is the
1246            // latest one it was answered.
1247            if let ProbeHealth::Unavailable { detail: held, .. } = &mut self.watch_state().probe {
1248                held.clone_from(&detail);
1249            }
1250            return Ok(None);
1251        }
1252        let since = self.clock().now();
1253        let found = match status {
1254            DetectorStatus::Available => ProbeHealth::Available { since },
1255            DetectorStatus::Unavailable => ProbeHealth::Unavailable {
1256                since,
1257                detail: detail.clone(),
1258            },
1259        };
1260        // The first check finding the detector up is where watching it begins,
1261        // not a change in it.
1262        if previous == DetectorHealthStatus::Unchecked && health == DetectorHealthStatus::Available
1263        {
1264            self.watch_state().probe = found;
1265            return Ok(None);
1266        }
1267        let draft = self.draft_of(
1268            None,
1269            system_source(),
1270            &DetectorHealthChangedPayload {
1271                status,
1272                detail: detail.clone(),
1273            },
1274        )?;
1275        let event = self.stores().events.append_event(draft).await?;
1276        // Remembered only once it is written down: a change the store refused
1277        // is found again by the next check.
1278        self.watch_state().probe = found;
1279        if status != DetectorStatus::Unavailable {
1280            return Ok(None);
1281        }
1282        if matches!(
1283            self.detector_health_for(print.id),
1284            DetectorHealth::Scoring { .. }
1285        ) {
1286            // The detector is still scoring the print, so the print is still
1287            // watched: the failing check is a port that failed, not an outage.
1288            self.record_port_failure_to(
1289                None,
1290                event.id,
1291                PortFailureSite::DetectorHealthCheck,
1292                detail,
1293            )
1294            .await;
1295            return Ok(None);
1296        }
1297        if !self.turns_allowed(print.id).await? {
1298            return Ok(None);
1299        }
1300        let arrival = Arrival {
1301            frame_captured_at: None,
1302            event,
1303            detection: None,
1304            camera_frame: crate::inbox::AlertCameraFrame::NotAsked,
1305        };
1306        Ok(self
1307            .inboxes()
1308            .claim_or_hand_over(print.id, arrival.clone())
1309            .then(|| PendingTurn::new(print, arrival, Vec::new())))
1310    }
1311}
1312
1313/// The kinds a print that has ended is still given a turn on: how it ended,
1314/// and what the printer did on its own after.
1315pub(crate) fn concerns_its_end(kind: &EventKind) -> bool {
1316    [
1317        PrintEndedPayload::KIND,
1318        UnattendedPrinterActivityPayload::KIND,
1319    ]
1320    .contains(&kind.as_str())
1321}
1322
1323/// What a print carrying on from a planned change says: which colour is now
1324/// expected, from which layer, and what came before it.
1325fn resumed_noticed(resumed: &crate::kinds::FilamentChangePlannedResumedPayload) -> String {
1326    let named = |colour: Option<&str>| {
1327        colour.map_or_else(
1328            || "a colour the file does not name".to_owned(),
1329            str::to_owned,
1330        )
1331    };
1332    let change = &resumed.change;
1333    let what = match change.kind {
1334        crate::gcode_index::PlannedChangeKind::ColorChange => "colour change",
1335        crate::gcode_index::PlannedChangeKind::Pause => "pause",
1336    };
1337    format!(
1338        "{}: the print carried on from planned {what} {} after waiting {} s; the expected colour \
1339         is {} from layer {} (Z {} mm) up, and the colour before it was {}",
1340        crate::kinds::FilamentChangePlannedResumedPayload::KIND,
1341        change.index,
1342        resumed.waited_s,
1343        named(change.color.as_deref()),
1344        change.layer,
1345        change.z_mm,
1346        named(resumed.previous_color.as_deref()),
1347    )
1348}
1349
1350/// What one event says the watch noticed, in words, for the situation of the
1351/// turn it prompts; nothing for an event the watch did not raise.
1352pub(crate) fn noticed_of(event: &EventRecord) -> Option<String> {
1353    if let Some(Ok(ended)) = event.payload_as::<PrintEndedPayload>() {
1354        let outcome = match ended.outcome {
1355            PrintOutcome::Interrupted => "interrupted",
1356            PrintOutcome::Failed => "failed",
1357            PrintOutcome::Completed | PrintOutcome::Cancelled => return None,
1358        };
1359        return Some(format!(
1360            "{}: the print ended {outcome}, the printer reporting {:?} ({})",
1361            PrintEndedPayload::KIND,
1362            ended.state,
1363            ended.reason
1364        ));
1365    }
1366    if let Some(Ok(activity)) = event.payload_as::<UnattendedPrinterActivityPayload>() {
1367        return Some(format!(
1368            "{}: after print {} ended, {}",
1369            UnattendedPrinterActivityPayload::KIND,
1370            activity.last_print_id,
1371            activity.detail
1372        ));
1373    }
1374    if let Some(Ok(degraded)) = event.payload_as::<crate::kinds::CameraDegradedPayload>() {
1375        return Some(format!(
1376            "{}: the camera gave no usable frame in {} attempts, so there is no frame to look \
1377             at: {}",
1378            crate::kinds::CameraDegradedPayload::KIND,
1379            degraded.attempts,
1380            degraded.detail
1381        ));
1382    }
1383    if let Some(Ok(resumed)) =
1384        event.payload_as::<crate::kinds::FilamentChangePlannedResumedPayload>()
1385    {
1386        return Some(resumed_noticed(&resumed));
1387    }
1388    if let Some(Ok(health)) = event.payload_as::<DetectorHealthChangedPayload>() {
1389        return Some(format!(
1390            "{}: the failure detector is {:?}, so nothing is watching the print for failures: {}",
1391            DetectorHealthChangedPayload::KIND,
1392            health.status,
1393            health.detail
1394        ));
1395    }
1396    None
1397}