printobserver-core 0.10.5

Supervision logic for printobserver.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
//! The printer watch: what changed under a print while nobody asked.
//!
//! Every other read of the printer here is somebody's — a listing, a status, a
//! turn's context. The watch is nobody's: the server asks it to read the
//! machine every [`CoreConfig::printer_poll`](crate::CoreConfig::printer_poll),
//! whether or not a print is active, and it records what changed.
//!
//! * **The connection.** A read finding the printer's state changed into or
//!   out of `offline` or `error` — a serial disconnect, a reconnect, a printer
//!   error — is a [`PrinterConnectionChangedPayload`]. The printer's state is
//!   read from its job, never from a refusal: a printer that is not
//!   operational refuses a read of its own state, and that refusal is the
//!   adapter's to read as `offline`, never one recorded as a port failure.
//! * **How a print ended.** The watch's read settles the open prints as every
//!   other read does ([`crate::listing`]), and the close-out decides the
//!   outcome from what the printer pushed during the stop as well as from what
//!   a read shows ([`crate::accounting`]). An `interrupted` or `failed` ending
//!   gives the print's agent a turn on its `print_ended`, and opens the
//!   unattended window.
//! * **The printer acting on its own.** Within
//!   [`CoreConfig::unattended_window`](crate::CoreConfig::unattended_window)
//!   of an `interrupted` or `failed` ending, a read finding a heater target
//!   above zero, or the head moved, while no job runs is an
//!   [`UnattendedPrinterActivityPayload`]: once when it begins, and again only
//!   when what it reports changes. The head's position is asked for through a
//!   [`PositionProbe`] the server supplies, and only after this read found no
//!   job running. The print's agent gets a turn on it, at most one per
//!   [`CoreConfig::observation_interval`](crate::CoreConfig::observation_interval);
//!   one recorded inside that interval reaches the agent through its next
//!   turn's recent events.
//! * **A reset.** The printer's push channel says when it reset, one while
//!   idle included, which no read shows; each is a [`PrinterResetPayload`]
//!   ([`Supervisor::note_push`]).
//! * **The detector.** During a print, a [`DetectorProbe`] the server supplies
//!   is asked whether the failure detector is answering, and each change is a
//!   [`DetectorHealthChangedPayload`]; going unavailable gives the active
//!   print's agent a turn. The last status is what the status and context
//!   reads answer as [`DetectorHealth`].
//!
//! # Nothing here commands the machine
//!
//! The watch reads. A position is asked for through the probe, which is the
//! server's own: this crate names no method of the printer port but its reads,
//! and the chokepoint stands as [`crate::supervisor`] states it.

use std::time::Duration;

use printobserver_printer_api::{
    BoxFuture, PrinterErrorReason, PrinterPush, PrinterSnapshot, PrinterState,
};
use printobserver_types::contract::Sample;
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};
use printobserver_types::{EventKind, EventPayload as _, EventRecord, PrintId, Timestamp};

use crate::error::CoreError;
use crate::events::PendingTurn;
use crate::inbox::Arrival;
use crate::kinds::{
    DetectorHealthChangedPayload, DetectorStatus, HeatedTool, PrintEndedPayload,
    PrinterConnectionChangedPayload, PrinterResetPayload, UnattendedPrinterActivityPayload,
    system_source,
};
use crate::listing::ObservedJob;
use crate::records::{PrintOutcome, PrintRecord};
use crate::store::HistoryQuery;
use crate::supervisor::Supervisor;

/// How often the printer watch reads the machine, when nothing configures it.
pub const DEFAULT_PRINTER_POLL: Duration = Duration::from_secs(15);

/// How long after an `interrupted` or `failed` ending the printer acting on
/// its own is recorded, when nothing configures it.
pub const DEFAULT_UNATTENDED_WINDOW: Duration = Duration::from_secs(3600);

/// How long a return to idle that would read as a cancel waits for the reset
/// the printer may still be pushing for it.
///
/// `OctoPrint` pushes a reset within about a third of a second of the
/// printer's own, and moves its state to idle within about two thirds; a read
/// can land between the two, and without the reset a firmware reset reads as
/// a cancel made at the printer.
pub const RESET_GRACE: Duration = Duration::from_secs(1);

/// What a detail says while the push channel is down.
pub const PUSH_CHANNEL_DOWN: &str =
    "the printer's push channel was down, so this was read from its state alone";

