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, 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 health, as the last check found 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    /// It answered its health check.
135    Available,
136    /// It did not.
137    Unavailable,
138    /// Nothing checks it: no detector health address is configured, or no
139    /// check has been made yet.
140    #[default]
141    Unchecked,
142}
143
144/// The failure detector's health, and since when it has been so.
145///
146/// Three states and no fourth: a detector nobody has checked has no "since",
147/// and one that was checked always has one. On the wire it is the object the
148/// status and context reads answer — `status`, and `since` that is `null`
149/// exactly when the status is `unchecked` — and an object pairing them any
150/// other way is refused rather than read.
151#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
152pub enum DetectorHealth {
153    /// Nothing checks it: no detector health address is configured, or no
154    /// check has been made yet.
155    #[default]
156    Unchecked,
157    /// It answered its health check, from this instant on.
158    Available {
159        /// When it was first found answering.
160        since: Timestamp,
161    },
162    /// It did not, from this instant on.
163    Unavailable {
164        /// When it was first found not answering.
165        since: Timestamp,
166    },
167}
168
169impl DetectorHealth {
170    /// What the last check found.
171    #[must_use]
172    pub const fn status(&self) -> DetectorHealthStatus {
173        match self {
174            Self::Unchecked => DetectorHealthStatus::Unchecked,
175            Self::Available { .. } => DetectorHealthStatus::Available,
176            Self::Unavailable { .. } => DetectorHealthStatus::Unavailable,
177        }
178    }
179}
180
181/// The failure detector's health as the wire carries it.
182#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
183#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
184struct DetectorHealthWire {
185    /// What the last check found.
186    status: DetectorHealthStatus,
187    /// When the status became what it is, `null` exactly while unchecked —
188    /// and always present, as the schema requires.
189    #[serde(deserialize_with = "present")]
190    since: Option<Timestamp>,
191}
192
193/// Read a value that may be `null` but may not be missing: serde reads a
194/// missing optional as `None` unless it is read through a function of its own.
195fn present<'de, D: printobserver_types::serde::Deserializer<'de>>(
196    deserializer: D,
197) -> Result<Option<Timestamp>, D::Error> {
198    Option::deserialize(deserializer)
199}
200
201impl From<DetectorHealth> for DetectorHealthWire {
202    fn from(health: DetectorHealth) -> Self {
203        let since = match health {
204            DetectorHealth::Unchecked => None,
205            DetectorHealth::Available { since } | DetectorHealth::Unavailable { since } => {
206                Some(since)
207            }
208        };
209        Self {
210            status: health.status(),
211            since,
212        }
213    }
214}
215
216impl TryFrom<DetectorHealthWire> for DetectorHealth {
217    type Error = &'static str;
218
219    fn try_from(wire: DetectorHealthWire) -> Result<Self, Self::Error> {
220        match (wire.status, wire.since) {
221            (DetectorHealthStatus::Unchecked, None) => Ok(Self::Unchecked),
222            (DetectorHealthStatus::Available, Some(since)) => Ok(Self::Available { since }),
223            (DetectorHealthStatus::Unavailable, Some(since)) => Ok(Self::Unavailable { since }),
224            (DetectorHealthStatus::Unchecked, Some(_)) => {
225                Err("an unchecked detector has no instant it became so")
226            }
227            (_, None) => Err("a checked detector carries the instant it became so"),
228        }
229    }
230}
231
232impl Serialize for DetectorHealth {
233    fn serialize<S: printobserver_types::serde::Serializer>(
234        &self,
235        serializer: S,
236    ) -> Result<S::Ok, S::Error> {
237        DetectorHealthWire::from(*self).serialize(serializer)
238    }
239}
240
241impl<'de> Deserialize<'de> for DetectorHealth {
242    fn deserialize<D: printobserver_types::serde::Deserializer<'de>>(
243        deserializer: D,
244    ) -> Result<Self, D::Error> {
245        let wire = DetectorHealthWire::deserialize(deserializer)?;
246        Self::try_from(wire).map_err(printobserver_types::serde::de::Error::custom)
247    }
248}
249
250/// One arm of the detector's health as a schema: its status, and its `since`.
251fn health_arm(
252    status: &str,
253    doc: &str,
254    since: &printobserver_types::serde_json::Value,
255) -> printobserver_types::serde_json::Value {
256    printobserver_types::serde_json::json!({
257        "type": "object",
258        "description": doc,
259        "properties": {
260            "status": { "type": "string", "const": status },
261            "since": since,
262        },
263        "required": ["status", "since"],
264        "additionalProperties": false,
265    })
266}
267
268/// The schema describes the three states as arms tagged by `status`, so a
269/// generated client cannot pair a status with the wrong `since` either.
270impl JsonSchema for DetectorHealth {
271    fn schema_name() -> std::borrow::Cow<'static, str> {
272        std::borrow::Cow::Borrowed("DetectorHealth")
273    }
274
275    fn json_schema(
276        generator: &mut printobserver_types::schemars::SchemaGenerator,
277    ) -> printobserver_types::schemars::Schema {
278        let timestamp =
279            printobserver_types::serde_json::to_value(generator.subschema_for::<Timestamp>())
280                .unwrap_or_default();
281        let schema = printobserver_types::serde_json::json!({
282            "title": "DetectorHealth",
283            "description": "The failure detector's health, and since when it has been so: \
284                `since` is `null` exactly while the status is `unchecked`.",
285            "oneOf": [
286                health_arm(
287                    "unchecked",
288                    "Nothing checks it: no detector health address is configured, or no \
289                     check has been made yet.",
290                    &printobserver_types::serde_json::json!({
291                        "type": "null",
292                        "description": "Nothing: an unchecked detector has no instant it became so.",
293                    }),
294                ),
295                health_arm(
296                    "available",
297                    "It answered its health check, from `since` on.",
298                    &timestamp,
299                ),
300                health_arm(
301                    "unavailable",
302                    "It did not answer its health check, from `since` on.",
303                    &timestamp,
304                ),
305            ],
306        });
307        printobserver_types::schemars::Schema::try_from(schema).unwrap_or_default()
308    }
309}
310
311impl Sample for DetectorHealth {
312    fn sample_full() -> Self {
313        Self::Unavailable {
314            since: Timestamp::sample_full(),
315        }
316    }
317
318    fn sample_minimal() -> Self {
319        Self::Unchecked
320    }
321
322    fn sample_alternates() -> Vec<Self> {
323        vec![Self::Available {
324            since: Timestamp::sample_full(),
325        }]
326    }
327}
328
329/// What the printer pushed since the last print started or was closed out:
330/// a stop's push and the read that finds the stop can arrive in either order,
331/// so what a print's run pushed is kept for its whole run.
332#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
333pub(crate) struct PushFacts {
334    /// It pushed a reset.
335    pub(crate) reset: bool,
336    /// It pushed an error of its own.
337    pub(crate) firmware_error: bool,
338    /// The push channel was down at some point, so what it pushed is not the
339    /// whole of what happened.
340    pub(crate) gap: bool,
341}
342
343/// What the printer was doing on its own, as one read found it.
344#[derive(Debug, Clone, PartialEq)]
345struct Activity {
346    /// Every tool whose target is above zero.
347    tools: Vec<HeatedTool>,
348    /// The bed's target, when above zero.
349    bed: Option<f64>,
350    /// Whether the head moved since the last position read.
351    moved: Option<bool>,
352}
353
354impl Activity {
355    /// Whether this is activity at all.
356    fn is_active(&self) -> bool {
357        !self.tools.is_empty() || self.bed.is_some() || self.moved == Some(true)
358    }
359}
360
361/// The window after an unfinished ending in which activity is recorded.
362#[derive(Debug, Clone)]
363struct Unattended {
364    /// The print that ended.
365    print_id: PrintId,
366    /// When, on the clock nothing steps, it ended.
367    began: Duration,
368    /// The activity last recorded, absent when none is under way.
369    recorded: Option<Activity>,
370    /// The position last read.
371    position: Option<HeadPosition>,
372    /// When, on the clock nothing steps, its agent was last given a turn on
373    /// activity.
374    turned_at: Option<Duration>,
375}
376
377/// What the watch holds between reads.
378#[derive(Debug, Default)]
379pub(crate) struct WatchState {
380    /// The printer's state the last read found.
381    last_state: Option<PrinterState>,
382    /// What the printer pushed since the last print started or was closed out.
383    pushes: PushFacts,
384    /// The push channel.
385    channel: Channel,
386    /// The unattended window, while one is open.
387    unattended: Option<Unattended>,
388    /// The detector's health.
389    detector: DetectorHealth,
390    /// Turns an ending claimed, for the next watch round to answer.
391    pending_turns: Vec<PendingTurn>,
392    /// Resets the store refused to write down, for the next round to write.
393    pending_resets: Vec<PrinterResetPayload>,
394    /// Prints closed out whose ending was not yet followed up, because the
395    /// store would not answer, for the next round to follow up.
396    pending_ends: Vec<PrintId>,
397    /// Activity turns the store would not answer for, for the next round to
398    /// claim.
399    pending_claims: Vec<(PrintId, EventRecord)>,
400}
401
402impl WatchState {
403    /// Whether the push channel is anything but open now.
404    const fn channel_is_down(&self) -> bool {
405        !matches!(self.channel, Channel::Open)
406    }
407}
408
409/// The printer's push channel, as the server last reported it.
410#[derive(Debug, Clone, Default, PartialEq, Eq)]
411enum Channel {
412    /// Nothing has reported on it yet.
413    #[default]
414    Unknown,
415    /// It is open.
416    Open,
417    /// It is down, and why.
418    Down(String),
419}
420
421/// What one round of the watch claimed.
422#[derive(Debug, Default)]
423pub struct Watched {
424    /// The turns it claimed, each to be run by
425    /// [`Supervisor::run_supervision`].
426    pub turns: Vec<PendingTurn>,
427}
428
429/// Whether a state is one a connection change is recorded into or out of.
430const fn is_down(state: &PrinterState) -> bool {
431    matches!(state, PrinterState::Offline | PrinterState::Error)
432}
433
434/// Whether a job in this state is one the printer is running.
435const fn job_runs(state: &PrinterState) -> bool {
436    matches!(
437        state,
438        PrinterState::Printing | PrinterState::Paused | PrinterState::Cancelling
439    )
440}
441
442/// What one snapshot says the heaters are driving towards.
443fn heated(snapshot: &PrinterSnapshot) -> (Vec<HeatedTool>, Option<f64>) {
444    let tools = snapshot
445        .tools
446        .iter()
447        .enumerate()
448        .filter_map(|(index, heater)| {
449            let target = heater.target_c.as_ref()?.value();
450            (target > 0.0).then(|| HeatedTool {
451                tool: i64::try_from(index).unwrap_or(i64::MAX),
452                target_c: target,
453            })
454        })
455        .collect();
456    let bed = snapshot
457        .bed
458        .as_ref()
459        .and_then(|bed| bed.target_c.as_ref())
460        .map(printobserver_types::Reported::value)
461        .filter(|target| *target > 0.0);
462    (tools, bed)
463}
464
465/// One activity in words.
466fn activity_detail(activity: &Activity, channel_down: bool) -> String {
467    let mut parts: Vec<String> = activity
468        .tools
469        .iter()
470        .map(|tool| format!("tool {} is heating to {} °C", tool.tool, tool.target_c))
471        .collect();
472    if let Some(bed) = activity.bed {
473        parts.push(format!("the bed is heating to {bed} °C"));
474    }
475    match activity.moved {
476        Some(true) => parts.push("the print head moved".to_owned()),
477        Some(false) => {}
478        None => parts.push("the print head's position could not be read".to_owned()),
479    }
480    let mut detail = format!("with no job running, {}", parts.join(", "));
481    if channel_down {
482        detail.push_str("; ");
483        detail.push_str(PUSH_CHANNEL_DOWN);
484    }
485    detail
486}
487
488impl Supervisor {
489    /// What the watch holds, held for one read or write.
490    pub(crate) fn watch_state(&self) -> std::sync::MutexGuard<'_, WatchState> {
491        self.watch
492            .lock()
493            .unwrap_or_else(std::sync::PoisonError::into_inner)
494    }
495
496    /// What the printer pushed since the last print started or was closed out.
497    pub(crate) fn push_facts(&self) -> PushFacts {
498        let state = self.watch_state();
499        let mut facts = state.pushes;
500        facts.gap |= state.channel_is_down();
501        facts
502    }
503
504    /// What the printer pushed, once a reset it may still be pushing for a
505    /// return to idle has had [`RESET_GRACE`] to arrive — at once when the
506    /// push channel is down, since nothing would arrive.
507    pub(crate) async fn pushes_after_a_reset_could_arrive(&self) -> PushFacts {
508        // A wait for something a real socket delivers, so it is measured on
509        // the host's own clock rather than the one supervision is driven by.
510        let started = std::time::Instant::now();
511        loop {
512            let facts = self.push_facts();
513            if facts.reset
514                || self.watch_state().channel_is_down()
515                || started.elapsed() >= RESET_GRACE
516                || crate::delay::Delay::new(Duration::from_millis(50))
517                    .await
518                    .is_err()
519            {
520                return facts;
521            }
522        }
523    }
524
525    /// Close any unattended window: a job is running.
526    pub(crate) fn note_job_running(&self) {
527        self.watch_state().unattended = None;
528    }
529
530    /// Forget what the printer pushed: a print starts, or one's close-out has
531    /// read it.
532    pub(crate) fn forget_pushes(&self) {
533        let mut state = self.watch_state();
534        let gap = state.channel_is_down();
535        state.pushes = PushFacts {
536            gap,
537            ..PushFacts::default()
538        };
539    }
540
541    /// The failure detector's health, as the last check found it.
542    #[must_use]
543    pub fn detector_health(&self) -> DetectorHealth {
544        self.watch_state().detector
545    }
546
547    /// Report that the printer's push channel opened, or why it is down.
548    ///
549    /// While it is down an ending is decided from the printer's state alone,
550    /// and every event the watch writes says so.
551    pub fn note_push_channel(&self, open: Result<(), String>) {
552        let mut state = self.watch_state();
553        match open {
554            Ok(()) => state.channel = Channel::Open,
555            Err(detail) => {
556                state.channel = Channel::Down(detail);
557                state.pushes.gap = true;
558            }
559        }
560    }
561
562    /// Take one thing the printer pushed.
563    ///
564    /// A reset is recorded at once as a [`PrinterResetPayload`], naming the
565    /// print it happened during when one was running; it and an error of the
566    /// printer's own are kept for the close-out of the print they stopped.
567    /// Terminal lines are the server's to read, and are ignored here.
568    ///
569    /// # Errors
570    ///
571    /// Returns the store's own error when the reset could not be recorded.
572    pub async fn note_push(&self, push: PrinterPush) -> Result<(), CoreError> {
573        match push {
574            PrinterPush::Reset => {
575                // A reset forgets where every axis is.
576                self.distrust_z("the printer pushed a reset, and a reset forgets where Z is");
577                // Which print was running is read before the close-out is told
578                // of the reset: told first, it can close that print while the
579                // read is still waiting on the store, and the reset would then
580                // name no print. A close-out that reads the machine idle first
581                // waits `RESET_GRACE` for this flag, so setting it a moment
582                // later still reaches it.
583                let running = self.running_print().await;
584                self.watch_state().pushes.reset = true;
585                // A reset is recorded whatever the store answers about which
586                // print was running: the push is not sent again.
587                let (during_print, detail) = match running {
588                    Ok(Some(print)) => (
589                        Some(print.id),
590                        format!("the printer pushed a reset during print {}", print.id),
591                    ),
592                    Ok(None) => (
593                        None,
594                        "the printer pushed a reset while no print was running".to_owned(),
595                    ),
596                    Err(error) => (
597                        None,
598                        format!(
599                            "the printer pushed a reset; which print was running could not be \
600                             read: {error}"
601                        ),
602                    ),
603                };
604                let payload = PrinterResetPayload {
605                    during_print,
606                    detail,
607                };
608                if let Err(error) = self.write_reset(&payload).await {
609                    // The push is not sent again, so what it said is kept for
610                    // the next round to write down.
611                    self.watch_state().pending_resets.push(payload);
612                    return Err(error);
613                }
614                Ok(())
615            }
616            PrinterPush::Error {
617                reason: PrinterErrorReason::Firmware,
618            } => {
619                self.watch_state().pushes.firmware_error = true;
620                Ok(())
621            }
622            PrinterPush::Error {
623                reason: PrinterErrorReason::Other(_),
624            }
625            | PrinterPush::Log { .. } => Ok(()),
626        }
627    }
628
629    /// Write one reset down.
630    async fn write_reset(&self, payload: &PrinterResetPayload) -> Result<(), CoreError> {
631        let draft = self.draft_of(None, system_source(), payload)?;
632        self.stores().events.append_event(draft).await?;
633        Ok(())
634    }
635
636    /// Write down what an earlier round could not: the resets the store
637    /// refused, the follow-up of endings and the activity turns it would not
638    /// answer for. Each still refused is kept for the round after.
639    async fn catch_up(&self) {
640        let resets = std::mem::take(&mut self.watch_state().pending_resets);
641        for payload in resets {
642            if self.write_reset(&payload).await.is_err() {
643                self.watch_state().pending_resets.push(payload);
644            }
645        }
646        let ends = std::mem::take(&mut self.watch_state().pending_ends);
647        for print_id in ends {
648            if self.after_close_out(print_id).await.is_err() {
649                self.watch_state().pending_ends.push(print_id);
650            }
651        }
652        let claims = std::mem::take(&mut self.watch_state().pending_claims);
653        for (print_id, event) in claims {
654            self.claim_activity_turn(print_id, event).await;
655        }
656    }
657
658    /// Follow up one print's close-out, or keep it for the next round when the
659    /// store will not answer.
660    pub(crate) async fn follow_up_end(&self, print_id: PrintId) {
661        if self.after_close_out(print_id).await.is_err() {
662            self.watch_state().pending_ends.push(print_id);
663        }
664    }
665
666    /// The open print this supervisor last saw running, when there is one.
667    async fn running_print(&self) -> Result<Option<PrintRecord>, CoreError> {
668        Ok(self
669            .stores()
670            .prints
671            .open_prints()
672            .await?
673            .into_iter()
674            .find(|print| self.was_seen_running(print.id)))
675    }
676
677    /// Read the machine once, record what changed, and answer the turns that
678    /// claimed.
679    ///
680    /// A printer whose job cannot be read changes nothing: an instance that
681    /// does not answer says nothing about the machine behind it.
682    ///
683    /// # Errors
684    ///
685    /// Returns the store's own error when what changed could not be recorded.
686    pub async fn watch_printer(&self, probe: &dyn PositionProbe) -> Result<Watched, CoreError> {
687        self.catch_up().await;
688        let resolving = self.resolving().await;
689        let observed = self.observe_job().await;
690        if let Some(observed) = &observed {
691            self.note_connection(
692                &observed.job.state,
693                observed.job.error.as_ref().map(|error| error.text.as_str()),
694            )
695            .await?;
696            self.settle_and_adopt(observed).await?;
697        }
698        drop(resolving);
699        if let Some(observed) = &observed {
700            self.watch_unattended(observed, probe).await?;
701        }
702        Ok(Watched {
703            turns: std::mem::take(&mut self.watch_state().pending_turns),
704        })
705    }
706
707    /// Record a change of the printer's state into or out of `offline` or
708    /// `error`.
709    async fn note_connection(
710        &self,
711        state: &PrinterState,
712        error: Option<&str>,
713    ) -> Result<(), CoreError> {
714        let (previous, channel_down) = {
715            let held = self.watch_state();
716            (held.last_state.clone(), held.channel_is_down())
717        };
718        if is_down(state) && previous.as_ref() != Some(state) {
719            // A printer that went offline or into error may have been
720            // reset, moved or powered off since: where Z is is unknown.
721            self.distrust_z(format!(
722                "the printer went {state:?}, and Z may have moved since"
723            ));
724        }
725        let changed = previous
726            .as_ref()
727            .filter(|previous| *previous != state && (is_down(previous) || is_down(state)));
728        if let Some(previous) = changed {
729            let reporting = error
730                .filter(|error| !error.trim().is_empty())
731                .map(|error| format!(", reporting {error:?}"))
732                .unwrap_or_default();
733            let mut detail = format!("the printer went from {previous:?} to {state:?}{reporting}");
734            if channel_down {
735                detail.push_str("; ");
736                detail.push_str(PUSH_CHANNEL_DOWN);
737            }
738            let draft = self.draft_of(
739                None,
740                system_source(),
741                &PrinterConnectionChangedPayload {
742                    from: previous.clone(),
743                    to: state.clone(),
744                    detail,
745                },
746            )?;
747            // Remembered only once it is written down: a change the store
748            // refused is found again by the next read.
749            self.stores().events.append_event(draft).await?;
750        }
751        self.watch_state().last_state = Some(state.clone());
752        Ok(())
753    }
754
755    /// What follows a print's close-out: an `interrupted` or `failed` ending
756    /// opens the unattended window and claims its agent a turn on the
757    /// `print_ended`; any other ending closes the window.
758    async fn after_close_out(&self, print_id: PrintId) -> Result<(), CoreError> {
759        self.forget_pushes();
760        let Some(ended) = self
761            .stores()
762            .events
763            .history(HistoryQuery {
764                print_id,
765                kinds: vec![PrintEndedPayload::kind()],
766                since: None,
767                until: None,
768                limit: Some(1),
769            })
770            .await?
771            .into_iter()
772            .next()
773        else {
774            return Ok(());
775        };
776        let Some(Ok(payload)) = ended.payload_as::<PrintEndedPayload>() else {
777            return Ok(());
778        };
779        if !matches!(
780            payload.outcome,
781            PrintOutcome::Interrupted | PrintOutcome::Failed
782        ) {
783            self.watch_state().unattended = None;
784            return Ok(());
785        }
786        self.distrust_z(format!(
787            "print {print_id} ended {}, and where it left Z is unknown",
788            if payload.outcome == PrintOutcome::Failed {
789                "failed"
790            } else {
791                "interrupted"
792            }
793        ));
794        self.watch_state().unattended = Some(Unattended {
795            print_id,
796            began: self.clock().elapsed(),
797            recorded: None,
798            position: None,
799            turned_at: None,
800        });
801        self.claim_after_end(print_id, ended).await
802    }
803
804    /// Claim one ended print's agent a turn on one event about its end, or
805    /// hand the event to the turn already running for it.
806    async fn claim_after_end(
807        &self,
808        print_id: PrintId,
809        event: EventRecord,
810    ) -> Result<(), CoreError> {
811        let Some(print) = self.stores().prints.print(print_id).await? else {
812            return Ok(());
813        };
814        let arrival = Arrival {
815            frame_captured_at: None,
816            event,
817            detection: None,
818        };
819        if self.inboxes().claim_or_hand_over(print_id, arrival.clone()) {
820            self.watch_state()
821                .pending_turns
822                .push(PendingTurn::new(print, arrival, Vec::new()));
823        }
824        Ok(())
825    }
826
827    /// Record the printer acting on its own, while the unattended window is
828    /// open and no job runs.
829    async fn watch_unattended(
830        &self,
831        observed: &ObservedJob,
832        probe: &dyn PositionProbe,
833    ) -> Result<(), CoreError> {
834        let window = self.config().unattended_window;
835        let now = self.clock().elapsed();
836        let (print_id, last_position, channel_down) = {
837            let mut held = self.watch_state();
838            let Some(open) = &held.unattended else {
839                return Ok(());
840            };
841            if now.saturating_sub(open.began) > window {
842                held.unattended = None;
843                return Ok(());
844            }
845            (open.print_id, open.position, held.channel_is_down())
846        };
847        if job_runs(&observed.job.state) || is_down(&observed.job.state) {
848            return Ok(());
849        }
850        let Ok(snapshot) = self.read_snapshot().await else {
851            return Ok(());
852        };
853        if job_runs(&snapshot.connection) || is_down(&snapshot.connection) {
854            return Ok(());
855        }
856        let (tools, bed) = heated(&snapshot);
857        let position = probe.read_position().await;
858        let moved = match (last_position, position) {
859            (_, None) => None,
860            (None, Some(_)) => Some(false),
861            (Some(before), Some(after)) => Some(before != after),
862        };
863        let activity = Activity { tools, bed, moved };
864        let unchanged = {
865            let mut held = self.watch_state();
866            let Some(open) = held
867                .unattended
868                .as_mut()
869                .filter(|open| open.print_id == print_id)
870            else {
871                return Ok(());
872            };
873            if position.is_some() {
874                open.position = position;
875            }
876            if !activity.is_active() {
877                open.recorded = None;
878                return Ok(());
879            }
880            open.recorded.as_ref() == Some(&activity)
881        };
882        if unchanged {
883            return Ok(());
884        }
885        let draft = self.draft_of(
886            None,
887            system_source(),
888            &UnattendedPrinterActivityPayload {
889                last_print_id: print_id,
890                tools: activity.tools.clone(),
891                bed_target_c: activity.bed,
892                moved: activity.moved,
893                detail: activity_detail(&activity, channel_down),
894            },
895        )?;
896        let event = self.stores().events.append_event(draft).await?;
897        let interval = self.config().observation_interval;
898        let turn_due = {
899            let mut held = self.watch_state();
900            let Some(open) = held.unattended.as_mut() else {
901                return Ok(());
902            };
903            // Remembered only once it is written down: activity the store
904            // refused is found again by the next read.
905            open.recorded = Some(activity.clone());
906            open.turned_at
907                .is_none_or(|turned| now.saturating_sub(turned) >= interval)
908        };
909        if turn_due {
910            self.claim_activity_turn(print_id, event).await;
911        }
912        Ok(())
913    }
914
915    /// Claim the turn one activity owes its print's agent, counting it against
916    /// the interval once it is claimed; one the store would not answer for is
917    /// kept for the next round to claim.
918    async fn claim_activity_turn(&self, print_id: PrintId, event: EventRecord) {
919        if self.claim_after_end(print_id, event.clone()).await.is_err() {
920            self.watch_state().pending_claims.push((print_id, event));
921            return;
922        }
923        let now = self.clock().elapsed();
924        if let Some(open) = self
925            .watch_state()
926            .unattended
927            .as_mut()
928            .filter(|open| open.print_id == print_id)
929        {
930            open.turned_at = Some(now);
931        }
932    }
933
934    /// Ask the failure detector whether it is answering, during a print, and
935    /// record each change; going unavailable claims the active print's agent a
936    /// turn.
937    ///
938    /// No print open, no check: a detector nobody needs is not one to
939    /// record.
940    ///
941    /// # Errors
942    ///
943    /// Returns the store's own error when a change could not be recorded.
944    pub async fn check_detector(
945        &self,
946        probe: &dyn DetectorProbe,
947    ) -> Result<Option<PendingTurn>, CoreError> {
948        let Some(print) = self.stores().prints.open_prints().await?.into_iter().next() else {
949            return Ok(None);
950        };
951        let (status, detail) = match probe.check().await {
952            Ok(detail) => (DetectorStatus::Available, detail),
953            Err(detail) => (DetectorStatus::Unavailable, detail),
954        };
955        let health = match status {
956            DetectorStatus::Available => DetectorHealthStatus::Available,
957            DetectorStatus::Unavailable => DetectorHealthStatus::Unavailable,
958        };
959        let previous = self.watch_state().detector.status();
960        if previous == health {
961            return Ok(None);
962        }
963        let since = self.clock().now();
964        let found = match status {
965            DetectorStatus::Available => DetectorHealth::Available { since },
966            DetectorStatus::Unavailable => DetectorHealth::Unavailable { since },
967        };
968        // The first check finding the detector up is where watching it begins,
969        // not a change in it.
970        if previous == DetectorHealthStatus::Unchecked && health == DetectorHealthStatus::Available
971        {
972            self.watch_state().detector = found;
973            return Ok(None);
974        }
975        let draft = self.draft_of(
976            None,
977            system_source(),
978            &DetectorHealthChangedPayload { status, detail },
979        )?;
980        let event = self.stores().events.append_event(draft).await?;
981        // Remembered only once it is written down: a change the store refused
982        // is found again by the next check.
983        self.watch_state().detector = found;
984        if status != DetectorStatus::Unavailable {
985            return Ok(None);
986        }
987        let arrival = Arrival {
988            frame_captured_at: None,
989            event,
990            detection: None,
991        };
992        Ok(self
993            .inboxes()
994            .claim_or_hand_over(print.id, arrival.clone())
995            .then(|| PendingTurn::new(print, arrival, Vec::new())))
996    }
997}
998
999/// The kinds a print that has ended is still given a turn on: how it ended,
1000/// and what the printer did on its own after.
1001pub(crate) fn concerns_its_end(kind: &EventKind) -> bool {
1002    [
1003        PrintEndedPayload::KIND,
1004        UnattendedPrinterActivityPayload::KIND,
1005    ]
1006    .contains(&kind.as_str())
1007}
1008
1009/// What one event says the watch noticed, in words, for the situation of the
1010/// turn it prompts; nothing for an event the watch did not raise.
1011pub(crate) fn noticed_of(event: &EventRecord) -> Option<String> {
1012    if let Some(Ok(ended)) = event.payload_as::<PrintEndedPayload>() {
1013        let outcome = match ended.outcome {
1014            PrintOutcome::Interrupted => "interrupted",
1015            PrintOutcome::Failed => "failed",
1016            PrintOutcome::Completed | PrintOutcome::Cancelled => return None,
1017        };
1018        return Some(format!(
1019            "{}: the print ended {outcome}, the printer reporting {:?} ({})",
1020            PrintEndedPayload::KIND,
1021            ended.state,
1022            ended.reason
1023        ));
1024    }
1025    if let Some(Ok(activity)) = event.payload_as::<UnattendedPrinterActivityPayload>() {
1026        return Some(format!(
1027            "{}: after print {} ended, {}",
1028            UnattendedPrinterActivityPayload::KIND,
1029            activity.last_print_id,
1030            activity.detail
1031        ));
1032    }
1033    if let Some(Ok(degraded)) = event.payload_as::<crate::kinds::CameraDegradedPayload>() {
1034        return Some(format!(
1035            "{}: the camera gave no usable frame in {} attempts, so there is no frame to look \
1036             at: {}",
1037            crate::kinds::CameraDegradedPayload::KIND,
1038            degraded.attempts,
1039            degraded.detail
1040        ));
1041    }
1042    if let Some(Ok(health)) = event.payload_as::<DetectorHealthChangedPayload>() {
1043        return Some(format!(
1044            "{}: the failure detector is {:?}, so nothing is watching the print for failures: {}",
1045            DetectorHealthChangedPayload::KIND,
1046            health.status,
1047            health.detail
1048        ));
1049    }
1050    None
1051}