Skip to main content

printobserver_core/
kinds.rs

1//! The event kinds and source names the supervision domain writes.
2//!
3//! Each kind here is one the supervision loop, the action chokepoint or the
4//! expiry sweep raises itself, declared under a [`KIND`](EventPayload::KIND)
5//! of its own and written down through the envelope
6//! [`printobserver_types::event`] declares. Nothing outside this crate names
7//! these kinds to write them; a reader elsewhere reads one back through
8//! [`EventRecord::payload_as`](printobserver_types::EventRecord::payload_as)
9//! and is answered nothing for a record of another kind.
10//!
11//! The three source names are the actors this domain writes events on behalf
12//! of: the supervisor itself, a person, and the supervising agent.
13//!
14//! The printer timeline — every print's start and end, every charge against a
15//! spool, every change to the spool ledger, and every change the printer watch
16//! finds in the machine itself, and every recovery asked of it — is the
17//! twenty-three kinds [`TIMELINE_KINDS`] lists.
18//! A spool event is written with no print unless it happened during one, in
19//! which case it carries that print's; the four the printer watch writes are
20//! the printer's rather than any print's, and are written with no print at
21//! all, naming in their payload the print they happened during or after. The
22//! three a recovery writes are the printer's too, and are written with no
23//! print.
24
25use crate::records::{
26    AcknowledgementDisposition, ActionId, Actor, ChargeKey, ChargeMethod, ChargedFilament,
27    ClearedMark, FilePosition, InterventionId, InterventionOutcome, LoadedSpool, PendingCharge,
28    PendingTaken, PolicyDecision, Preflight, PrintAction, PrintOutcome, RecoveryAction,
29    RecoveryRejection, SpoolCommand, SpoolId, SpoolRecord, UnverifiedReason,
30};
31use printobserver_printer_api::{Adjustable, JobSnapshot, PrinterSnapshot, PrinterState};
32use printobserver_supervisor_api::AgentAssessment;
33use printobserver_types::contract::Sample;
34use printobserver_types::schemars::JsonSchema;
35use printobserver_types::serde::{Deserialize, Serialize};
36use printobserver_types::{
37    EventId, EventKind, EventPayload, EventSource, FileName, PrintId, Timestamp,
38};
39
40/// The source name of an event the supervisor raised itself.
41pub const SYSTEM_SOURCE: &str = "system";
42
43/// The source name of an event a person raised.
44pub const OPERATOR_SOURCE: &str = "operator";
45
46/// The source name of an event the supervising agent raised.
47pub const AGENT_SOURCE: &str = "agent";
48
49/// The source of an event the supervisor raised itself.
50#[must_use]
51pub fn system_source() -> EventSource {
52    EventSource::new(SYSTEM_SOURCE)
53}
54
55/// The source of an event a person raised.
56#[must_use]
57pub fn operator_source() -> EventSource {
58    EventSource::new(OPERATOR_SOURCE)
59}
60
61/// The source of an event the supervising agent raised.
62#[must_use]
63pub fn agent_source() -> EventSource {
64    EventSource::new(AGENT_SOURCE)
65}
66
67/// An actor asked for an action.
68#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
69#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
70#[schemars(crate = "printobserver_types::schemars")]
71pub struct ActionRequestedPayload {
72    /// The action's identifier.
73    pub action_id: ActionId,
74    /// What was asked for.
75    pub action: PrintAction,
76    /// Who asked.
77    pub actor: Actor,
78}
79
80impl EventPayload for ActionRequestedPayload {
81    const KIND: &'static str = "action_requested";
82}
83
84impl Sample for ActionRequestedPayload {
85    fn sample_full() -> Self {
86        Self {
87            action_id: ActionId::sample_full(),
88            action: PrintAction::sample_full(),
89            actor: Actor::sample_full(),
90        }
91    }
92
93    fn sample_minimal() -> Self {
94        Self {
95            action: PrintAction::sample_minimal(),
96            ..Self::sample_full()
97        }
98    }
99}
100
101/// An accepted action reached the printer.
102#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
103#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
104#[schemars(crate = "printobserver_types::schemars")]
105pub struct ActionExecutedPayload {
106    /// The action's identifier.
107    pub action_id: ActionId,
108    /// The bounded intervention it opened, when it opened one.
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub intervention_id: Option<InterventionId>,
111    /// How far into its file the print had last been read to have got when
112    /// the action was taken, in bytes, when that was known: what places a
113    /// change against the commands the file sets the same thing with.
114    #[serde(default, skip_serializing_if = "Option::is_none")]
115    pub file_position_bytes: Option<i64>,
116}
117
118impl EventPayload for ActionExecutedPayload {
119    const KIND: &'static str = "action_executed";
120}
121
122impl Sample for ActionExecutedPayload {
123    fn sample_full() -> Self {
124        Self {
125            action_id: ActionId::sample_full(),
126            intervention_id: Some(InterventionId::sample_full()),
127            file_position_bytes: Some(4_096),
128        }
129    }
130
131    fn sample_minimal() -> Self {
132        Self {
133            action_id: ActionId::sample_full(),
134            intervention_id: None,
135            file_position_bytes: None,
136        }
137    }
138}
139
140/// Policy refused an action.
141#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
142#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
143#[schemars(crate = "printobserver_types::schemars")]
144pub struct ActionRejectedPayload {
145    /// The action's identifier.
146    pub action_id: ActionId,
147    /// The whole decision, carrying which rejection it was.
148    pub decision: PolicyDecision,
149}
150
151impl EventPayload for ActionRejectedPayload {
152    const KIND: &'static str = "action_rejected";
153}
154
155impl Sample for ActionRejectedPayload {
156    fn sample_full() -> Self {
157        Self {
158            action_id: ActionId::sample_full(),
159            decision: PolicyDecision::sample_full(),
160        }
161    }
162}
163
164/// A bounded intervention expired.
165#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
166#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
167#[schemars(crate = "printobserver_types::schemars")]
168pub struct InterventionExpiredPayload {
169    /// The intervention's identifier.
170    pub intervention_id: InterventionId,
171    /// What it had changed.
172    pub adjustable: Adjustable,
173    /// What became of it.
174    pub outcome: InterventionOutcome,
175}
176
177impl EventPayload for InterventionExpiredPayload {
178    const KIND: &'static str = "intervention_expired";
179}
180
181impl Sample for InterventionExpiredPayload {
182    fn sample_full() -> Self {
183        Self {
184            intervention_id: InterventionId::sample_full(),
185            adjustable: Adjustable::Feedrate,
186            outcome: InterventionOutcome::Restored,
187        }
188    }
189}
190
191/// The agent wrote down what it made of a turn.
192#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
193#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
194#[schemars(crate = "printobserver_types::schemars")]
195pub struct AgentAssessmentPayload {
196    /// The session the turn ran in.
197    pub session_name: String,
198    /// What the agent answered with.
199    pub assessment: AgentAssessment,
200}
201
202impl EventPayload for AgentAssessmentPayload {
203    const KIND: &'static str = "agent_assessment";
204}
205
206impl Sample for AgentAssessmentPayload {
207    fn sample_full() -> Self {
208        Self {
209            session_name: "print-0191f0a0".to_owned(),
210            assessment: AgentAssessment::sample_full(),
211        }
212    }
213}
214
215/// The agent answered that a running print should stop, and asked for no
216/// pause or cancel — not even when asked again — so nothing stopped it.
217///
218/// An answer records a judgement and does not act: acting is a request that
219/// policy rules on. Written to the print's history, where a refused pause is,
220/// so the person reading it is told the print the agent judged should stop is
221/// still running.
222#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
223#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
224#[schemars(crate = "printobserver_types::schemars")]
225pub struct AgentStopUnactedPayload {
226    /// The event the turn was about.
227    pub event_id: EventId,
228    /// The session the turn ran in.
229    pub session_name: String,
230    /// What the agent said it saw, as its answer's summary put it.
231    pub summary: String,
232}
233
234impl EventPayload for AgentStopUnactedPayload {
235    const KIND: &'static str = "agent_stop_unacted";
236}
237
238impl Sample for AgentStopUnactedPayload {
239    fn sample_full() -> Self {
240        Self {
241            event_id: EventId::sample_full(),
242            session_name: "print-0191f0a0".to_owned(),
243            summary: "The part has moved off its planned place.".to_owned(),
244        }
245    }
246}
247
248/// An operator acknowledged an event.
249#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
250#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
251#[schemars(crate = "printobserver_types::schemars")]
252pub struct OperatorAcknowledgementPayload {
253    /// The event being acknowledged.
254    pub acknowledged_event_id: EventId,
255    /// What the operator asked for next.
256    pub disposition: AcknowledgementDisposition,
257}
258
259impl EventPayload for OperatorAcknowledgementPayload {
260    const KIND: &'static str = "operator_acknowledgement";
261}
262
263impl Sample for OperatorAcknowledgementPayload {
264    fn sample_full() -> Self {
265        Self {
266            acknowledged_event_id: EventId::sample_full(),
267            disposition: AcknowledgementDisposition::Watch,
268        }
269    }
270}
271
272/// Somebody took a fresh look at the print, or at the printer when no print
273/// was named.
274///
275/// Written down once the camera has been asked for its frame, together with
276/// that frame as this event's image, so that nobody reading the look finds it
277/// without the frame it was taken with. A frame the camera would not give is
278/// recorded against the look as a port failure. A look at the printer belongs
279/// to no print, waits on nothing that arrives for one, and so delivers
280/// nothing.
281#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
282#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
283#[schemars(crate = "printobserver_types::schemars")]
284pub struct CameraLookPayload {
285    /// How long the look waited for something to happen before it was taken,
286    /// in whole seconds.
287    pub waited_s: u32,
288    /// The events for the print that arrived while it waited, and that it
289    /// handed to whoever looked, oldest first.
290    #[serde(default)]
291    pub delivered: Vec<EventId>,
292    /// When the frame this look answered was captured, which its source says or
293    /// the moment it answered; absent when there is no frame. Two looks naming one
294    /// instant saw one frame: no newer one had been taken.
295    #[serde(default, skip_serializing_if = "Option::is_none")]
296    pub frame_captured_at: Option<Timestamp>,
297}
298
299impl EventPayload for CameraLookPayload {
300    const KIND: &'static str = "camera_look";
301}
302
303impl Sample for CameraLookPayload {
304    fn sample_full() -> Self {
305        Self {
306            waited_s: 60,
307            delivered: vec![EventId::sample_full()],
308            frame_captured_at: Some(Timestamp::sample_full()),
309        }
310    }
311
312    fn sample_minimal() -> Self {
313        Self {
314            waited_s: 0,
315            delivered: Vec::new(),
316            frame_captured_at: None,
317        }
318    }
319}
320
321/// The supervisor looked in on an active print on its own schedule, with no
322/// detector having said anything about it.
323///
324/// What a failure detector never alerts on — a progress that stopped moving, a
325/// heater whose target fell to nothing mid-print, a fan cut at a bridge, a wall
326/// going thin — is still on the machine and in the camera's frame, so every
327/// active print is given one of these each interval and a turn on it. It
328/// carries what the printer reported as it was taken; the frame the camera gave
329/// at the same moment, untagged by any detector, is this event's image.
330#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
331#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
332#[schemars(crate = "printobserver_types::schemars")]
333pub struct PeriodicObservationPayload {
334    /// How often these are taken, in whole seconds.
335    pub interval_s: u64,
336    /// The printer's state as the observation was taken, absent when it could
337    /// not be read — which the history records as a port failure.
338    #[serde(default, skip_serializing_if = "Option::is_none")]
339    pub printer: Option<PrinterSnapshot>,
340    /// The job the printer reported as the observation was taken, absent when
341    /// it could not be read.
342    #[serde(default, skip_serializing_if = "Option::is_none")]
343    pub job: Option<JobSnapshot>,
344    /// When the observation's frame was captured, which its source says or the
345    /// moment it answered; absent when there is no frame.
346    #[serde(default, skip_serializing_if = "Option::is_none")]
347    pub frame_captured_at: Option<Timestamp>,
348}
349
350impl EventPayload for PeriodicObservationPayload {
351    const KIND: &'static str = "periodic_observation";
352}
353
354impl Sample for PeriodicObservationPayload {
355    fn sample_full() -> Self {
356        Self {
357            interval_s: 120,
358            printer: Some(PrinterSnapshot::sample_full()),
359            job: Some(JobSnapshot::sample_full()),
360            frame_captured_at: Some(Timestamp::sample_full()),
361        }
362    }
363
364    fn sample_minimal() -> Self {
365        Self {
366            interval_s: 120,
367            printer: None,
368            job: None,
369            frame_captured_at: None,
370        }
371    }
372}
373
374/// The camera answered a request for a frame with a server error, and is being
375/// asked again.
376///
377/// A camera server that could not take a frame this time — go2rtc answers
378/// `500` with `exit status 69` — is often one that will take the next, so a
379/// fetch answered `500` to `599` is made again after a short wait, a bounded
380/// number of times. One of these is written down for each such answer, as it
381/// happens, before the wait; a fetch whose every attempt was refused is
382/// recorded as a port failure only once the attempts run out.
383#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
384#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
385#[schemars(crate = "printobserver_types::schemars")]
386pub struct CameraRetryPayload {
387    /// Which attempt the camera refused, counting from one.
388    pub attempt: u32,
389    /// How many attempts the fetch may make in all.
390    pub attempts: u32,
391    /// The HTTP status the camera answered.
392    pub status: u16,
393    /// The start of what the camera answered with, as text.
394    pub excerpt: String,
395    /// How long the fetch waits before its next attempt, in milliseconds.
396    pub backoff_ms: u64,
397}
398
399impl EventPayload for CameraRetryPayload {
400    const KIND: &'static str = "camera_retry";
401}
402
403impl Sample for CameraRetryPayload {
404    fn sample_full() -> Self {
405        Self {
406            attempt: 1,
407            attempts: 4,
408            status: 500,
409            excerpt: "exit status 69".to_owned(),
410            backoff_ms: 500,
411        }
412    }
413
414    fn sample_minimal() -> Self {
415        Self {
416            excerpt: String::new(),
417            ..Self::sample_full()
418        }
419    }
420}
421
422/// Why a camera frame was not one to hand the agent.
423#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
424#[serde(
425    crate = "printobserver_types::serde",
426    rename_all = "snake_case",
427    deny_unknown_fields
428)]
429#[schemars(crate = "printobserver_types::schemars")]
430pub enum FrameCause {
431    /// It decoded, but is near-uniform grey: its grey-level spread is below
432    /// the configured blank-frame bound.
433    Blank,
434    /// It is not a whole image: a strict decode refused it.
435    Undecodable,
436}
437
438impl Sample for FrameCause {
439    fn sample_full() -> Self {
440        Self::Blank
441    }
442
443    fn sample_alternates() -> Vec<Self> {
444        vec![Self::Undecodable]
445    }
446}
447
448/// The camera gave no usable frame for a look or a periodic observation,
449/// however many times it was asked.
450///
451/// Written in place of the look or the observation it was for, so that no
452/// frame the camera could not give is handed to the agent as one it did.
453#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
454#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
455#[schemars(crate = "printobserver_types::schemars")]
456pub struct CameraDegradedPayload {
457    /// How many frames were fetched, every one of them bad.
458    pub attempts: u32,
459    /// Why the last of them was bad.
460    pub cause: FrameCause,
461    /// What was wrong with each, in words.
462    pub detail: String,
463}
464
465impl EventPayload for CameraDegradedPayload {
466    const KIND: &'static str = "camera_degraded";
467}
468
469impl Sample for CameraDegradedPayload {
470    fn sample_full() -> Self {
471        Self {
472            attempts: 3,
473            cause: FrameCause::Blank,
474            detail: "every frame was near-uniform grey (grey-level spread 2.1 below 36.5)"
475                .to_owned(),
476        }
477    }
478
479    fn sample_alternates() -> Vec<Self> {
480        vec![Self {
481            cause: FrameCause::Undecodable,
482            detail: "every frame failed a strict decode: the image ends early".to_owned(),
483            ..Self::sample_full()
484        }]
485    }
486}
487
488/// A print's G-code was read and indexed: what the slicer planned at each
489/// file position is now known for it, without reading the file again.
490///
491/// Written once per index built, which is once per print for as long as the
492/// server runs.
493#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
494#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
495#[schemars(crate = "printobserver_types::schemars")]
496pub struct GcodeIndexedPayload {
497    /// The file that was indexed.
498    pub file_name: FileName,
499    /// How many bytes of it were read.
500    pub bytes: u64,
501    /// How many layers it plans.
502    pub layers: u64,
503}
504
505impl EventPayload for GcodeIndexedPayload {
506    const KIND: &'static str = "gcode_indexed";
507}
508
509impl Sample for GcodeIndexedPayload {
510    fn sample_full() -> Self {
511        Self {
512            file_name: FileName::sample_full(),
513            bytes: 440_608,
514            layers: 150,
515        }
516    }
517}
518
519/// Where a port failed while an event was being handled.
520///
521/// A closed set of exactly the sites at which a failure has nowhere else to be
522/// recorded. The printer's action methods record theirs on the
523/// [`ActionRecord`](crate::records::ActionRecord) the request minted, and a restoring
524/// call records its own on the [`Intervention`](crate::records::Intervention) it was
525/// expiring; those are not sites here, because a second record of them would be
526/// a second version of one fact.
527#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
528#[serde(
529    crate = "printobserver_types::serde",
530    rename_all = "snake_case",
531    deny_unknown_fields
532)]
533#[schemars(crate = "printobserver_types::schemars")]
534pub enum PortFailureSite {
535    /// Reading the printer's own state.
536    PrinterSnapshot,
537    /// Reading the job the printer reports it is running.
538    PrinterJob,
539    /// Writing the image the event arrived with.
540    ImageWrite,
541    /// Running the supervision turn the event prompted.
542    SupervisionTurn,
543    /// Taking a fresh frame from the camera, for a look at the print or for a
544    /// periodic observation of it.
545    CameraLook,
546    /// Telling the detector that paused the print its detection was handled.
547    DetectorAcknowledgement,
548    /// Asking the failure detector whether it is answering, while it was
549    /// scoring the print all the same.
550    DetectorHealthCheck,
551    /// Reading the failure detector's own record of the print's live
552    /// prediction.
553    DetectorScoringRead,
554}
555
556impl Sample for PortFailureSite {
557    fn sample_full() -> Self {
558        Self::PrinterSnapshot
559    }
560}
561
562/// A port failed while one event was being handled.
563///
564/// The event is named rather than implied, so that a reader holding an event's
565/// identifier reaches every failure recorded while that event was being
566/// handled. A failure recorded here is one the handling survived: the event is
567/// already in the history by the time any of these sites is reached, and the
568/// loop goes on to handle the next event.
569#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
570#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
571#[schemars(crate = "printobserver_types::schemars")]
572pub struct PortFailurePayload {
573    /// The event whose handling reached the failing call.
574    pub event_id: EventId,
575    /// Where it failed.
576    pub site: PortFailureSite,
577    /// What the port said about it, in the port's own words.
578    pub detail: String,
579}
580
581impl EventPayload for PortFailurePayload {
582    const KIND: &'static str = "port_failure";
583}
584
585impl Sample for PortFailurePayload {
586    fn sample_full() -> Self {
587        Self {
588            event_id: EventId::sample_full(),
589            site: PortFailureSite::sample_full(),
590            detail: "the printer is unreachable: connection refused".to_owned(),
591        }
592    }
593}
594
595/// Every kind of the printer timeline: prints starting and ending, what they
596/// took from a spool, every change to the spool ledger, every change the
597/// printer watch finds in the machine, every recovery, and the operator's word
598/// that the bed is clear.
599pub const TIMELINE_KINDS: [&str; 24] = [
600    PrintStartedPayload::KIND,
601    PrintEndedPayload::KIND,
602    FilamentConsumedPayload::KIND,
603    SpoolRegisteredPayload::KIND,
604    SpoolLoadedPayload::KIND,
605    SpoolUnloadedPayload::KIND,
606    SpoolAdjustedPayload::KIND,
607    SpoolRetiredPayload::KIND,
608    SpoolCommandRejectedPayload::KIND,
609    SpoolUnverifiedPayload::KIND,
610    FilamentChangeSignalledPayload::KIND,
611    UnaccountedPrintPayload::KIND,
612    PreflightCheckedPayload::KIND,
613    ChargePendedPayload::KIND,
614    PrintUntrackedPayload::KIND,
615    FileTallyRebaselinedPayload::KIND,
616    PrinterConnectionChangedPayload::KIND,
617    PrinterResetPayload::KIND,
618    UnattendedPrinterActivityPayload::KIND,
619    DetectorHealthChangedPayload::KIND,
620    RecoveryRequestedPayload::KIND,
621    RecoveryExecutedPayload::KIND,
622    RecoveryRejectedPayload::KIND,
623    BedClearAssertedPayload::KIND,
624];
625
626/// A fixed spool identifier the timeline's samples share.
627fn sample_spool_id() -> SpoolId {
628    SpoolId::sample_full()
629}
630
631/// The reason the timeline's samples of a spool command carry.
632fn sample_reason() -> String {
633    "the spool on the shelf changed".to_owned()
634}
635
636/// A print started.
637#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
638#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
639#[schemars(crate = "printobserver_types::schemars")]
640pub struct PrintStartedPayload {
641    /// The file being printed, when it is known.
642    #[serde(default, skip_serializing_if = "Option::is_none")]
643    pub file_name: Option<String>,
644    /// The action that started it; absent when the print was observed rather
645    /// than started through this system.
646    #[serde(default, skip_serializing_if = "Option::is_none")]
647    pub started_by: Option<ActionId>,
648    /// The spool loaded on each tool as it started.
649    pub loaded: Vec<LoadedSpool>,
650    /// The filament check made before it started, when one was.
651    #[serde(default, skip_serializing_if = "Option::is_none")]
652    pub preflight: Option<Preflight>,
653}
654
655impl EventPayload for PrintStartedPayload {
656    const KIND: &'static str = "print_started";
657}
658
659impl Sample for PrintStartedPayload {
660    fn sample_full() -> Self {
661        Self {
662            file_name: Some("benchy.gcode".to_owned()),
663            started_by: Some(ActionId::sample_full()),
664            loaded: vec![LoadedSpool::sample_full()],
665            preflight: Some(Preflight::sample_full()),
666        }
667    }
668
669    fn sample_minimal() -> Self {
670        Self {
671            file_name: None,
672            started_by: None,
673            loaded: Vec::new(),
674            preflight: None,
675        }
676    }
677}
678
679/// A print ended.
680#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
681#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
682#[schemars(crate = "printobserver_types::schemars")]
683pub struct PrintEndedPayload {
684    /// How it ended.
685    pub outcome: PrintOutcome,
686    /// The state the printer was in as it ended.
687    pub state: PrinterState,
688    /// Why it ended, in the words the end was recorded with.
689    pub reason: String,
690    /// How far into its file it last read, when that was read.
691    #[serde(default, skip_serializing_if = "Option::is_none")]
692    pub last_position: Option<FilePosition>,
693}
694
695impl EventPayload for PrintEndedPayload {
696    const KIND: &'static str = "print_ended";
697}
698
699impl Sample for PrintEndedPayload {
700    fn sample_full() -> Self {
701        Self {
702            outcome: PrintOutcome::Cancelled,
703            state: PrinterState::Cancelling,
704            reason: "the operator cancelled it".to_owned(),
705            last_position: Some(FilePosition::sample_full()),
706        }
707    }
708
709    fn sample_minimal() -> Self {
710        Self {
711            outcome: PrintOutcome::Completed,
712            state: PrinterState::Operational,
713            reason: "finished".to_owned(),
714            last_position: None,
715        }
716    }
717}
718
719/// Filament was charged against a spool, or recorded uncharged.
720#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
721#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
722#[schemars(crate = "printobserver_types::schemars")]
723pub struct FilamentConsumedPayload {
724    /// The durable identity of this debit.
725    pub charge_key: ChargeKey,
726    /// The tool that fed it, as its key names it.
727    pub tool: i64,
728    /// How the length was worked out.
729    pub method: ChargeMethod,
730    /// How much was fed, in millimetres.
731    pub length_mm: f64,
732    /// The spool charged and the whole calculation of what it was charged;
733    /// absent when nothing was tracked on the tool, and the filament was
734    /// recorded uncharged.
735    #[serde(default, skip_serializing_if = "Option::is_none")]
736    pub charged: Option<ChargedFilament>,
737    /// The file's analysed length for the tool, in millimetres, when it had one.
738    #[serde(default, skip_serializing_if = "Option::is_none")]
739    pub analysed_length_mm: Option<f64>,
740    /// How far into the file the charge runs, when that was read.
741    #[serde(default, skip_serializing_if = "Option::is_none")]
742    pub position: Option<FilePosition>,
743    /// Anything a reader needs to make sense of the figure.
744    #[serde(default, skip_serializing_if = "Option::is_none")]
745    pub note: Option<String>,
746}
747
748impl EventPayload for FilamentConsumedPayload {
749    const KIND: &'static str = "filament_consumed";
750}
751
752impl Sample for FilamentConsumedPayload {
753    fn sample_full() -> Self {
754        Self {
755            charge_key: ChargeKey::sample_full(),
756            tool: 0,
757            method: ChargeMethod::GcodeExtrusion,
758            length_mm: 1_000.0,
759            charged: Some(ChargedFilament::sample_full()),
760            analysed_length_mm: Some(5_120.0),
761            position: Some(FilePosition::sample_full()),
762            note: Some("charged up to the filament change".to_owned()),
763        }
764    }
765
766    fn sample_minimal() -> Self {
767        Self {
768            charge_key: ChargeKey::sample_full(),
769            tool: 0,
770            method: ChargeMethod::SlicerEstimate,
771            length_mm: 5_120.0,
772            charged: None,
773            analysed_length_mm: None,
774            position: None,
775            note: None,
776        }
777    }
778}
779
780/// A spool was registered.
781#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
782#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
783#[schemars(crate = "printobserver_types::schemars")]
784pub struct SpoolRegisteredPayload {
785    /// The spool, as it was registered.
786    pub spool: SpoolRecord,
787    /// Who registered it.
788    pub actor: Actor,
789    /// Why.
790    pub reason: String,
791}
792
793impl EventPayload for SpoolRegisteredPayload {
794    const KIND: &'static str = "spool_registered";
795}
796
797impl Sample for SpoolRegisteredPayload {
798    fn sample_full() -> Self {
799        Self {
800            spool: SpoolRecord::sample_full(),
801            actor: Actor::Operator,
802            reason: sample_reason(),
803        }
804    }
805
806    fn sample_minimal() -> Self {
807        Self {
808            spool: SpoolRecord::sample_minimal(),
809            ..Self::sample_full()
810        }
811    }
812}
813
814/// A spool was loaded onto a tool, or confirmed as never having left it.
815#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
816#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
817#[schemars(crate = "printobserver_types::schemars")]
818pub struct SpoolLoadedPayload {
819    /// The spool loaded.
820    pub spool_id: SpoolId,
821    /// The tool, in the printer's own numbering.
822    pub tool: i64,
823    /// The spool the load swapped off the tool, when it was occupied.
824    #[serde(default, skip_serializing_if = "Option::is_none")]
825    pub replaced: Option<SpoolId>,
826    /// The pending charges the load took, each also its own
827    /// `filament_consumed` event under its key.
828    #[serde(default, skip_serializing_if = "Vec::is_empty")]
829    pub took_pending: Vec<PendingTaken>,
830    /// Every mark the load cleared, on either spool.
831    #[serde(default, skip_serializing_if = "Vec::is_empty")]
832    pub cleared_marks: Vec<ClearedMark>,
833    /// Who loaded it.
834    pub actor: Actor,
835    /// Why.
836    pub reason: String,
837}
838
839impl EventPayload for SpoolLoadedPayload {
840    const KIND: &'static str = "spool_loaded";
841}
842
843impl Sample for SpoolLoadedPayload {
844    fn sample_full() -> Self {
845        Self {
846            spool_id: sample_spool_id(),
847            tool: 0,
848            replaced: Some(ClearedMark::sample_full().spool_id),
849            took_pending: vec![PendingTaken::sample_full()],
850            cleared_marks: vec![ClearedMark::sample_full()],
851            actor: Actor::Operator,
852            reason: sample_reason(),
853        }
854    }
855
856    fn sample_minimal() -> Self {
857        Self {
858            replaced: None,
859            took_pending: Vec::new(),
860            cleared_marks: Vec::new(),
861            ..Self::sample_full()
862        }
863    }
864}
865
866/// A spool was unloaded from its tool.
867#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
868#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
869#[schemars(crate = "printobserver_types::schemars")]
870pub struct SpoolUnloadedPayload {
871    /// The spool unloaded.
872    pub spool_id: SpoolId,
873    /// The tool it left.
874    pub tool: i64,
875    /// Who unloaded it.
876    pub actor: Actor,
877    /// Why.
878    pub reason: String,
879}
880
881impl EventPayload for SpoolUnloadedPayload {
882    const KIND: &'static str = "spool_unloaded";
883}
884
885impl Sample for SpoolUnloadedPayload {
886    fn sample_full() -> Self {
887        Self {
888            spool_id: sample_spool_id(),
889            tool: 0,
890            actor: Actor::Operator,
891            reason: sample_reason(),
892        }
893    }
894}
895
896/// A spool's remaining figure was corrected.
897#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
898#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
899#[schemars(crate = "printobserver_types::schemars")]
900pub struct SpoolAdjustedPayload {
901    /// The spool corrected.
902    pub spool_id: SpoolId,
903    /// Its figure before, in grams, after any pending charge it took.
904    pub remaining_before_g: f64,
905    /// Its figure after, in grams.
906    pub remaining_after_g: f64,
907    /// The scale reading the figure was worked out from, when it was given as
908    /// one.
909    #[serde(default, skip_serializing_if = "Option::is_none")]
910    pub gross_g: Option<f64>,
911    /// The pending charges the correction took first, each also its own
912    /// `filament_consumed` event under its key.
913    #[serde(default, skip_serializing_if = "Vec::is_empty")]
914    pub took_pending: Vec<PendingTaken>,
915    /// Every mark the correction cleared.
916    #[serde(default, skip_serializing_if = "Vec::is_empty")]
917    pub cleared_marks: Vec<ClearedMark>,
918    /// Who corrected it.
919    pub actor: Actor,
920    /// Why.
921    pub reason: String,
922}
923
924impl EventPayload for SpoolAdjustedPayload {
925    const KIND: &'static str = "spool_adjusted";
926}
927
928impl Sample for SpoolAdjustedPayload {
929    fn sample_full() -> Self {
930        Self {
931            spool_id: sample_spool_id(),
932            remaining_before_g: 742.5,
933            remaining_after_g: 700.0,
934            gross_g: Some(950.0),
935            took_pending: vec![PendingTaken::sample_full()],
936            cleared_marks: vec![ClearedMark {
937                spool_id: sample_spool_id(),
938                reason: UnverifiedReason::sample_full(),
939            }],
940            actor: Actor::Operator,
941            reason: sample_reason(),
942        }
943    }
944
945    fn sample_minimal() -> Self {
946        Self {
947            gross_g: None,
948            took_pending: Vec::new(),
949            cleared_marks: Vec::new(),
950            ..Self::sample_full()
951        }
952    }
953}
954
955/// A spool was retired.
956#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
957#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
958#[schemars(crate = "printobserver_types::schemars")]
959pub struct SpoolRetiredPayload {
960    /// The spool retired.
961    pub spool_id: SpoolId,
962    /// Its figure as it was retired, in grams.
963    pub remaining_g: f64,
964    /// Who retired it.
965    pub actor: Actor,
966    /// Why.
967    pub reason: String,
968}
969
970impl EventPayload for SpoolRetiredPayload {
971    const KIND: &'static str = "spool_retired";
972}
973
974impl Sample for SpoolRetiredPayload {
975    fn sample_full() -> Self {
976        Self {
977            spool_id: sample_spool_id(),
978            remaining_g: 12.5,
979            actor: Actor::Operator,
980            reason: "the spool is empty".to_owned(),
981        }
982    }
983}
984
985/// A spool command was refused.
986#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
987#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
988#[schemars(crate = "printobserver_types::schemars")]
989pub struct SpoolCommandRejectedPayload {
990    /// The command, as it was asked for.
991    pub command: SpoolCommand,
992    /// The whole decision, carrying which refusal it was.
993    pub decision: PolicyDecision,
994}
995
996impl EventPayload for SpoolCommandRejectedPayload {
997    const KIND: &'static str = "spool_command_rejected";
998}
999
1000impl Sample for SpoolCommandRejectedPayload {
1001    fn sample_full() -> Self {
1002        Self {
1003            command: SpoolCommand::sample_full(),
1004            decision: PolicyDecision::Rejected(crate::records::RejectionReason::SpoolRefused {
1005                cause: crate::records::SpoolRefusalCause::DensityRequired {
1006                    spool_id: None,
1007                    material: "PEEK".to_owned(),
1008                },
1009                message: "PEEK has no known density, so the spool needs one".to_owned(),
1010            }),
1011        }
1012    }
1013
1014    fn sample_minimal() -> Self {
1015        Self {
1016            command: SpoolCommand::sample_minimal(),
1017            ..Self::sample_full()
1018        }
1019    }
1020}
1021
1022/// A spool was marked as one whose figure is in doubt.
1023#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1024#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1025#[schemars(crate = "printobserver_types::schemars")]
1026pub struct SpoolUnverifiedPayload {
1027    /// The spool marked.
1028    pub spool_id: SpoolId,
1029    /// Why its figure is in doubt.
1030    pub reason: UnverifiedReason,
1031}
1032
1033impl EventPayload for SpoolUnverifiedPayload {
1034    const KIND: &'static str = "spool_unverified";
1035}
1036
1037impl Sample for SpoolUnverifiedPayload {
1038    fn sample_full() -> Self {
1039        Self {
1040            spool_id: sample_spool_id(),
1041            reason: UnverifiedReason::sample_full(),
1042        }
1043    }
1044}
1045
1046/// A filament change was signalled during a print.
1047#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1048#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1049#[schemars(crate = "printobserver_types::schemars")]
1050pub struct FilamentChangeSignalledPayload {
1051    /// The tool the change was signalled for, when it is known.
1052    #[serde(default, skip_serializing_if = "Option::is_none")]
1053    pub tool: Option<i64>,
1054    /// The spool that was on it, when one was tracked.
1055    #[serde(default, skip_serializing_if = "Option::is_none")]
1056    pub spool_id: Option<SpoolId>,
1057    /// The kind of the alert that carried the signal.
1058    pub source_kind: EventKind,
1059    /// The position the spool was charged up to, and how fresh it is, when one
1060    /// was known; absent, there is no position and so no claim about one.
1061    #[serde(default, skip_serializing_if = "Option::is_none")]
1062    pub position: Option<SignalPosition>,
1063}
1064
1065/// The position a filament change charged up to, and how fresh it is.
1066#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1067#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1068#[schemars(crate = "printobserver_types::schemars")]
1069pub struct SignalPosition {
1070    /// The position.
1071    pub position: FilePosition,
1072    /// Whether it was read when the signal was handled, or is the last one
1073    /// recorded before it.
1074    pub freshness: PositionFreshness,
1075}
1076
1077/// How fresh the position a filament change charged up to is.
1078#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1079#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
1080#[schemars(crate = "printobserver_types::schemars")]
1081pub enum PositionFreshness {
1082    /// Read from the job as the signal was handled: where the spool stopped.
1083    ReadAtSignal,
1084    /// The last position recorded before the signal, the job reporting none
1085    /// as it was handled: the spool may have fed past it.
1086    LastRecorded,
1087}
1088
1089impl EventPayload for FilamentChangeSignalledPayload {
1090    const KIND: &'static str = "filament_change_signalled";
1091}
1092
1093impl Sample for FilamentChangeSignalledPayload {
1094    fn sample_full() -> Self {
1095        Self {
1096            tool: Some(0),
1097            spool_id: Some(sample_spool_id()),
1098            source_kind: EventKind::new("obico_printer_notification").expect("a kind name"),
1099            position: Some(SignalPosition {
1100                position: FilePosition::sample_full(),
1101                freshness: PositionFreshness::ReadAtSignal,
1102            }),
1103        }
1104    }
1105
1106    fn sample_minimal() -> Self {
1107        Self {
1108            tool: None,
1109            spool_id: None,
1110            position: None,
1111            ..Self::sample_full()
1112        }
1113    }
1114}
1115
1116/// A print this system never saw was found in the printer's own tally.
1117#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1118#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1119#[schemars(crate = "printobserver_types::schemars")]
1120pub struct UnaccountedPrintPayload {
1121    /// The file that was printed.
1122    pub file_name: String,
1123    /// When it was printed, when the printer says.
1124    #[serde(default, skip_serializing_if = "Option::is_none")]
1125    pub printed_at: Option<Timestamp>,
1126    /// Whether it completed.
1127    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
1128    pub success: bool,
1129    /// Whether it was charged against a spool.
1130    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
1131    pub charged: bool,
1132}
1133
1134impl EventPayload for UnaccountedPrintPayload {
1135    const KIND: &'static str = "unaccounted_print";
1136}
1137
1138impl Sample for UnaccountedPrintPayload {
1139    fn sample_full() -> Self {
1140        Self {
1141            file_name: "benchy.gcode".to_owned(),
1142            printed_at: Some(Timestamp::sample_full()),
1143            success: true,
1144            charged: true,
1145        }
1146    }
1147
1148    fn sample_minimal() -> Self {
1149        Self {
1150            printed_at: None,
1151            success: false,
1152            charged: false,
1153            ..Self::sample_full()
1154        }
1155    }
1156}
1157
1158/// The filament check before a start was made.
1159#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1160#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1161#[schemars(crate = "printobserver_types::schemars")]
1162pub struct PreflightCheckedPayload {
1163    /// What the check found.
1164    pub preflight: Preflight,
1165    /// The start it was made for, when it was made for one.
1166    #[serde(default, skip_serializing_if = "Option::is_none")]
1167    pub action_id: Option<ActionId>,
1168}
1169
1170impl EventPayload for PreflightCheckedPayload {
1171    const KIND: &'static str = "preflight_checked";
1172}
1173
1174impl Sample for PreflightCheckedPayload {
1175    fn sample_full() -> Self {
1176        Self {
1177            preflight: Preflight::sample_full(),
1178            action_id: Some(ActionId::sample_full()),
1179        }
1180    }
1181
1182    fn sample_minimal() -> Self {
1183        Self {
1184            action_id: None,
1185            ..Self::sample_full()
1186        }
1187    }
1188}
1189
1190/// Filament a tool fed after an unconfirmed filament change was held for the
1191/// next spool loaded onto that tool, or confirmed on it.
1192#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1193#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1194#[schemars(crate = "printobserver_types::schemars")]
1195pub struct ChargePendedPayload {
1196    /// What was held.
1197    pub pending: PendingCharge,
1198}
1199
1200impl EventPayload for ChargePendedPayload {
1201    const KIND: &'static str = "charge_pended";
1202}
1203
1204impl Sample for ChargePendedPayload {
1205    fn sample_full() -> Self {
1206        Self {
1207            pending: PendingCharge::sample_full(),
1208        }
1209    }
1210
1211    fn sample_minimal() -> Self {
1212        Self {
1213            pending: PendingCharge::sample_minimal(),
1214        }
1215    }
1216}
1217
1218/// A print that was already open when spool tracking was installed: it is
1219/// never charged, and this says why it carries no charge.
1220#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1221#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1222#[schemars(crate = "printobserver_types::schemars")]
1223pub struct PrintUntrackedPayload {
1224    /// Why the print carries no charge.
1225    pub reason: String,
1226}
1227
1228impl EventPayload for PrintUntrackedPayload {
1229    const KIND: &'static str = "print_untracked";
1230}
1231
1232impl Sample for PrintUntrackedPayload {
1233    fn sample_full() -> Self {
1234        Self {
1235            reason: "the print was already running when spool tracking was installed".to_owned(),
1236        }
1237    }
1238}
1239
1240/// What became of the prints a file's new tally generation counts.
1241#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1242#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
1243#[schemars(crate = "printobserver_types::schemars")]
1244pub enum RebaselineDisposition {
1245    /// They were accounted as prints this system never saw.
1246    Accounted,
1247    /// It could not be told which of them this system already settled, so the
1248    /// loaded spool was marked unverified rather than charged on a guess.
1249    Unverified,
1250}
1251
1252impl Sample for RebaselineDisposition {
1253    fn sample_full() -> Self {
1254        Self::Unverified
1255    }
1256}
1257
1258/// The printer's tally for a file went down — the file was deleted and
1259/// uploaded again — so the file's tally generation advanced, and the new count
1260/// is that generation's growth from zero.
1261///
1262/// The rebaseline itself marks no spool; only an `unverified` disposition does.
1263#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1264#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1265#[schemars(crate = "printobserver_types::schemars")]
1266pub struct FileTallyRebaselinedPayload {
1267    /// The file whose tally went down.
1268    pub file_name: String,
1269    /// Where it lives, in the printer's own vocabulary.
1270    pub origin: String,
1271    /// The generation the tally was in.
1272    pub old_generation: u32,
1273    /// The generation it is in now.
1274    pub new_generation: u32,
1275    /// The completed prints the old tally counted.
1276    pub old_successes: i64,
1277    /// The failed prints the old tally counted.
1278    pub old_failures: i64,
1279    /// The completed prints the new tally counts.
1280    pub new_successes: i64,
1281    /// The failed prints the new tally counts.
1282    pub new_failures: i64,
1283    /// What became of the prints the new generation counts.
1284    pub disposition: RebaselineDisposition,
1285}
1286
1287impl EventPayload for FileTallyRebaselinedPayload {
1288    const KIND: &'static str = "file_tally_rebaselined";
1289}
1290
1291impl Sample for FileTallyRebaselinedPayload {
1292    fn sample_full() -> Self {
1293        Self {
1294            file_name: "benchy.gcode".to_owned(),
1295            origin: "local".to_owned(),
1296            old_generation: 0,
1297            new_generation: 1,
1298            old_successes: 5,
1299            old_failures: 1,
1300            new_successes: 1,
1301            new_failures: 0,
1302            disposition: RebaselineDisposition::Unverified,
1303        }
1304    }
1305
1306    fn sample_alternates() -> Vec<Self> {
1307        vec![Self {
1308            disposition: RebaselineDisposition::Accounted,
1309            ..Self::sample_full()
1310        }]
1311    }
1312}
1313
1314/// The printer's connection changed into or out of `offline` or `error`: a
1315/// serial disconnect, a reconnect, a printer error.
1316///
1317/// The printer's rather than any print's, so it is written with no print.
1318#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1319#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1320#[schemars(crate = "printobserver_types::schemars")]
1321pub struct PrinterConnectionChangedPayload {
1322    /// The state the previous read found.
1323    pub from: PrinterState,
1324    /// The state this read found.
1325    pub to: PrinterState,
1326    /// What the watch read, in words.
1327    pub detail: String,
1328}
1329
1330impl EventPayload for PrinterConnectionChangedPayload {
1331    const KIND: &'static str = "printer_connection_changed";
1332}
1333
1334impl Sample for PrinterConnectionChangedPayload {
1335    fn sample_full() -> Self {
1336        Self {
1337            from: PrinterState::Printing,
1338            to: PrinterState::Offline,
1339            detail: "the printer reports Offline after error: SerialTimeoutException: ".to_owned(),
1340        }
1341    }
1342
1343    fn sample_alternates() -> Vec<Self> {
1344        vec![Self {
1345            from: PrinterState::Offline,
1346            to: PrinterState::Operational,
1347            detail: "the printer reports Operational".to_owned(),
1348        }]
1349    }
1350}
1351
1352/// The printer reset: its firmware restarted, and whatever it held is gone.
1353///
1354/// Recorded on each reset the printer pushed, one while idle included, which
1355/// changes nothing a read of its state reports. The printer's rather than any
1356/// print's, so it is written with no print; `during_print` names the print it
1357/// happened during, when one was running.
1358#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1359#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1360#[schemars(crate = "printobserver_types::schemars")]
1361pub struct PrinterResetPayload {
1362    /// The print that was running when it reset, `null` when none was.
1363    #[serde(default)]
1364    pub during_print: Option<PrintId>,
1365    /// What the watch knew of it, in words.
1366    pub detail: String,
1367}
1368
1369impl EventPayload for PrinterResetPayload {
1370    const KIND: &'static str = "printer_reset";
1371}
1372
1373impl Sample for PrinterResetPayload {
1374    fn sample_full() -> Self {
1375        Self {
1376            during_print: Some(PrintId::sample_full()),
1377            detail: "the printer pushed a reset".to_owned(),
1378        }
1379    }
1380
1381    fn sample_minimal() -> Self {
1382        Self {
1383            during_print: None,
1384            detail: "the printer pushed a reset".to_owned(),
1385        }
1386    }
1387}
1388
1389/// One tool heater whose target was above zero.
1390#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1391#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1392#[schemars(crate = "printobserver_types::schemars")]
1393pub struct HeatedTool {
1394    /// The tool's number.
1395    pub tool: i64,
1396    /// Its target, in degrees Celsius.
1397    pub target_c: f64,
1398}
1399
1400impl Sample for HeatedTool {
1401    fn sample_full() -> Self {
1402        Self {
1403            tool: 0,
1404            target_c: 215.0,
1405        }
1406    }
1407}
1408
1409/// The printer heated or moved with no job running, soon after a print ended
1410/// `interrupted` or `failed`.
1411///
1412/// A transition rather than a reading: written once when such activity begins,
1413/// and again only when what it reports changes. The printer's rather than any
1414/// print's, so it is written with no print; `last_print_id` names the print it
1415/// came after.
1416#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1417#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1418#[schemars(crate = "printobserver_types::schemars")]
1419pub struct UnattendedPrinterActivityPayload {
1420    /// The print that ended before it.
1421    pub last_print_id: PrintId,
1422    /// Every tool whose target is above zero.
1423    pub tools: Vec<HeatedTool>,
1424    /// The bed's target, when it is above zero; `null` otherwise.
1425    #[serde(default)]
1426    pub bed_target_c: Option<f64>,
1427    /// Whether the print head moved since the last position read, `null` when
1428    /// no position could be read.
1429    #[serde(default)]
1430    pub moved: Option<bool>,
1431    /// What the watch read, in words.
1432    pub detail: String,
1433}
1434
1435impl EventPayload for UnattendedPrinterActivityPayload {
1436    const KIND: &'static str = "unattended_printer_activity";
1437}
1438
1439impl Sample for UnattendedPrinterActivityPayload {
1440    fn sample_full() -> Self {
1441        Self {
1442            last_print_id: PrintId::sample_full(),
1443            tools: vec![HeatedTool::sample_full()],
1444            bed_target_c: Some(60.0),
1445            moved: Some(true),
1446            detail: "tool 0 is heating to 215 °C with no job running".to_owned(),
1447        }
1448    }
1449
1450    fn sample_minimal() -> Self {
1451        Self {
1452            last_print_id: PrintId::sample_full(),
1453            tools: Vec::new(),
1454            bed_target_c: None,
1455            moved: None,
1456            detail: "the print head moved with no job running".to_owned(),
1457        }
1458    }
1459}
1460
1461/// What a check of the failure detector's own health found.
1462#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1463#[serde(
1464    crate = "printobserver_types::serde",
1465    rename_all = "snake_case",
1466    deny_unknown_fields
1467)]
1468#[schemars(crate = "printobserver_types::schemars")]
1469pub enum DetectorStatus {
1470    /// It answered its health check.
1471    Available,
1472    /// It did not: refused, reset, answered otherwise, or not in time.
1473    Unavailable,
1474}
1475
1476impl Sample for DetectorStatus {
1477    fn sample_full() -> Self {
1478        Self::Unavailable
1479    }
1480
1481    fn sample_alternates() -> Vec<Self> {
1482        vec![Self::Available]
1483    }
1484}
1485
1486/// The failure detector's own health changed.
1487///
1488/// The printer's rather than any print's, so it is written with no print.
1489#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1490#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1491#[schemars(crate = "printobserver_types::schemars")]
1492pub struct DetectorHealthChangedPayload {
1493    /// What the check found.
1494    pub status: DetectorStatus,
1495    /// What it was answered, in words.
1496    pub detail: String,
1497}
1498
1499impl EventPayload for DetectorHealthChangedPayload {
1500    const KIND: &'static str = "detector_health_changed";
1501}
1502
1503impl Sample for DetectorHealthChangedPayload {
1504    fn sample_full() -> Self {
1505        Self {
1506            status: DetectorStatus::Unavailable,
1507            detail: "the detector's health check answered 503".to_owned(),
1508        }
1509    }
1510
1511    fn sample_alternates() -> Vec<Self> {
1512        vec![Self {
1513            status: DetectorStatus::Available,
1514            detail: "the detector's health check answered 200".to_owned(),
1515        }]
1516    }
1517}
1518
1519/// A recovery action was asked for.
1520///
1521/// The printer's rather than any print's, so it is written with no print.
1522#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1523#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1524#[schemars(crate = "printobserver_types::schemars")]
1525pub struct RecoveryRequestedPayload {
1526    /// What was asked for.
1527    pub action: RecoveryAction,
1528    /// Who asked.
1529    pub actor: Actor,
1530    /// Why.
1531    pub reason: String,
1532    /// The operator's standing word that the bed is clear this request is
1533    /// decided on in place of an assertion of its own, when it is: the
1534    /// `bed_clear_asserted` event recording it. Absent otherwise.
1535    #[serde(default, skip_serializing_if = "Option::is_none")]
1536    pub bed_clear: Option<EventId>,
1537}
1538
1539impl EventPayload for RecoveryRequestedPayload {
1540    const KIND: &'static str = "recovery_requested";
1541}
1542
1543impl Sample for RecoveryRequestedPayload {
1544    fn sample_full() -> Self {
1545        Self {
1546            action: RecoveryAction::sample_full(),
1547            actor: Actor::Operator,
1548            reason: "free the nozzle from the part".to_owned(),
1549            bed_clear: Some(EventId::sample_full()),
1550        }
1551    }
1552
1553    fn sample_minimal() -> Self {
1554        Self {
1555            bed_clear: None,
1556            ..Self::sample_full()
1557        }
1558    }
1559}
1560
1561/// A recovery action reached the printer, and what the printer made of it.
1562#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1563#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1564#[schemars(crate = "printobserver_types::schemars")]
1565pub struct RecoveryExecutedPayload {
1566    /// What was asked for.
1567    pub action: RecoveryAction,
1568    /// Who asked.
1569    pub actor: Actor,
1570    /// Why.
1571    pub reason: String,
1572    /// What the printer made of it.
1573    pub outcome: crate::records::ExecutionOutcome,
1574    /// The operator's standing word that the bed is clear this action was
1575    /// carried out on in place of an assertion of its own, when it was: the
1576    /// `bed_clear_asserted` event recording it. Absent otherwise.
1577    #[serde(default, skip_serializing_if = "Option::is_none")]
1578    pub bed_clear: Option<EventId>,
1579}
1580
1581impl EventPayload for RecoveryExecutedPayload {
1582    const KIND: &'static str = "recovery_executed";
1583}
1584
1585impl Sample for RecoveryExecutedPayload {
1586    fn sample_full() -> Self {
1587        Self {
1588            action: RecoveryAction::RecoverLift { mm: 10.0 },
1589            actor: Actor::Operator,
1590            reason: "free the nozzle from the part".to_owned(),
1591            outcome: crate::records::ExecutionOutcome::Succeeded,
1592            bed_clear: Some(EventId::sample_full()),
1593        }
1594    }
1595
1596    fn sample_minimal() -> Self {
1597        Self {
1598            bed_clear: None,
1599            ..Self::sample_full()
1600        }
1601    }
1602
1603    fn sample_alternates() -> Vec<Self> {
1604        vec![Self {
1605            outcome: crate::records::ExecutionOutcome::Failed {
1606                reason: "the printer is unreachable: connection refused".to_owned(),
1607            },
1608            ..Self::sample_full()
1609        }]
1610    }
1611}
1612
1613/// A recovery action was refused, and reached nothing.
1614#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1615#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1616#[schemars(crate = "printobserver_types::schemars")]
1617pub struct RecoveryRejectedPayload {
1618    /// What was asked for.
1619    pub action: RecoveryAction,
1620    /// Who asked.
1621    pub actor: Actor,
1622    /// Why.
1623    pub reason: String,
1624    /// Why it was refused.
1625    pub rejection: RecoveryRejection,
1626}
1627
1628impl EventPayload for RecoveryRejectedPayload {
1629    const KIND: &'static str = "recovery_rejected";
1630}
1631
1632impl Sample for RecoveryRejectedPayload {
1633    fn sample_full() -> Self {
1634        Self {
1635            action: RecoveryAction::RecoverPark {
1636                clearance_asserted: false,
1637            },
1638            actor: Actor::Operator,
1639            reason: "move the head off the part".to_owned(),
1640            rejection: RecoveryRejection::sample_full(),
1641        }
1642    }
1643}
1644
1645/// The operator's word that the bed is clear: nothing is on it that homing Z
1646/// could crush or a move over the part could strike.
1647///
1648/// The printer's rather than any print's, so it is written with no print. It
1649/// stands until the next `print_started`, whichever way that print started,
1650/// and while it stands a recovery that needs the bed or the nozzle clear is
1651/// decided as though it carried the operator's assertion — read back out of
1652/// the event log, so a server started again holds it as the one before did.
1653/// Only the operator records one: an assertion is a person's word for what
1654/// they can see.
1655#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1656#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1657#[schemars(crate = "printobserver_types::schemars")]
1658pub struct BedClearAssertedPayload {
1659    /// Who said so: the operator, the one actor whose word this records.
1660    pub actor: BedClearActor,
1661    /// Why they say so.
1662    pub reason: String,
1663}
1664
1665/// Who may say the bed is clear: the operator, and no other actor.
1666///
1667/// Its own type rather than [`Actor`], so that a record of the agent's or the
1668/// system's word that the bed is clear is one no value can spell. On the wire
1669/// it is `"operator"`, as [`Actor::Operator`] is.
1670#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1671#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
1672#[schemars(crate = "printobserver_types::schemars")]
1673pub enum BedClearActor {
1674    /// A person: the operator.
1675    Operator,
1676}
1677
1678impl BedClearActor {
1679    /// The actor this is, in the vocabulary every other record names actors in.
1680    #[must_use]
1681    pub const fn actor(self) -> Actor {
1682        match self {
1683            Self::Operator => Actor::Operator,
1684        }
1685    }
1686}
1687
1688impl EventPayload for BedClearAssertedPayload {
1689    const KIND: &'static str = "bed_clear_asserted";
1690}
1691
1692impl Sample for BedClearAssertedPayload {
1693    fn sample_full() -> Self {
1694        Self {
1695            actor: BedClearActor::Operator,
1696            reason: "the cancelled print is off the bed and nothing else is on it".to_owned(),
1697        }
1698    }
1699}