/// The kinds the printer watch writes with no print: the printer's own, read
/// into a print's recent events from the moment it opened.
pub const PRINTER_WATCH_KINDS: [&str; 4] = [
    PrinterConnectionChangedPayload::KIND,
    PrinterResetPayload::KIND,
    UnattendedPrinterActivityPayload::KIND,
    DetectorHealthChangedPayload::KIND,
];

/// Where the print head is.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct HeadPosition {
    /// X, in millimetres.
    pub x: f64,
    /// Y, in millimetres.
    pub y: f64,
    /// Z, in millimetres.
    pub z: f64,
}

/// What reads the print head's position for the watch.
///
/// The server's own: it asks the printer and reads the answer off the push
/// channel. Answers nothing when no position could be read.
pub trait PositionProbe: Send + Sync {
    /// Read where the head is now.
    fn read_position(&self) -> BoxFuture<'_, Option<HeadPosition>>;
}

/// What asks the failure detector whether it is answering.
pub trait DetectorProbe: Send + Sync {
    /// Answers what it was told: `Ok` when the detector answered its health
    /// check, `Err` when it did not, each in words.
    fn check(&self) -> BoxFuture<'_, Result<String, String>>;
}

/// The failure detector's health, as the last check found it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
#[serde(
    crate = "printobserver_types::serde",
    rename_all = "snake_case",
    deny_unknown_fields
)]
#[schemars(crate = "printobserver_types::schemars")]
pub enum DetectorHealthStatus {
    /// It answered its health check.
    Available,
    /// It did not.
    Unavailable,
    /// Nothing checks it: no detector health address is configured, or no
    /// check has been made yet.
    #[default]
    Unchecked,
}

/// The failure detector's health, and since when it has been so.
///
/// Three states and no fourth: a detector nobody has checked has no "since",
/// and one that was checked always has one. On the wire it is the object the
/// status and context reads answer — `status`, and `since` that is `null`
/// exactly when the status is `unchecked` — and an object pairing them any
/// other way is refused rather than read.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DetectorHealth {
    /// Nothing checks it: no detector health address is configured, or no
    /// check has been made yet.
    #[default]
    Unchecked,
    /// It answered its health check, from this instant on.
    Available {
        /// When it was first found answering.
        since: Timestamp,
    },
    /// It did not, from this instant on.
    Unavailable {
        /// When it was first found not answering.
        since: Timestamp,
    },
}

impl DetectorHealth {
    /// What the last check found.
    #[must_use]
    pub const fn status(&self) -> DetectorHealthStatus {
        match self {
            Self::Unchecked => DetectorHealthStatus::Unchecked,
            Self::Available { .. } => DetectorHealthStatus::Available,
            Self::Unavailable { .. } => DetectorHealthStatus::Unavailable,
        }
    }
}

/// The failure detector's health as the wire carries it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
struct DetectorHealthWire {
    /// What the last check found.
    status: DetectorHealthStatus,
    /// When the status became what it is, `null` exactly while unchecked —
    /// and always present, as the schema requires.
    #[serde(deserialize_with = "present")]
    since: Option<Timestamp>,
}

/// Read a value that may be `null` but may not be missing: serde reads a
/// missing optional as `None` unless it is read through a function of its own.
fn present<'de, D: printobserver_types::serde::Deserializer<'de>>(
    deserializer: D,
) -> Result<Option<Timestamp>, D::Error> {
    Option::deserialize(deserializer)
}

impl From<DetectorHealth> for DetectorHealthWire {
    fn from(health: DetectorHealth) -> Self {
        let since = match health {
            DetectorHealth::Unchecked => None,
            DetectorHealth::Available { since } | DetectorHealth::Unavailable { since } => {
                Some(since)
            }
        };
        Self {
            status: health.status(),
            since,
        }
    }
}

impl TryFrom<DetectorHealthWire> for DetectorHealth {
    type Error = &'static str;

    fn try_from(wire: DetectorHealthWire) -> Result<Self, Self::Error> {
        match (wire.status, wire.since) {
            (DetectorHealthStatus::Unchecked, None) => Ok(Self::Unchecked),
            (DetectorHealthStatus::Available, Some(since)) => Ok(Self::Available { since }),
            (DetectorHealthStatus::Unavailable, Some(since)) => Ok(Self::Unavailable { since }),
            (DetectorHealthStatus::Unchecked, Some(_)) => {
                Err("an unchecked detector has no instant it became so")
            }
            (_, None) => Err("a checked detector carries the instant it became so"),
        }
    }
}

