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