Skip to main content

printobserver_core/
kinds.rs

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