impl Serialize for DetectorHealth {
    fn serialize<S: printobserver_types::serde::Serializer>(
        &self,
        serializer: S,
    ) -> Result<S::Ok, S::Error> {
        DetectorHealthWire::from(*self).serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for DetectorHealth {
    fn deserialize<D: printobserver_types::serde::Deserializer<'de>>(
        deserializer: D,
    ) -> Result<Self, D::Error> {
        let wire = DetectorHealthWire::deserialize(deserializer)?;
        Self::try_from(wire).map_err(printobserver_types::serde::de::Error::custom)
    }
}

/// One arm of the detector's health as a schema: its status, and its `since`.
fn health_arm(
    status: &str,
    doc: &str,
    since: &printobserver_types::serde_json::Value,
) -> printobserver_types::serde_json::Value {
    printobserver_types::serde_json::json!({
        "type": "object",
        "description": doc,
        "properties": {
            "status": { "type": "string", "const": status },
            "since": since,
        },
        "required": ["status", "since"],
        "additionalProperties": false,
    })
}

/// The schema describes the three states as arms tagged by `status`, so a
/// generated client cannot pair a status with the wrong `since` either.
impl JsonSchema for DetectorHealth {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        std::borrow::Cow::Borrowed("DetectorHealth")
    }

    fn json_schema(
        generator: &mut printobserver_types::schemars::SchemaGenerator,
    ) -> printobserver_types::schemars::Schema {
        let timestamp =
            printobserver_types::serde_json::to_value(generator.subschema_for::<Timestamp>())
                .unwrap_or_default();
        let schema = printobserver_types::serde_json::json!({
            "title": "DetectorHealth",
            "description": "The failure detector's health, and since when it has been so: \
                `since` is `null` exactly while the status is `unchecked`.",
            "oneOf": [
                health_arm(
                    "unchecked",
                    "Nothing checks it: no detector health address is configured, or no \
                     check has been made yet.",
                    &printobserver_types::serde_json::json!({
                        "type": "null",
                        "description": "Nothing: an unchecked detector has no instant it became so.",
                    }),
                ),
                health_arm(
                    "available",
                    "It answered its health check, from `since` on.",
                    &timestamp,
                ),
                health_arm(
                    "unavailable",
                    "It did not answer its health check, from `since` on.",
                    &timestamp,
                ),
            ],
        });
        printobserver_types::schemars::Schema::try_from(schema).unwrap_or_default()
    }
}

impl Sample for DetectorHealth {
    fn sample_full() -> Self {
        Self::Unavailable {
            since: Timestamp::sample_full(),
        }
    }

    fn sample_minimal() -> Self {
        Self::Unchecked
    }

    fn sample_alternates() -> Vec<Self> {
        vec![Self::Available {
            since: Timestamp::sample_full(),
        }]
    }
}

/// What the printer pushed since the last print started or was closed out:
/// a stop's push and the read that finds the stop can arrive in either order,
/// so what a print's run pushed is kept for its whole run.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct PushFacts {
    /// It pushed a reset.
    pub(crate) reset: bool,
    /// It pushed an error of its own.
    pub(crate) firmware_error: bool,
    /// The push channel was down at some point, so what it pushed is not the
    /// whole of what happened.
    pub(crate) gap: bool,
}

/// What the printer was doing on its own, as one read found it.
#[derive(Debug, Clone, PartialEq)]
struct Activity {
    /// Every tool whose target is above zero.
    tools: Vec<HeatedTool>,
    /// The bed's target, when above zero.
    bed: Option<f64>,
    /// Whether the head moved since the last position read.
    moved: Option<bool>,
}

impl Activity {
    /// Whether this is activity at all.
    fn is_active(&self) -> bool {
        !self.tools.is_empty() || self.bed.is_some() || self.moved == Some(true)
    }
}

/// The window after an unfinished ending in which activity is recorded.
#[derive(Debug, Clone)]
struct Unattended {
    /// The print that ended.
    print_id: PrintId,
    /// When, on the clock nothing steps, it ended.
    began: Duration,
    /// The activity last recorded, absent when none is under way.
    recorded: Option<Activity>,
    /// The position last read.
    position: Option<HeadPosition>,
    /// When, on the clock nothing steps, its agent was last given a turn on
    /// activity.
    turned_at: Option<Duration>,
}

