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                self.watch_state().pushes.reset = true;
576                // A reset is recorded whatever the store answers about which
577                // print was running: the push is not sent again.
578                let (during_print, detail) = match self.running_print().await {
579                    Ok(Some(print)) => (
580                        Some(print.id),
581                        format!("the printer pushed a reset during print {}", print.id),
582                    ),
583                    Ok(None) => (
584                        None,
585                        "the printer pushed a reset while no print was running".to_owned(),
586                    ),
587                    Err(error) => (
588                        None,
589                        format!(
590                            "the printer pushed a reset; which print was running could not be \
591                             read: {error}"
592                        ),
593                    ),
594                };
595                let payload = PrinterResetPayload {
596                    during_print,
597                    detail,
598                };
599                if let Err(error) = self.write_reset(&payload).await {
600                    // The push is not sent again, so what it said is kept for
601                    // the next round to write down.
602                    self.watch_state().pending_resets.push(payload);
603                    return Err(error);
604                }
605                Ok(())
606            }
607            PrinterPush::Error {
608                reason: PrinterErrorReason::Firmware,
609            } => {
610                self.watch_state().pushes.firmware_error = true;
611                Ok(())
612            }
613            PrinterPush::Error {
614                reason: PrinterErrorReason::Other(_),
615            }
616            | PrinterPush::Log { .. } => Ok(()),
617        }
618    }
619
620    /// Write one reset down.
621    async fn write_reset(&self, payload: &PrinterResetPayload) -> Result<(), CoreError> {
622        let draft = self.draft_of(None, system_source(), payload)?;
623        self.stores().events.append_event(draft).await?;
624        Ok(())
625    }
626
627    /// Write down what an earlier round could not: the resets the store
628    /// refused, the follow-up of endings and the activity turns it would not
629    /// answer for. Each still refused is kept for the round after.
630    async fn catch_up(&self) {
631        let resets = std::mem::take(&mut self.watch_state().pending_resets);
632        for payload in resets {
633            if self.write_reset(&payload).await.is_err() {
634                self.watch_state().pending_resets.push(payload);
635            }
636        }
637        let ends = std::mem::take(&mut self.watch_state().pending_ends);
638        for print_id in ends {
639            if self.after_close_out(print_id).await.is_err() {
640                self.watch_state().pending_ends.push(print_id);
641            }
642        }
643        let claims = std::mem::take(&mut self.watch_state().pending_claims);
644        for (print_id, event) in claims {
645            self.claim_activity_turn(print_id, event).await;
646        }
647    }
648
649    /// Follow up one print's close-out, or keep it for the next round when the
650    /// store will not answer.
651    pub(crate) async fn follow_up_end(&self, print_id: PrintId) {
652        if self.after_close_out(print_id).await.is_err() {
653            self.watch_state().pending_ends.push(print_id);
654        }
655    }
656
657    /// The open print this supervisor last saw running, when there is one.
658    async fn running_print(&self) -> Result<Option<PrintRecord>, CoreError> {
659        Ok(self
660            .stores()
661            .prints
662            .open_prints()
663            .await?
664            .into_iter()
665            .find(|print| self.was_seen_running(print.id)))
666    }
667
668    /// Read the machine once, record what changed, and answer the turns that
669    /// claimed.
670    ///
671    /// A printer whose job cannot be read changes nothing: an instance that
672    /// does not answer says nothing about the machine behind it.
673    ///
674    /// # Errors
675    ///
676    /// Returns the store's own error when what changed could not be recorded.
677    pub async fn watch_printer(&self, probe: &dyn PositionProbe) -> Result<Watched, CoreError> {
678        self.catch_up().await;
679        let resolving = self.resolving().await;
680        let observed = self.observe_job().await;
681        if let Some(observed) = &observed {
682            self.note_connection(
683                &observed.job.state,
684                observed.job.error.as_ref().map(|error| error.text.as_str()),
685            )
686            .await?;
687            self.settle_and_adopt(observed).await?;
688        }
689        drop(resolving);
690        if let Some(observed) = &observed {
691            self.watch_unattended(observed, probe).await?;
692        }
693        Ok(Watched {
694            turns: std::mem::take(&mut self.watch_state().pending_turns),
695        })
696    }
697
698    /// Record a change of the printer's state into or out of `offline` or
699    /// `error`.
700    async fn note_connection(
701        &self,
702        state: &PrinterState,
703        error: Option<&str>,
704    ) -> Result<(), CoreError> {
705        let (previous, channel_down) = {
706            let held = self.watch_state();
707            (held.last_state.clone(), held.channel_is_down())
708        };
709        let changed = previous
710            .as_ref()
711            .filter(|previous| *previous != state && (is_down(previous) || is_down(state)));
712        if let Some(previous) = changed {
713            let reporting = error
714                .filter(|error| !error.trim().is_empty())
715                .map(|error| format!(", reporting {error:?}"))
716                .unwrap_or_default();
717            let mut detail = format!("the printer went from {previous:?} to {state:?}{reporting}");
718            if channel_down {
719                detail.push_str("; ");
720                detail.push_str(PUSH_CHANNEL_DOWN);
721            }
722            let draft = self.draft_of(
723                None,
724                system_source(),
725                &PrinterConnectionChangedPayload {
726                    from: previous.clone(),
727                    to: state.clone(),
728                    detail,
729                },
730            )?;
731            // Remembered only once it is written down: a change the store
732            // refused is found again by the next read.
733            self.stores().events.append_event(draft).await?;
734        }
735        self.watch_state().last_state = Some(state.clone());
736        Ok(())
737    }
738
739    /// What follows a print's close-out: an `interrupted` or `failed` ending
740    /// opens the unattended window and claims its agent a turn on the
741    /// `print_ended`; any other ending closes the window.
742    async fn after_close_out(&self, print_id: PrintId) -> Result<(), CoreError> {
743        self.forget_pushes();
744        let Some(ended) = self
745            .stores()
746            .events
747            .history(HistoryQuery {
748                print_id,
749                kinds: vec![PrintEndedPayload::kind()],
750                since: None,
751                until: None,
752                limit: Some(1),
753            })
754            .await?
755            .into_iter()
756            .next()
757        else {
758            return Ok(());
759        };
760        let Some(Ok(payload)) = ended.payload_as::<PrintEndedPayload>() else {
761            return Ok(());
762        };
763        if !matches!(
764            payload.outcome,
765            PrintOutcome::Interrupted | PrintOutcome::Failed
766        ) {
767            self.watch_state().unattended = None;
768            return Ok(());
769        }
770        self.watch_state().unattended = Some(Unattended {
771            print_id,
772            began: self.clock().elapsed(),
773            recorded: None,
774            position: None,
775            turned_at: None,
776        });
777        self.claim_after_end(print_id, ended).await
778    }
779
780    /// Claim one ended print's agent a turn on one event about its end, or
781    /// hand the event to the turn already running for it.
782    async fn claim_after_end(
783        &self,
784        print_id: PrintId,
785        event: EventRecord,
786    ) -> Result<(), CoreError> {
787        let Some(print) = self.stores().prints.print(print_id).await? else {
788            return Ok(());
789        };
790        let arrival = Arrival {
791            event,
792            detection: None,
793        };
794        if self.inboxes().claim_or_hand_over(print_id, arrival.clone()) {
795            self.watch_state()
796                .pending_turns
797                .push(PendingTurn::new(print, arrival, Vec::new()));
798        }
799        Ok(())
800    }
801
802    /// Record the printer acting on its own, while the unattended window is
803    /// open and no job runs.
804    async fn watch_unattended(
805        &self,
806        observed: &ObservedJob,
807        probe: &dyn PositionProbe,
808    ) -> Result<(), CoreError> {
809        let window = self.config().unattended_window;
810        let now = self.clock().elapsed();
811        let (print_id, last_position, channel_down) = {
812            let mut held = self.watch_state();
813            let Some(open) = &held.unattended else {
814                return Ok(());
815            };
816            if now.saturating_sub(open.began) > window {
817                held.unattended = None;
818                return Ok(());
819            }
820            (open.print_id, open.position, held.channel_is_down())
821        };
822        if job_runs(&observed.job.state) || is_down(&observed.job.state) {
823            return Ok(());
824        }
825        let Ok(snapshot) = self.read_snapshot().await else {
826            return Ok(());
827        };
828        if job_runs(&snapshot.connection) || is_down(&snapshot.connection) {
829            return Ok(());
830        }
831        let (tools, bed) = heated(&snapshot);
832        let position = probe.read_position().await;
833        let moved = match (last_position, position) {
834            (_, None) => None,
835            (None, Some(_)) => Some(false),
836            (Some(before), Some(after)) => Some(before != after),
837        };
838        let activity = Activity { tools, bed, moved };
839        let unchanged = {
840            let mut held = self.watch_state();
841            let Some(open) = held
842                .unattended
843                .as_mut()
844                .filter(|open| open.print_id == print_id)
845            else {
846                return Ok(());
847            };
848            if position.is_some() {
849                open.position = position;
850            }
851            if !activity.is_active() {
852                open.recorded = None;
853                return Ok(());
854            }
855            open.recorded.as_ref() == Some(&activity)
856        };
857        if unchanged {
858            return Ok(());
859        }
860        let draft = self.draft_of(
861            None,
862            system_source(),
863            &UnattendedPrinterActivityPayload {
864                last_print_id: print_id,
865                tools: activity.tools.clone(),
866                bed_target_c: activity.bed,
867                moved: activity.moved,
868                detail: activity_detail(&activity, channel_down),
869            },
870        )?;
871        let event = self.stores().events.append_event(draft).await?;
872        let interval = self.config().observation_interval;
873        let turn_due = {
874            let mut held = self.watch_state();
875            let Some(open) = held.unattended.as_mut() else {
876                return Ok(());
877            };
878            // Remembered only once it is written down: activity the store
879            // refused is found again by the next read.
880            open.recorded = Some(activity.clone());
881            open.turned_at
882                .is_none_or(|turned| now.saturating_sub(turned) >= interval)
883        };
884        if turn_due {
885            self.claim_activity_turn(print_id, event).await;
886        }
887        Ok(())
888    }
889
890    /// Claim the turn one activity owes its print's agent, counting it against
891    /// the interval once it is claimed; one the store would not answer for is
892    /// kept for the next round to claim.
893    async fn claim_activity_turn(&self, print_id: PrintId, event: EventRecord) {
894        if self.claim_after_end(print_id, event.clone()).await.is_err() {
895            self.watch_state().pending_claims.push((print_id, event));
896            return;
897        }
898        let now = self.clock().elapsed();
899        if let Some(open) = self
900            .watch_state()
901            .unattended
902            .as_mut()
903            .filter(|open| open.print_id == print_id)
904        {
905            open.turned_at = Some(now);
906        }
907    }
908
909    /// Ask the failure detector whether it is answering, during a print, and
910    /// record each change; going unavailable claims the active print's agent a
911    /// turn.
912    ///
913    /// No print open, no check: a detector nobody needs is not one to
914    /// record.
915    ///
916    /// # Errors
917    ///
918    /// Returns the store's own error when a change could not be recorded.
919    pub async fn check_detector(
920        &self,
921        probe: &dyn DetectorProbe,
922    ) -> Result<Option<PendingTurn>, CoreError> {
923        let Some(print) = self.stores().prints.open_prints().await?.into_iter().next() else {
924            return Ok(None);
925        };
926        let (status, detail) = match probe.check().await {
927            Ok(detail) => (DetectorStatus::Available, detail),
928            Err(detail) => (DetectorStatus::Unavailable, detail),
929        };
930        let health = match status {
931            DetectorStatus::Available => DetectorHealthStatus::Available,
932            DetectorStatus::Unavailable => DetectorHealthStatus::Unavailable,
933        };
934        let previous = self.watch_state().detector.status();
935        if previous == health {
936            return Ok(None);
937        }
938        let since = self.clock().now();
939        let found = match status {
940            DetectorStatus::Available => DetectorHealth::Available { since },
941            DetectorStatus::Unavailable => DetectorHealth::Unavailable { since },
942        };
943        // The first check finding the detector up is where watching it begins,
944        // not a change in it.
945        if previous == DetectorHealthStatus::Unchecked && health == DetectorHealthStatus::Available
946        {
947            self.watch_state().detector = found;
948            return Ok(None);
949        }
950        let draft = self.draft_of(
951            None,
952            system_source(),
953            &DetectorHealthChangedPayload { status, detail },
954        )?;
955        let event = self.stores().events.append_event(draft).await?;
956        // Remembered only once it is written down: a change the store refused
957        // is found again by the next check.
958        self.watch_state().detector = found;
959        if status != DetectorStatus::Unavailable {
960            return Ok(None);
961        }
962        let arrival = Arrival {
963            event,
964            detection: None,
965        };
966        Ok(self
967            .inboxes()
968            .claim_or_hand_over(print.id, arrival.clone())
969            .then(|| PendingTurn::new(print, arrival, Vec::new())))
970    }
971}
972
973/// The kinds a print that has ended is still given a turn on: how it ended,
974/// and what the printer did on its own after.
975pub(crate) fn concerns_its_end(kind: &EventKind) -> bool {
976    [
977        PrintEndedPayload::KIND,
978        UnattendedPrinterActivityPayload::KIND,
979    ]
980    .contains(&kind.as_str())
981}
982
983/// What one event says the watch noticed, in words, for the situation of the
984/// turn it prompts; nothing for an event the watch did not raise.
985pub(crate) fn noticed_of(event: &EventRecord) -> Option<String> {
986    if let Some(Ok(ended)) = event.payload_as::<PrintEndedPayload>() {
987        let outcome = match ended.outcome {
988            PrintOutcome::Interrupted => "interrupted",
989            PrintOutcome::Failed => "failed",
990            PrintOutcome::Completed | PrintOutcome::Cancelled => return None,
991        };
992        return Some(format!(
993            "{}: the print ended {outcome}, the printer reporting {:?} ({})",
994            PrintEndedPayload::KIND,
995            ended.state,
996            ended.reason
997        ));
998    }
999    if let Some(Ok(activity)) = event.payload_as::<UnattendedPrinterActivityPayload>() {
1000        return Some(format!(
1001            "{}: after print {} ended, {}",
1002            UnattendedPrinterActivityPayload::KIND,
1003            activity.last_print_id,
1004            activity.detail
1005        ));
1006    }
1007    if let Some(Ok(degraded)) = event.payload_as::<crate::kinds::CameraDegradedPayload>() {
1008        return Some(format!(
1009            "{}: the camera gave no usable frame in {} attempts, so there is no frame to look \
1010             at: {}",
1011            crate::kinds::CameraDegradedPayload::KIND,
1012            degraded.attempts,
1013            degraded.detail
1014        ));
1015    }
1016    if let Some(Ok(health)) = event.payload_as::<DetectorHealthChangedPayload>() {
1017        return Some(format!(
1018            "{}: the failure detector is {:?}, so nothing is watching the print for failures: {}",
1019            DetectorHealthChangedPayload::KIND,
1020            health.status,
1021            health.detail
1022        ));
1023    }
1024    None
1025}