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