/// What the watch holds between reads.
#[derive(Debug, Default)]
pub(crate) struct WatchState {
    /// The printer's state the last read found.
    last_state: Option<PrinterState>,
    /// What the printer pushed since the last print started or was closed out.
    pushes: PushFacts,
    /// The push channel.
    channel: Channel,
    /// The unattended window, while one is open.
    unattended: Option<Unattended>,
    /// The detector's health.
    detector: DetectorHealth,
    /// Turns an ending claimed, for the next watch round to answer.
    pending_turns: Vec<PendingTurn>,
    /// Resets the store refused to write down, for the next round to write.
    pending_resets: Vec<PrinterResetPayload>,
    /// Prints closed out whose ending was not yet followed up, because the
    /// store would not answer, for the next round to follow up.
    pending_ends: Vec<PrintId>,
    /// Activity turns the store would not answer for, for the next round to
    /// claim.
    pending_claims: Vec<(PrintId, EventRecord)>,
}

impl WatchState {
    /// Whether the push channel is anything but open now.
    const fn channel_is_down(&self) -> bool {
        !matches!(self.channel, Channel::Open)
    }
}

/// The printer's push channel, as the server last reported it.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
enum Channel {
    /// Nothing has reported on it yet.
    #[default]
    Unknown,
    /// It is open.
    Open,
    /// It is down, and why.
    Down(String),
}

/// What one round of the watch claimed.
#[derive(Debug, Default)]
pub struct Watched {
    /// The turns it claimed, each to be run by
    /// [`Supervisor::run_supervision`].
    pub turns: Vec<PendingTurn>,
}

/// Whether a state is one a connection change is recorded into or out of.
const fn is_down(state: &PrinterState) -> bool {
    matches!(state, PrinterState::Offline | PrinterState::Error)
}

/// Whether a job in this state is one the printer is running.
const fn job_runs(state: &PrinterState) -> bool {
    matches!(
        state,
        PrinterState::Printing | PrinterState::Paused | PrinterState::Cancelling
    )
}

/// What one snapshot says the heaters are driving towards.
fn heated(snapshot: &PrinterSnapshot) -> (Vec<HeatedTool>, Option<f64>) {
    let tools = snapshot
        .tools
        .iter()
        .enumerate()
        .filter_map(|(index, heater)| {
            let target = heater.target_c.as_ref()?.value();
            (target > 0.0).then(|| HeatedTool {
                tool: i64::try_from(index).unwrap_or(i64::MAX),
                target_c: target,
            })
        })
        .collect();
    let bed = snapshot
        .bed
        .as_ref()
        .and_then(|bed| bed.target_c.as_ref())
        .map(printobserver_types::Reported::value)
        .filter(|target| *target > 0.0);
    (tools, bed)
}

/// One activity in words.
fn activity_detail(activity: &Activity, channel_down: bool) -> String {
    let mut parts: Vec<String> = activity
        .tools
        .iter()
        .map(|tool| format!("tool {} is heating to {} °C", tool.tool, tool.target_c))
        .collect();
    if let Some(bed) = activity.bed {
        parts.push(format!("the bed is heating to {bed} °C"));
    }
    match activity.moved {
        Some(true) => parts.push("the print head moved".to_owned()),
        Some(false) => {}
        None => parts.push("the print head's position could not be read".to_owned()),
    }
    let mut detail = format!("with no job running, {}", parts.join(", "));
    if channel_down {
        detail.push_str("; ");
        detail.push_str(PUSH_CHANNEL_DOWN);
    }
    detail
}

impl Supervisor {
    /// What the watch holds, held for one read or write.
    pub(crate) fn watch_state(&self) -> std::sync::MutexGuard<'_, WatchState> {
        self.watch
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// What the printer pushed since the last print started or was closed out.
    pub(crate) fn push_facts(&self) -> PushFacts {
        let state = self.watch_state();
        let mut facts = state.pushes;
        facts.gap |= state.channel_is_down();
        facts
    }

