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