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        }
974        Ok(Watched {
975            turns: std::mem::take(&mut self.watch_state().pending_turns),
976            active,
977        })
978    }
979
980    /// Record a change of the printer's state into or out of `offline` or
981    /// `error`.
982    async fn note_connection(
983        &self,
984        state: &PrinterState,
985        error: Option<&str>,
986    ) -> Result<(), CoreError> {
987        let (previous, channel_down) = {
988            let held = self.watch_state();
989            (held.last_state.clone(), held.channel_is_down())
990        };
991        if is_down(state) && previous.as_ref() != Some(state) {
992            // A printer that went offline or into error may have been
993            // reset, moved or powered off since: where Z is is unknown.
994            self.distrust_z(format!(
995                "the printer went {state:?}, and Z may have moved since"
996            ));
997        }
998        let changed = previous
999            .as_ref()
1000            .filter(|previous| *previous != state && (is_down(previous) || is_down(state)));
1001        if let Some(previous) = changed {
1002            let reporting = error
1003                .filter(|error| !error.trim().is_empty())
1004                .map(|error| format!(", reporting {error:?}"))
1005                .unwrap_or_default();
1006            let mut detail = format!("the printer went from {previous:?} to {state:?}{reporting}");
1007            if channel_down {
1008                detail.push_str("; ");
1009                detail.push_str(PUSH_CHANNEL_DOWN);
1010            }
1011            let draft = self.draft_of(
1012                None,
1013                system_source(),
1014                &PrinterConnectionChangedPayload {
1015                    from: previous.clone(),
1016                    to: state.clone(),
1017                    detail,
1018                },
1019            )?;
1020            // Remembered only once it is written down: a change the store
1021            // refused is found again by the next read.
1022            self.stores().events.append_event(draft).await?;
1023        }
1024        self.watch_state().last_state = Some(state.clone());
1025        Ok(())
1026    }
1027
1028    /// What follows a print's close-out: an `interrupted` or `failed` ending
1029    /// opens the unattended window and claims its agent a turn on the
1030    /// `print_ended`; any other ending closes the window.
1031    async fn after_close_out(&self, print_id: PrintId) -> Result<(), CoreError> {
1032        self.forget_pushes();
1033        let Some(ended) = self
1034            .stores()
1035            .events
1036            .history(HistoryQuery {
1037                print_id,
1038                kinds: vec![PrintEndedPayload::kind()],
1039                since: None,
1040                until: None,
1041                limit: Some(1),
1042            })
1043            .await?
1044            .into_iter()
1045            .next()
1046        else {
1047            return Ok(());
1048        };
1049        let Some(Ok(payload)) = ended.payload_as::<PrintEndedPayload>() else {
1050            return Ok(());
1051        };
1052        if !matches!(
1053            payload.outcome,
1054            PrintOutcome::Interrupted | PrintOutcome::Failed
1055        ) {
1056            self.watch_state().unattended = None;
1057            return Ok(());
1058        }
1059        self.distrust_z(format!(
1060            "print {print_id} ended {}, and where it left Z is unknown",
1061            if payload.outcome == PrintOutcome::Failed {
1062                "failed"
1063            } else {
1064                "interrupted"
1065            }
1066        ));
1067        self.watch_state().unattended = Some(Unattended {
1068            print_id,
1069            began: self.clock().elapsed(),
1070            recorded: None,
1071            position: None,
1072            turned_at: None,
1073        });
1074        self.claim_after_end(print_id, ended).await
1075    }
1076
1077    /// Claim one ended print's agent a turn on one event about its end, or
1078    /// hand the event to the turn already running for it.
1079    async fn claim_after_end(
1080        &self,
1081        print_id: PrintId,
1082        event: EventRecord,
1083    ) -> Result<(), CoreError> {
1084        let Some(print) = self.stores().prints.print(print_id).await? else {
1085            return Ok(());
1086        };
1087        let arrival = Arrival {
1088            frame_captured_at: None,
1089            event,
1090            detection: None,
1091        };
1092        if self.inboxes().claim_or_hand_over(print_id, arrival.clone()) {
1093            self.watch_state()
1094                .pending_turns
1095                .push(PendingTurn::new(print, arrival, Vec::new()));
1096        }
1097        Ok(())
1098    }
1099
1100    /// Record the printer acting on its own, while the unattended window is
1101    /// open and no job runs.
1102    async fn watch_unattended(
1103        &self,
1104        observed: &ObservedJob,
1105        probe: &dyn PositionProbe,
1106    ) -> Result<(), CoreError> {
1107        let window = self.config().unattended_window;
1108        let now = self.clock().elapsed();
1109        let (print_id, last_position, channel_down) = {
1110            let mut held = self.watch_state();
1111            let Some(open) = &held.unattended else {
1112                return Ok(());
1113            };
1114            if now.saturating_sub(open.began) > window {
1115                held.unattended = None;
1116                return Ok(());
1117            }
1118            (open.print_id, open.position, held.channel_is_down())
1119        };
1120        if job_runs(&observed.job.state) || is_down(&observed.job.state) {
1121            return Ok(());
1122        }
1123        let Ok(snapshot) = self.read_snapshot().await else {
1124            return Ok(());
1125        };
1126        if job_runs(&snapshot.connection) || is_down(&snapshot.connection) {
1127            return Ok(());
1128        }
1129        let (tools, bed) = heated(&snapshot);
1130        let position = probe.read_position().await;
1131        let moved = match (last_position, position) {
1132            (_, None) => None,
1133            (None, Some(_)) => Some(false),
1134            (Some(before), Some(after)) => Some(before != after),
1135        };
1136        let activity = Activity { tools, bed, moved };
1137        let unchanged = {
1138            let mut held = self.watch_state();
1139            let Some(open) = held
1140                .unattended
1141                .as_mut()
1142                .filter(|open| open.print_id == print_id)
1143            else {
1144                return Ok(());
1145            };
1146            if position.is_some() {
1147                open.position = position;
1148            }
1149            if !activity.is_active() {
1150                open.recorded = None;
1151                return Ok(());
1152            }
1153            open.recorded.as_ref() == Some(&activity)
1154        };
1155        if unchanged {
1156            return Ok(());
1157        }
1158        let draft = self.draft_of(
1159            None,
1160            system_source(),
1161            &UnattendedPrinterActivityPayload {
1162                last_print_id: print_id,
1163                tools: activity.tools.clone(),
1164                bed_target_c: activity.bed,
1165                moved: activity.moved,
1166                detail: activity_detail(&activity, channel_down),
1167            },
1168        )?;
1169        let event = self.stores().events.append_event(draft).await?;
1170        let interval = self.config().observation_interval;
1171        let turn_due = {
1172            let mut held = self.watch_state();
1173            let Some(open) = held.unattended.as_mut() else {
1174                return Ok(());
1175            };
1176            // Remembered only once it is written down: activity the store
1177            // refused is found again by the next read.
1178            open.recorded = Some(activity.clone());
1179            open.turned_at
1180                .is_none_or(|turned| now.saturating_sub(turned) >= interval)
1181        };
1182        if turn_due {
1183            self.claim_activity_turn(print_id, event).await;
1184        }
1185        Ok(())
1186    }
1187
1188    /// Claim the turn one activity owes its print's agent, counting it against
1189    /// the interval once it is claimed; one the store would not answer for is
1190    /// kept for the next round to claim.
1191    async fn claim_activity_turn(&self, print_id: PrintId, event: EventRecord) {
1192        if self.claim_after_end(print_id, event.clone()).await.is_err() {
1193            self.watch_state().pending_claims.push((print_id, event));
1194            return;
1195        }
1196        let now = self.clock().elapsed();
1197        if let Some(open) = self
1198            .watch_state()
1199            .unattended
1200            .as_mut()
1201            .filter(|open| open.print_id == print_id)
1202        {
1203            open.turned_at = Some(now);
1204        }
1205    }
1206
1207    /// Ask the failure detector whether it is answering, during a print, and
1208    /// record each change; going unavailable claims the active print's agent a
1209    /// turn — unless the detector is scoring that print, when its failing
1210    /// health check is recorded as a port failure against the change instead,
1211    /// and the print is still watched.
1212    ///
1213    /// No print open, no check: a detector nobody needs is not one to
1214    /// record.
1215    ///
1216    /// # Errors
1217    ///
1218    /// Returns the store's own error when a change could not be recorded.
1219    pub async fn check_detector(
1220        &self,
1221        probe: &dyn DetectorProbe,
1222    ) -> Result<Option<PendingTurn>, CoreError> {
1223        let Some(print) = self.stores().prints.open_prints().await?.into_iter().next() else {
1224            return Ok(None);
1225        };
1226        let (status, detail) = match probe.check().await {
1227            Ok(detail) => (DetectorStatus::Available, detail),
1228            Err(detail) => (DetectorStatus::Unavailable, detail),
1229        };
1230        let health = match status {
1231            DetectorStatus::Available => DetectorHealthStatus::Available,
1232            DetectorStatus::Unavailable => DetectorHealthStatus::Unavailable,
1233        };
1234        let previous = self.watch_state().probe.status();
1235        if previous == health {
1236            // The failure the status names beside a scoring detector is the
1237            // latest one it was answered.
1238            if let ProbeHealth::Unavailable { detail: held, .. } = &mut self.watch_state().probe {
1239                held.clone_from(&detail);
1240            }
1241            return Ok(None);
1242        }
1243        let since = self.clock().now();
1244        let found = match status {
1245            DetectorStatus::Available => ProbeHealth::Available { since },
1246            DetectorStatus::Unavailable => ProbeHealth::Unavailable {
1247                since,
1248                detail: detail.clone(),
1249            },
1250        };
1251        // The first check finding the detector up is where watching it begins,
1252        // not a change in it.
1253        if previous == DetectorHealthStatus::Unchecked && health == DetectorHealthStatus::Available
1254        {
1255            self.watch_state().probe = found;
1256            return Ok(None);
1257        }
1258        let draft = self.draft_of(
1259            None,
1260            system_source(),
1261            &DetectorHealthChangedPayload {
1262                status,
1263                detail: detail.clone(),
1264            },
1265        )?;
1266        let event = self.stores().events.append_event(draft).await?;
1267        // Remembered only once it is written down: a change the store refused
1268        // is found again by the next check.
1269        self.watch_state().probe = found;
1270        if status != DetectorStatus::Unavailable {
1271            return Ok(None);
1272        }
1273        if matches!(
1274            self.detector_health_for(print.id),
1275            DetectorHealth::Scoring { .. }
1276        ) {
1277            // The detector is still scoring the print, so the print is still
1278            // watched: the failing check is a port that failed, not an outage.
1279            self.record_port_failure_to(
1280                None,
1281                event.id,
1282                PortFailureSite::DetectorHealthCheck,
1283                detail,
1284            )
1285            .await;
1286            return Ok(None);
1287        }
1288        let arrival = Arrival {
1289            frame_captured_at: None,
1290            event,
1291            detection: None,
1292        };
1293        Ok(self
1294            .inboxes()
1295            .claim_or_hand_over(print.id, arrival.clone())
1296            .then(|| PendingTurn::new(print, arrival, Vec::new())))
1297    }
1298}
1299
1300/// The kinds a print that has ended is still given a turn on: how it ended,
1301/// and what the printer did on its own after.
1302pub(crate) fn concerns_its_end(kind: &EventKind) -> bool {
1303    [
1304        PrintEndedPayload::KIND,
1305        UnattendedPrinterActivityPayload::KIND,
1306    ]
1307    .contains(&kind.as_str())
1308}
1309
1310/// What one event says the watch noticed, in words, for the situation of the
1311/// turn it prompts; nothing for an event the watch did not raise.
1312pub(crate) fn noticed_of(event: &EventRecord) -> Option<String> {
1313    if let Some(Ok(ended)) = event.payload_as::<PrintEndedPayload>() {
1314        let outcome = match ended.outcome {
1315            PrintOutcome::Interrupted => "interrupted",
1316            PrintOutcome::Failed => "failed",
1317            PrintOutcome::Completed | PrintOutcome::Cancelled => return None,
1318        };
1319        return Some(format!(
1320            "{}: the print ended {outcome}, the printer reporting {:?} ({})",
1321            PrintEndedPayload::KIND,
1322            ended.state,
1323            ended.reason
1324        ));
1325    }
1326    if let Some(Ok(activity)) = event.payload_as::<UnattendedPrinterActivityPayload>() {
1327        return Some(format!(
1328            "{}: after print {} ended, {}",
1329            UnattendedPrinterActivityPayload::KIND,
1330            activity.last_print_id,
1331            activity.detail
1332        ));
1333    }
1334    if let Some(Ok(degraded)) = event.payload_as::<crate::kinds::CameraDegradedPayload>() {
1335        return Some(format!(
1336            "{}: the camera gave no usable frame in {} attempts, so there is no frame to look \
1337             at: {}",
1338            crate::kinds::CameraDegradedPayload::KIND,
1339            degraded.attempts,
1340            degraded.detail
1341        ));
1342    }
1343    if let Some(Ok(health)) = event.payload_as::<DetectorHealthChangedPayload>() {
1344        return Some(format!(
1345            "{}: the failure detector is {:?}, so nothing is watching the print for failures: {}",
1346            DetectorHealthChangedPayload::KIND,
1347            health.status,
1348            health.detail
1349        ));
1350    }
1351    None
1352}