    /// What the printer pushed, once a reset it may still be pushing for a
    /// return to idle has had [`RESET_GRACE`] to arrive — at once when the
    /// push channel is down, since nothing would arrive.
    pub(crate) async fn pushes_after_a_reset_could_arrive(&self) -> PushFacts {
        // A wait for something a real socket delivers, so it is measured on
        // the host's own clock rather than the one supervision is driven by.
        let started = std::time::Instant::now();
        loop {
            let facts = self.push_facts();
            if facts.reset
                || self.watch_state().channel_is_down()
                || started.elapsed() >= RESET_GRACE
                || crate::delay::Delay::new(Duration::from_millis(50))
                    .await
                    .is_err()
            {
                return facts;
            }
        }
    }

    /// Close any unattended window: a job is running.
    pub(crate) fn note_job_running(&self) {
        self.watch_state().unattended = None;
    }

    /// Forget what the printer pushed: a print starts, or one's close-out has
    /// read it.
    pub(crate) fn forget_pushes(&self) {
        let mut state = self.watch_state();
        let gap = state.channel_is_down();
        state.pushes = PushFacts {
            gap,
            ..PushFacts::default()
        };
    }

    /// The failure detector's health, as the last check found it.
    #[must_use]
    pub fn detector_health(&self) -> DetectorHealth {
        self.watch_state().detector
    }

    /// Report that the printer's push channel opened, or why it is down.
    ///
    /// While it is down an ending is decided from the printer's state alone,
    /// and every event the watch writes says so.
    pub fn note_push_channel(&self, open: Result<(), String>) {
        let mut state = self.watch_state();
        match open {
            Ok(()) => state.channel = Channel::Open,
            Err(detail) => {
                state.channel = Channel::Down(detail);
                state.pushes.gap = true;
            }
        }
    }

    /// Take one thing the printer pushed.
    ///
    /// A reset is recorded at once as a [`PrinterResetPayload`], naming the
    /// print it happened during when one was running; it and an error of the
    /// printer's own are kept for the close-out of the print they stopped.
    /// Terminal lines are the server's to read, and are ignored here.
    ///
    /// # Errors
    ///
    /// Returns the store's own error when the reset could not be recorded.
    pub async fn note_push(&self, push: PrinterPush) -> Result<(), CoreError> {
        match push {
            PrinterPush::Reset => {
                // A reset forgets where every axis is.
                self.distrust_z("the printer pushed a reset, and a reset forgets where Z is");
                // Which print was running is read before the close-out is told
                // of the reset: told first, it can close that print while the
                // read is still waiting on the store, and the reset would then
                // name no print. A close-out that reads the machine idle first
                // waits `RESET_GRACE` for this flag, so setting it a moment
                // later still reaches it.
                let running = self.running_print().await;
                self.watch_state().pushes.reset = true;
                // A reset is recorded whatever the store answers about which
                // print was running: the push is not sent again.
                let (during_print, detail) = match running {
                    Ok(Some(print)) => (
                        Some(print.id),
                        format!("the printer pushed a reset during print {}", print.id),
                    ),
                    Ok(None) => (
                        None,
                        "the printer pushed a reset while no print was running".to_owned(),
                    ),
                    Err(error) => (
                        None,
                        format!(
                            "the printer pushed a reset; which print was running could not be \
                             read: {error}"
                        ),
                    ),
                };
                let payload = PrinterResetPayload {
                    during_print,
                    detail,
                };
                if let Err(error) = self.write_reset(&payload).await {
                    // The push is not sent again, so what it said is kept for
                    // the next round to write down.
                    self.watch_state().pending_resets.push(payload);
                    return Err(error);
                }
                Ok(())
            }
            PrinterPush::Error {
                reason: PrinterErrorReason::Firmware,
            } => {
                self.watch_state().pushes.firmware_error = true;
                Ok(())
            }
            PrinterPush::Error {
                reason: PrinterErrorReason::Other(_),
            }
            | PrinterPush::Log { .. } => Ok(()),
        }
    }

    /// Write one reset down.
    async fn write_reset(&self, payload: &PrinterResetPayload) -> Result<(), CoreError> {
        let draft = self.draft_of(None, system_source(), payload)?;
        self.stores().events.append_event(draft).await?;
        Ok(())
    }

