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