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