    /// Write down what an earlier round could not: the resets the store
    /// refused, the follow-up of endings and the activity turns it would not
    /// answer for. Each still refused is kept for the round after.
    async fn catch_up(&self) {
        let resets = std::mem::take(&mut self.watch_state().pending_resets);
        for payload in resets {
            if self.write_reset(&payload).await.is_err() {
                self.watch_state().pending_resets.push(payload);
            }
        }
        let ends = std::mem::take(&mut self.watch_state().pending_ends);
        for print_id in ends {
            if self.after_close_out(print_id).await.is_err() {
                self.watch_state().pending_ends.push(print_id);
            }
        }
        let claims = std::mem::take(&mut self.watch_state().pending_claims);
        for (print_id, event) in claims {
            self.claim_activity_turn(print_id, event).await;
        }
    }

    /// Follow up one print's close-out, or keep it for the next round when the
    /// store will not answer.
    pub(crate) async fn follow_up_end(&self, print_id: PrintId) {
        if self.after_close_out(print_id).await.is_err() {
            self.watch_state().pending_ends.push(print_id);
        }
    }

    /// The open print this supervisor last saw running, when there is one.
    async fn running_print(&self) -> Result<Option<PrintRecord>, CoreError> {
        Ok(self
            .stores()
            .prints
            .open_prints()
            .await?
            .into_iter()
            .find(|print| self.was_seen_running(print.id)))
    }

    /// Read the machine once, record what changed, and answer the turns that
    /// claimed.
    ///
    /// A printer whose job cannot be read changes nothing: an instance that
    /// does not answer says nothing about the machine behind it.
    ///
    /// # Errors
    ///
    /// Returns the store's own error when what changed could not be recorded.
    pub async fn watch_printer(&self, probe: &dyn PositionProbe) -> Result<Watched, CoreError> {
        self.catch_up().await;
        let resolving = self.resolving().await;
        let observed = self.observe_job().await;
        if let Some(observed) = &observed {
            self.note_connection(
                &observed.job.state,
                observed.job.error.as_ref().map(|error| error.text.as_str()),
            )
            .await?;
            self.settle_and_adopt(observed).await?;
        }
        drop(resolving);
        if let Some(observed) = &observed {
            self.watch_unattended(observed, probe).await?;
        }
        Ok(Watched {
            turns: std::mem::take(&mut self.watch_state().pending_turns),
        })
    }

    /// Record a change of the printer's state into or out of `offline` or
    /// `error`.
    async fn note_connection(
        &self,
        state: &PrinterState,
        error: Option<&str>,
    ) -> Result<(), CoreError> {
        let (previous, channel_down) = {
            let held = self.watch_state();
            (held.last_state.clone(), held.channel_is_down())
        };
        if is_down(state) && previous.as_ref() != Some(state) {
            // A printer that went offline or into error may have been
            // reset, moved or powered off since: where Z is is unknown.
            self.distrust_z(format!(
                "the printer went {state:?}, and Z may have moved since"
            ));
        }
        let changed = previous
            .as_ref()
            .filter(|previous| *previous != state && (is_down(previous) || is_down(state)));
        if let Some(previous) = changed {
            let reporting = error
                .filter(|error| !error.trim().is_empty())
                .map(|error| format!(", reporting {error:?}"))
                .unwrap_or_default();
            let mut detail = format!("the printer went from {previous:?} to {state:?}{reporting}");
            if channel_down {
                detail.push_str("; ");
                detail.push_str(PUSH_CHANNEL_DOWN);
            }
            let draft = self.draft_of(
                None,
                system_source(),
                &PrinterConnectionChangedPayload {
                    from: previous.clone(),
                    to: state.clone(),
                    detail,
                },
            )?;
            // Remembered only once it is written down: a change the store
            // refused is found again by the next read.
            self.stores().events.append_event(draft).await?;
        }
        self.watch_state().last_state = Some(state.clone());
        Ok(())
    }

    /// What follows a print's close-out: an `interrupted` or `failed` ending
    /// opens the unattended window and claims its agent a turn on the
    /// `print_ended`; any other ending closes the window.
    async fn after_close_out(&self, print_id: PrintId) -> Result<(), CoreError> {
        self.forget_pushes();
        let Some(ended) = self
            .stores()
            .events
            .history(HistoryQuery {
                print_id,
                kinds: vec![PrintEndedPayload::kind()],
                since: None,
                until: None,
                limit: Some(1),
            })
            .await?
            .into_iter()
            .next()
        else {
            return Ok(());
        };
        let Some(Ok(payload)) = ended.payload_as::<PrintEndedPayload>() else {
            return Ok(());
        };
        if !matches!(
            payload.outcome,
            PrintOutcome::Interrupted | PrintOutcome::Failed
        ) {
            self.watch_state().unattended = None;
            return Ok(());
        }
        self.distrust_z(format!(
            "print {print_id} ended {}, and where it left Z is unknown",
            if payload.outcome == PrintOutcome::Failed {
                "failed"
            } else {
                "interrupted"
            }
        ));
        self.watch_state().unattended = Some(Unattended {
            print_id,
            began: self.clock().elapsed(),
            recorded: None,
            position: None,
            turned_at: None,
        });
        self.claim_after_end(print_id, ended).await
    }

    /// Claim one ended print's agent a turn on one event about its end, or
    /// hand the event to the turn already running for it.
    async fn claim_after_end(
        &self,
        print_id: PrintId,
        event: EventRecord,
    ) -> Result<(), CoreError> {
        let Some(print) = self.stores().prints.print(print_id).await? else {
            return Ok(());
        };
        let arrival = Arrival {
            event,
            detection: None,
        };
        if self.inboxes().claim_or_hand_over(print_id, arrival.clone()) {
            self.watch_state()
                .pending_turns
                .push(PendingTurn::new(print, arrival, Vec::new()));
        }
        Ok(())
    }

    /// Record the printer acting on its own, while the unattended window is
    /// open and no job runs.
    async fn watch_unattended(
        &self,
        observed: &ObservedJob,
        probe: &dyn PositionProbe,
    ) -> Result<(), CoreError> {
        let window = self.config().unattended_window;
        let now = self.clock().elapsed();
        let (print_id, last_position, channel_down) = {
            let mut held = self.watch_state();
            let Some(open) = &held.unattended else {
                return Ok(());
            };
            if now.saturating_sub(open.began) > window {
                held.unattended = None;
                return Ok(());
            }
            (open.print_id, open.position, held.channel_is_down())
        };
        if job_runs(&observed.job.state) || is_down(&observed.job.state) {
            return Ok(());
        }
        let Ok(snapshot) = self.read_snapshot().await else {
            return Ok(());
        };
        if job_runs(&snapshot.connection) || is_down(&snapshot.connection) {
            return Ok(());
        }
        let (tools, bed) = heated(&snapshot);
        let position = probe.read_position().await;
        let moved = match (last_position, position) {
            (_, None) => None,
            (None, Some(_)) => Some(false),
            (Some(before), Some(after)) => Some(before != after),
        };
        let activity = Activity { tools, bed, moved };
        let unchanged = {
            let mut held = self.watch_state();
            let Some(open) = held
                .unattended
                .as_mut()
                .filter(|open| open.print_id == print_id)
            else {
                return Ok(());
            };
            if position.is_some() {
                open.position = position;
            }
            if !activity.is_active() {
                open.recorded = None;
                return Ok(());
            }
            open.recorded.as_ref() == Some(&activity)
        };
        if unchanged {
            return Ok(());
        }
        let draft = self.draft_of(
            None,
            system_source(),
            &UnattendedPrinterActivityPayload {
                last_print_id: print_id,
                tools: activity.tools.clone(),
                bed_target_c: activity.bed,
                moved: activity.moved,
                detail: activity_detail(&activity, channel_down),
            },
        )?;
        let event = self.stores().events.append_event(draft).await?;
        let interval = self.config().observation_interval;
        let turn_due = {
            let mut held = self.watch_state();
            let Some(open) = held.unattended.as_mut() else {
                return Ok(());
            };
            // Remembered only once it is written down: activity the store
            // refused is found again by the next read.
            open.recorded = Some(activity.clone());
            open.turned_at
                .is_none_or(|turned| now.saturating_sub(turned) >= interval)
        };
        if turn_due {
            self.claim_activity_turn(print_id, event).await;
        }
        Ok(())
    }

    /// Claim the turn one activity owes its print's agent, counting it against
    /// the interval once it is claimed; one the store would not answer for is
    /// kept for the next round to claim.
    async fn claim_activity_turn(&self, print_id: PrintId, event: EventRecord) {
        if self.claim_after_end(print_id, event.clone()).await.is_err() {
            self.watch_state().pending_claims.push((print_id, event));
            return;
        }
        let now = self.clock().elapsed();
        if let Some(open) = self
            .watch_state()
            .unattended
            .as_mut()
            .filter(|open| open.print_id == print_id)
        {
            open.turned_at = Some(now);
        }
    }

    /// Ask the failure detector whether it is answering, during a print, and
    /// record each change; going unavailable claims the active print's agent a
    /// turn.
    ///
    /// No print open, no check: a detector nobody needs is not one to
    /// record.
    ///
    /// # Errors
    ///
    /// Returns the store's own error when a change could not be recorded.
    pub async fn check_detector(
        &self,
        probe: &dyn DetectorProbe,
    ) -> Result<Option<PendingTurn>, CoreError> {
        let Some(print) = self.stores().prints.open_prints().await?.into_iter().next() else {
            return Ok(None);
        };
        let (status, detail) = match probe.check().await {
            Ok(detail) => (DetectorStatus::Available, detail),
            Err(detail) => (DetectorStatus::Unavailable, detail),
        };
        let health = match status {
            DetectorStatus::Available => DetectorHealthStatus::Available,
            DetectorStatus::Unavailable => DetectorHealthStatus::Unavailable,
        };
        let previous = self.watch_state().detector.status();
        if previous == health {
            return Ok(None);
        }
        let since = self.clock().now();
        let found = match status {
            DetectorStatus::Available => DetectorHealth::Available { since },
            DetectorStatus::Unavailable => DetectorHealth::Unavailable { since },
        };
        // The first check finding the detector up is where watching it begins,
        // not a change in it.
        if previous == DetectorHealthStatus::Unchecked && health == DetectorHealthStatus::Available
        {
            self.watch_state().detector = found;
            return Ok(None);
        }
        let draft = self.draft_of(
            None,
            system_source(),
            &DetectorHealthChangedPayload { status, detail },
        )?;
        let event = self.stores().events.append_event(draft).await?;
        // Remembered only once it is written down: a change the store refused
        // is found again by the next check.
        self.watch_state().detector = found;
        if status != DetectorStatus::Unavailable {
            return Ok(None);
        }
        let arrival = Arrival {
            event,
            detection: None,
        };
        Ok(self
            .inboxes()
            .claim_or_hand_over(print.id, arrival.clone())
            .then(|| PendingTurn::new(print, arrival, Vec::new())))
    }
}

/// The kinds a print that has ended is still given a turn on: how it ended,
/// and what the printer did on its own after.
pub(crate) fn concerns_its_end(kind: &EventKind) -> bool {
    [
        PrintEndedPayload::KIND,
        UnattendedPrinterActivityPayload::KIND,
    ]
    .contains(&kind.as_str())
}

/// What one event says the watch noticed, in words, for the situation of the
/// turn it prompts; nothing for an event the watch did not raise.
pub(crate) fn noticed_of(event: &EventRecord) -> Option<String> {
    if let Some(Ok(ended)) = event.payload_as::<PrintEndedPayload>() {
        let outcome = match ended.outcome {
            PrintOutcome::Interrupted => "interrupted",
            PrintOutcome::Failed => "failed",
            PrintOutcome::Completed | PrintOutcome::Cancelled => return None,
        };
        return Some(format!(
            "{}: the print ended {outcome}, the printer reporting {:?} ({})",
            PrintEndedPayload::KIND,
            ended.state,
            ended.reason
        ));
    }
    if let Some(Ok(activity)) = event.payload_as::<UnattendedPrinterActivityPayload>() {
        return Some(format!(
            "{}: after print {} ended, {}",
            UnattendedPrinterActivityPayload::KIND,
            activity.last_print_id,
            activity.detail
        ));
    }
    if let Some(Ok(degraded)) = event.payload_as::<crate::kinds::CameraDegradedPayload>() {
        return Some(format!(
            "{}: the camera gave no usable frame in {} attempts, so there is no frame to look \
             at: {}",
            crate::kinds::CameraDegradedPayload::KIND,
            degraded.attempts,
            degraded.detail
        ));
    }
    if let Some(Ok(health)) = event.payload_as::<DetectorHealthChangedPayload>() {
        return Some(format!(
            "{}: the failure detector is {:?}, so nothing is watching the print for failures: {}",
            DetectorHealthChangedPayload::KIND,
            health.status,
            health.detail
        ));
    }
    None
}