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-five 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, CAMERA_CHECKED_KIND, CameraCheckId, ChargeKey,
28    ChargeMethod, ChargedFilament, ClearedMark, FilePosition, InterventionId, InterventionOutcome,
29    LoadedSpool, PendingCharge, PendingTaken, PolicyDecision, Preflight, PrintAction, PrintOutcome,
30    RecoveryAction, 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, the operator's word
599/// that the bed is clear, and every check of the camera on the empty sheet,
600/// whose payload the server declares.
601pub const TIMELINE_KINDS: [&str; 25] = [
602    PrintStartedPayload::KIND,
603    PrintEndedPayload::KIND,
604    FilamentConsumedPayload::KIND,
605    SpoolRegisteredPayload::KIND,
606    SpoolLoadedPayload::KIND,
607    SpoolUnloadedPayload::KIND,
608    SpoolAdjustedPayload::KIND,
609    SpoolRetiredPayload::KIND,
610    SpoolCommandRejectedPayload::KIND,
611    SpoolUnverifiedPayload::KIND,
612    FilamentChangeSignalledPayload::KIND,
613    UnaccountedPrintPayload::KIND,
614    PreflightCheckedPayload::KIND,
615    ChargePendedPayload::KIND,
616    PrintUntrackedPayload::KIND,
617    FileTallyRebaselinedPayload::KIND,
618    PrinterConnectionChangedPayload::KIND,
619    PrinterResetPayload::KIND,
620    UnattendedPrinterActivityPayload::KIND,
621    DetectorHealthChangedPayload::KIND,
622    RecoveryRequestedPayload::KIND,
623    RecoveryExecutedPayload::KIND,
624    RecoveryRejectedPayload::KIND,
625    BedClearAssertedPayload::KIND,
626    CAMERA_CHECKED_KIND,
627];
628
629/// A fixed spool identifier the timeline's samples share.
630fn sample_spool_id() -> SpoolId {
631    SpoolId::sample_full()
632}
633
634/// The reason the timeline's samples of a spool command carry.
635fn sample_reason() -> String {
636    "the spool on the shelf changed".to_owned()
637}
638
639/// A print started.
640#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
641#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
642#[schemars(crate = "printobserver_types::schemars")]
643pub struct PrintStartedPayload {
644    /// The file being printed, when it is known.
645    #[serde(default, skip_serializing_if = "Option::is_none")]
646    pub file_name: Option<String>,
647    /// The action that started it; absent when the print was observed rather
648    /// than started through this system.
649    #[serde(default, skip_serializing_if = "Option::is_none")]
650    pub started_by: Option<ActionId>,
651    /// The spool loaded on each tool as it started.
652    pub loaded: Vec<LoadedSpool>,
653    /// The filament check made before it started, when one was.
654    #[serde(default, skip_serializing_if = "Option::is_none")]
655    pub preflight: Option<Preflight>,
656    /// The camera check its manifest named, which every check of the print is
657    /// drawn through; absent when it named none.
658    #[serde(default, skip_serializing_if = "Option::is_none")]
659    pub camera_check: Option<CameraCheckId>,
660}
661
662impl EventPayload for PrintStartedPayload {
663    const KIND: &'static str = "print_started";
664}
665
666impl Sample for PrintStartedPayload {
667    fn sample_full() -> Self {
668        Self {
669            file_name: Some("benchy.gcode".to_owned()),
670            started_by: Some(ActionId::sample_full()),
671            loaded: vec![LoadedSpool::sample_full()],
672            preflight: Some(Preflight::sample_full()),
673            camera_check: Some(CameraCheckId::sample_full()),
674        }
675    }
676
677    fn sample_minimal() -> Self {
678        Self {
679            file_name: None,
680            started_by: None,
681            loaded: Vec::new(),
682            preflight: None,
683            camera_check: None,
684        }
685    }
686}
687
688/// A print ended.
689#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
690#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
691#[schemars(crate = "printobserver_types::schemars")]
692pub struct PrintEndedPayload {
693    /// How it ended.
694    pub outcome: PrintOutcome,
695    /// The state the printer was in as it ended.
696    pub state: PrinterState,
697    /// Why it ended, in the words the end was recorded with.
698    pub reason: String,
699    /// How far into its file it last read, when that was read.
700    #[serde(default, skip_serializing_if = "Option::is_none")]
701    pub last_position: Option<FilePosition>,
702}
703
704impl EventPayload for PrintEndedPayload {
705    const KIND: &'static str = "print_ended";
706}
707
708impl Sample for PrintEndedPayload {
709    fn sample_full() -> Self {
710        Self {
711            outcome: PrintOutcome::Cancelled,
712            state: PrinterState::Cancelling,
713            reason: "the operator cancelled it".to_owned(),
714            last_position: Some(FilePosition::sample_full()),
715        }
716    }
717
718    fn sample_minimal() -> Self {
719        Self {
720            outcome: PrintOutcome::Completed,
721            state: PrinterState::Operational,
722            reason: "finished".to_owned(),
723            last_position: None,
724        }
725    }
726}
727
728/// Filament was charged against a spool, or recorded uncharged.
729#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
730#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
731#[schemars(crate = "printobserver_types::schemars")]
732pub struct FilamentConsumedPayload {
733    /// The durable identity of this debit.
734    pub charge_key: ChargeKey,
735    /// The tool that fed it, as its key names it.
736    pub tool: i64,
737    /// How the length was worked out.
738    pub method: ChargeMethod,
739    /// How much was fed, in millimetres.
740    pub length_mm: f64,
741    /// The spool charged and the whole calculation of what it was charged;
742    /// absent when nothing was tracked on the tool, and the filament was
743    /// recorded uncharged.
744    #[serde(default, skip_serializing_if = "Option::is_none")]
745    pub charged: Option<ChargedFilament>,
746    /// The file's analysed length for the tool, in millimetres, when it had one.
747    #[serde(default, skip_serializing_if = "Option::is_none")]
748    pub analysed_length_mm: Option<f64>,
749    /// How far into the file the charge runs, when that was read.
750    #[serde(default, skip_serializing_if = "Option::is_none")]
751    pub position: Option<FilePosition>,
752    /// Anything a reader needs to make sense of the figure.
753    #[serde(default, skip_serializing_if = "Option::is_none")]
754    pub note: Option<String>,
755}
756
757impl EventPayload for FilamentConsumedPayload {
758    const KIND: &'static str = "filament_consumed";
759}
760
761impl Sample for FilamentConsumedPayload {
762    fn sample_full() -> Self {
763        Self {
764            charge_key: ChargeKey::sample_full(),
765            tool: 0,
766            method: ChargeMethod::GcodeExtrusion,
767            length_mm: 1_000.0,
768            charged: Some(ChargedFilament::sample_full()),
769            analysed_length_mm: Some(5_120.0),
770            position: Some(FilePosition::sample_full()),
771            note: Some("charged up to the filament change".to_owned()),
772        }
773    }
774
775    fn sample_minimal() -> Self {
776        Self {
777            charge_key: ChargeKey::sample_full(),
778            tool: 0,
779            method: ChargeMethod::SlicerEstimate,
780            length_mm: 5_120.0,
781            charged: None,
782            analysed_length_mm: None,
783            position: None,
784            note: None,
785        }
786    }
787}
788
789/// A spool was registered.
790#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
791#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
792#[schemars(crate = "printobserver_types::schemars")]
793pub struct SpoolRegisteredPayload {
794    /// The spool, as it was registered.
795    pub spool: SpoolRecord,
796    /// Who registered it.
797    pub actor: Actor,
798    /// Why.
799    pub reason: String,
800}
801
802impl EventPayload for SpoolRegisteredPayload {
803    const KIND: &'static str = "spool_registered";
804}
805
806impl Sample for SpoolRegisteredPayload {
807    fn sample_full() -> Self {
808        Self {
809            spool: SpoolRecord::sample_full(),
810            actor: Actor::Operator,
811            reason: sample_reason(),
812        }
813    }
814
815    fn sample_minimal() -> Self {
816        Self {
817            spool: SpoolRecord::sample_minimal(),
818            ..Self::sample_full()
819        }
820    }
821}
822
823/// A spool was loaded onto a tool, or confirmed as never having left it.
824#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
825#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
826#[schemars(crate = "printobserver_types::schemars")]
827pub struct SpoolLoadedPayload {
828    /// The spool loaded.
829    pub spool_id: SpoolId,
830    /// The tool, in the printer's own numbering.
831    pub tool: i64,
832    /// The spool the load swapped off the tool, when it was occupied.
833    #[serde(default, skip_serializing_if = "Option::is_none")]
834    pub replaced: Option<SpoolId>,
835    /// The pending charges the load took, each also its own
836    /// `filament_consumed` event under its key.
837    #[serde(default, skip_serializing_if = "Vec::is_empty")]
838    pub took_pending: Vec<PendingTaken>,
839    /// Every mark the load cleared, on either spool.
840    #[serde(default, skip_serializing_if = "Vec::is_empty")]
841    pub cleared_marks: Vec<ClearedMark>,
842    /// Who loaded it.
843    pub actor: Actor,
844    /// Why.
845    pub reason: String,
846}
847
848impl EventPayload for SpoolLoadedPayload {
849    const KIND: &'static str = "spool_loaded";
850}
851
852impl Sample for SpoolLoadedPayload {
853    fn sample_full() -> Self {
854        Self {
855            spool_id: sample_spool_id(),
856            tool: 0,
857            replaced: Some(ClearedMark::sample_full().spool_id),
858            took_pending: vec![PendingTaken::sample_full()],
859            cleared_marks: vec![ClearedMark::sample_full()],
860            actor: Actor::Operator,
861            reason: sample_reason(),
862        }
863    }
864
865    fn sample_minimal() -> Self {
866        Self {
867            replaced: None,
868            took_pending: Vec::new(),
869            cleared_marks: Vec::new(),
870            ..Self::sample_full()
871        }
872    }
873}
874
875/// A spool was unloaded from its tool.
876#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
877#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
878#[schemars(crate = "printobserver_types::schemars")]
879pub struct SpoolUnloadedPayload {
880    /// The spool unloaded.
881    pub spool_id: SpoolId,
882    /// The tool it left.
883    pub tool: i64,
884    /// Who unloaded it.
885    pub actor: Actor,
886    /// Why.
887    pub reason: String,
888}
889
890impl EventPayload for SpoolUnloadedPayload {
891    const KIND: &'static str = "spool_unloaded";
892}
893
894impl Sample for SpoolUnloadedPayload {
895    fn sample_full() -> Self {
896        Self {
897            spool_id: sample_spool_id(),
898            tool: 0,
899            actor: Actor::Operator,
900            reason: sample_reason(),
901        }
902    }
903}
904
905/// A spool's remaining figure was corrected.
906#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
907#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
908#[schemars(crate = "printobserver_types::schemars")]
909pub struct SpoolAdjustedPayload {
910    /// The spool corrected.
911    pub spool_id: SpoolId,
912    /// Its figure before, in grams, after any pending charge it took.
913    pub remaining_before_g: f64,
914    /// Its figure after, in grams.
915    pub remaining_after_g: f64,
916    /// The scale reading the figure was worked out from, when it was given as
917    /// one.
918    #[serde(default, skip_serializing_if = "Option::is_none")]
919    pub gross_g: Option<f64>,
920    /// The pending charges the correction took first, each also its own
921    /// `filament_consumed` event under its key.
922    #[serde(default, skip_serializing_if = "Vec::is_empty")]
923    pub took_pending: Vec<PendingTaken>,
924    /// Every mark the correction cleared.
925    #[serde(default, skip_serializing_if = "Vec::is_empty")]
926    pub cleared_marks: Vec<ClearedMark>,
927    /// Who corrected it.
928    pub actor: Actor,
929    /// Why.
930    pub reason: String,
931}
932
933impl EventPayload for SpoolAdjustedPayload {
934    const KIND: &'static str = "spool_adjusted";
935}
936
937impl Sample for SpoolAdjustedPayload {
938    fn sample_full() -> Self {
939        Self {
940            spool_id: sample_spool_id(),
941            remaining_before_g: 742.5,
942            remaining_after_g: 700.0,
943            gross_g: Some(950.0),
944            took_pending: vec![PendingTaken::sample_full()],
945            cleared_marks: vec![ClearedMark {
946                spool_id: sample_spool_id(),
947                reason: UnverifiedReason::sample_full(),
948            }],
949            actor: Actor::Operator,
950            reason: sample_reason(),
951        }
952    }
953
954    fn sample_minimal() -> Self {
955        Self {
956            gross_g: None,
957            took_pending: Vec::new(),
958            cleared_marks: Vec::new(),
959            ..Self::sample_full()
960        }
961    }
962}
963
964/// A spool was retired.
965#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
966#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
967#[schemars(crate = "printobserver_types::schemars")]
968pub struct SpoolRetiredPayload {
969    /// The spool retired.
970    pub spool_id: SpoolId,
971    /// Its figure as it was retired, in grams.
972    pub remaining_g: f64,
973    /// Who retired it.
974    pub actor: Actor,
975    /// Why.
976    pub reason: String,
977}
978
979impl EventPayload for SpoolRetiredPayload {
980    const KIND: &'static str = "spool_retired";
981}
982
983impl Sample for SpoolRetiredPayload {
984    fn sample_full() -> Self {
985        Self {
986            spool_id: sample_spool_id(),
987            remaining_g: 12.5,
988            actor: Actor::Operator,
989            reason: "the spool is empty".to_owned(),
990        }
991    }
992}
993
994/// A spool command was refused.
995#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
996#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
997#[schemars(crate = "printobserver_types::schemars")]
998pub struct SpoolCommandRejectedPayload {
999    /// The command, as it was asked for.
1000    pub command: SpoolCommand,
1001    /// The whole decision, carrying which refusal it was.
1002    pub decision: PolicyDecision,
1003}
1004
1005impl EventPayload for SpoolCommandRejectedPayload {
1006    const KIND: &'static str = "spool_command_rejected";
1007}
1008
1009impl Sample for SpoolCommandRejectedPayload {
1010    fn sample_full() -> Self {
1011        Self {
1012            command: SpoolCommand::sample_full(),
1013            decision: PolicyDecision::Rejected(crate::records::RejectionReason::SpoolRefused {
1014                cause: crate::records::SpoolRefusalCause::DensityRequired {
1015                    spool_id: None,
1016                    material: "PEEK".to_owned(),
1017                },
1018                message: "PEEK has no known density, so the spool needs one".to_owned(),
1019            }),
1020        }
1021    }
1022
1023    fn sample_minimal() -> Self {
1024        Self {
1025            command: SpoolCommand::sample_minimal(),
1026            ..Self::sample_full()
1027        }
1028    }
1029}
1030
1031/// A spool was marked as one whose figure is in doubt.
1032#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1033#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1034#[schemars(crate = "printobserver_types::schemars")]
1035pub struct SpoolUnverifiedPayload {
1036    /// The spool marked.
1037    pub spool_id: SpoolId,
1038    /// Why its figure is in doubt.
1039    pub reason: UnverifiedReason,
1040}
1041
1042impl EventPayload for SpoolUnverifiedPayload {
1043    const KIND: &'static str = "spool_unverified";
1044}
1045
1046impl Sample for SpoolUnverifiedPayload {
1047    fn sample_full() -> Self {
1048        Self {
1049            spool_id: sample_spool_id(),
1050            reason: UnverifiedReason::sample_full(),
1051        }
1052    }
1053}
1054
1055/// A filament change was signalled during a print.
1056#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1057#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1058#[schemars(crate = "printobserver_types::schemars")]
1059pub struct FilamentChangeSignalledPayload {
1060    /// The tool the change was signalled for, when it is known.
1061    #[serde(default, skip_serializing_if = "Option::is_none")]
1062    pub tool: Option<i64>,
1063    /// The spool that was on it, when one was tracked.
1064    #[serde(default, skip_serializing_if = "Option::is_none")]
1065    pub spool_id: Option<SpoolId>,
1066    /// The kind of the alert that carried the signal.
1067    pub source_kind: EventKind,
1068    /// The position the spool was charged up to, and how fresh it is, when one
1069    /// was known; absent, there is no position and so no claim about one.
1070    #[serde(default, skip_serializing_if = "Option::is_none")]
1071    pub position: Option<SignalPosition>,
1072    /// The index of the planned change the print stopped at, which the spool
1073    /// was charged up to the offset of; absent when no change was planned at
1074    /// that position, and on a record written before changes were planned.
1075    #[serde(default, skip_serializing_if = "Option::is_none")]
1076    pub planned_change: Option<u32>,
1077}
1078
1079/// The position a filament change charged up to, and how fresh it is.
1080#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1081#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1082#[schemars(crate = "printobserver_types::schemars")]
1083pub struct SignalPosition {
1084    /// The position.
1085    pub position: FilePosition,
1086    /// Whether it was read when the signal was handled, or is the last one
1087    /// recorded before it.
1088    pub freshness: PositionFreshness,
1089}
1090
1091/// How fresh the position a filament change charged up to is.
1092#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1093#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
1094#[schemars(crate = "printobserver_types::schemars")]
1095pub enum PositionFreshness {
1096    /// Read from the job as the signal was handled: where the spool stopped.
1097    ReadAtSignal,
1098    /// The last position recorded before the signal, the job reporting none
1099    /// as it was handled: the spool may have fed past it.
1100    LastRecorded,
1101}
1102
1103impl EventPayload for FilamentChangeSignalledPayload {
1104    const KIND: &'static str = "filament_change_signalled";
1105}
1106
1107impl Sample for FilamentChangeSignalledPayload {
1108    fn sample_full() -> Self {
1109        Self {
1110            tool: Some(0),
1111            spool_id: Some(sample_spool_id()),
1112            source_kind: EventKind::new("obico_printer_notification").expect("a kind name"),
1113            position: Some(SignalPosition {
1114                position: FilePosition::sample_full(),
1115                freshness: PositionFreshness::ReadAtSignal,
1116            }),
1117            planned_change: Some(0),
1118        }
1119    }
1120
1121    fn sample_minimal() -> Self {
1122        Self {
1123            tool: None,
1124            spool_id: None,
1125            position: None,
1126            planned_change: None,
1127            ..Self::sample_full()
1128        }
1129    }
1130}
1131
1132/// What told the supervisor a print had reached one of its planned changes.
1133#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1134#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
1135#[schemars(crate = "printobserver_types::schemars")]
1136pub enum PlannedChangeTrigger {
1137    /// A filament-change signal arrived with the job at the change.
1138    Signal,
1139    /// The job's file position stood at the change or just past it.
1140    Position,
1141}
1142
1143/// A print reached one of the changes its G-code plans, and the printer is
1144/// waiting there for a person: recorded once per planned change of a print.
1145///
1146/// From this event to the change's `filament_change_planned_resumed`, no
1147/// supervision turn runs for the print, and a pause, a resume or an adjustment
1148/// is refused `planned_change_waiting` to every actor.
1149#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1150#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1151#[schemars(
1152    crate = "printobserver_types::schemars",
1153    transform = crate::gcode_index::null_is_sent
1154)]
1155pub struct FilamentChangePlannedReachedPayload {
1156    /// The change reached.
1157    pub change: PlannedChange,
1158    /// The colour of the stretch before it, as `#RRGGBB`; null when the file
1159    /// names none.
1160    pub previous_color: Option<String>,
1161    /// What told the supervisor it was reached.
1162    pub trigger: PlannedChangeTrigger,
1163    /// Where the job stood when it was.
1164    pub position: FilePosition,
1165    /// The spool charged up to the change: the one on tool 0; null when none
1166    /// was loaded.
1167    pub spool_id: Option<SpoolId>,
1168    /// The spool the print's manifest names for the stretch after the change;
1169    /// null when it names none.
1170    pub next_spool_id: Option<SpoolId>,
1171    /// The filament the stretch after the change feeds, in millimetres.
1172    pub next_segment_filament_mm: f64,
1173}
1174
1175impl EventPayload for FilamentChangePlannedReachedPayload {
1176    const KIND: &'static str = "filament_change_planned_reached";
1177}
1178
1179impl Sample for FilamentChangePlannedReachedPayload {
1180    fn sample_full() -> Self {
1181        Self {
1182            change: PlannedChange::sample_full(),
1183            previous_color: Some("#FFFFFF".to_owned()),
1184            trigger: PlannedChangeTrigger::Position,
1185            position: FilePosition::sample_full(),
1186            spool_id: Some(sample_spool_id()),
1187            next_spool_id: Some(sample_spool_id()),
1188            next_segment_filament_mm: 812.4,
1189        }
1190    }
1191
1192    fn sample_alternates() -> Vec<Self> {
1193        vec![Self {
1194            previous_color: None,
1195            trigger: PlannedChangeTrigger::Signal,
1196            spool_id: None,
1197            next_spool_id: None,
1198            ..Self::sample_full()
1199        }]
1200    }
1201}
1202
1203/// A print carried on from a planned change it was waiting at: its file
1204/// position moved past the change. Recorded once per change reached, and the
1205/// check it prompts runs at once.
1206#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1207#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1208#[schemars(
1209    crate = "printobserver_types::schemars",
1210    transform = crate::gcode_index::null_is_sent
1211)]
1212pub struct FilamentChangePlannedResumedPayload {
1213    /// The change the print carried on from.
1214    pub change: PlannedChange,
1215    /// The colour of the stretch before it, as `#RRGGBB`; null when the file
1216    /// names none.
1217    pub previous_color: Option<String>,
1218    /// How long the print waited at it, in whole seconds.
1219    pub waited_s: i64,
1220    /// Where the job stood when it was found to have carried on.
1221    pub position: FilePosition,
1222}
1223
1224impl EventPayload for FilamentChangePlannedResumedPayload {
1225    const KIND: &'static str = "filament_change_planned_resumed";
1226}
1227
1228impl Sample for FilamentChangePlannedResumedPayload {
1229    fn sample_full() -> Self {
1230        Self {
1231            change: PlannedChange::sample_full(),
1232            previous_color: Some("#FFFFFF".to_owned()),
1233            waited_s: 412,
1234            position: FilePosition::sample_full(),
1235        }
1236    }
1237
1238    fn sample_alternates() -> Vec<Self> {
1239        vec![Self {
1240            previous_color: None,
1241            ..Self::sample_full()
1242        }]
1243    }
1244}
1245
1246/// A print this system never saw was found in the printer's own tally.
1247#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1248#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1249#[schemars(crate = "printobserver_types::schemars")]
1250pub struct UnaccountedPrintPayload {
1251    /// The file that was printed.
1252    pub file_name: String,
1253    /// When it was printed, when the printer says.
1254    #[serde(default, skip_serializing_if = "Option::is_none")]
1255    pub printed_at: Option<Timestamp>,
1256    /// Whether it completed.
1257    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
1258    pub success: bool,
1259    /// Whether it was charged against a spool.
1260    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
1261    pub charged: bool,
1262}
1263
1264impl EventPayload for UnaccountedPrintPayload {
1265    const KIND: &'static str = "unaccounted_print";
1266}
1267
1268impl Sample for UnaccountedPrintPayload {
1269    fn sample_full() -> Self {
1270        Self {
1271            file_name: "benchy.gcode".to_owned(),
1272            printed_at: Some(Timestamp::sample_full()),
1273            success: true,
1274            charged: true,
1275        }
1276    }
1277
1278    fn sample_minimal() -> Self {
1279        Self {
1280            printed_at: None,
1281            success: false,
1282            charged: false,
1283            ..Self::sample_full()
1284        }
1285    }
1286}
1287
1288/// The filament check before a start was made.
1289#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1290#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1291#[schemars(crate = "printobserver_types::schemars")]
1292pub struct PreflightCheckedPayload {
1293    /// What the check found.
1294    pub preflight: Preflight,
1295    /// The start it was made for, when it was made for one.
1296    #[serde(default, skip_serializing_if = "Option::is_none")]
1297    pub action_id: Option<ActionId>,
1298}
1299
1300impl EventPayload for PreflightCheckedPayload {
1301    const KIND: &'static str = "preflight_checked";
1302}
1303
1304impl Sample for PreflightCheckedPayload {
1305    fn sample_full() -> Self {
1306        Self {
1307            preflight: Preflight::sample_full(),
1308            action_id: Some(ActionId::sample_full()),
1309        }
1310    }
1311
1312    fn sample_minimal() -> Self {
1313        Self {
1314            action_id: None,
1315            ..Self::sample_full()
1316        }
1317    }
1318}
1319
1320/// Filament a tool fed after an unconfirmed filament change was held for the
1321/// next spool loaded onto that tool, or confirmed on it.
1322#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1323#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1324#[schemars(crate = "printobserver_types::schemars")]
1325pub struct ChargePendedPayload {
1326    /// What was held.
1327    pub pending: PendingCharge,
1328}
1329
1330impl EventPayload for ChargePendedPayload {
1331    const KIND: &'static str = "charge_pended";
1332}
1333
1334impl Sample for ChargePendedPayload {
1335    fn sample_full() -> Self {
1336        Self {
1337            pending: PendingCharge::sample_full(),
1338        }
1339    }
1340
1341    fn sample_minimal() -> Self {
1342        Self {
1343            pending: PendingCharge::sample_minimal(),
1344        }
1345    }
1346}
1347
1348/// A print that was already open when spool tracking was installed: it is
1349/// never charged, and this says why it carries no charge.
1350#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1351#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1352#[schemars(crate = "printobserver_types::schemars")]
1353pub struct PrintUntrackedPayload {
1354    /// Why the print carries no charge.
1355    pub reason: String,
1356}
1357
1358impl EventPayload for PrintUntrackedPayload {
1359    const KIND: &'static str = "print_untracked";
1360}
1361
1362impl Sample for PrintUntrackedPayload {
1363    fn sample_full() -> Self {
1364        Self {
1365            reason: "the print was already running when spool tracking was installed".to_owned(),
1366        }
1367    }
1368}
1369
1370/// What became of the prints a file's new tally generation counts.
1371#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1372#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
1373#[schemars(crate = "printobserver_types::schemars")]
1374pub enum RebaselineDisposition {
1375    /// They were accounted as prints this system never saw.
1376    Accounted,
1377    /// It could not be told which of them this system already settled, so the
1378    /// loaded spool was marked unverified rather than charged on a guess.
1379    Unverified,
1380}
1381
1382impl Sample for RebaselineDisposition {
1383    fn sample_full() -> Self {
1384        Self::Unverified
1385    }
1386}
1387
1388/// The printer's tally for a file went down — the file was deleted and
1389/// uploaded again — so the file's tally generation advanced, and the new count
1390/// is that generation's growth from zero.
1391///
1392/// The rebaseline itself marks no spool; only an `unverified` disposition does.
1393#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1394#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1395#[schemars(crate = "printobserver_types::schemars")]
1396pub struct FileTallyRebaselinedPayload {
1397    /// The file whose tally went down.
1398    pub file_name: String,
1399    /// Where it lives, in the printer's own vocabulary.
1400    pub origin: String,
1401    /// The generation the tally was in.
1402    pub old_generation: u32,
1403    /// The generation it is in now.
1404    pub new_generation: u32,
1405    /// The completed prints the old tally counted.
1406    pub old_successes: i64,
1407    /// The failed prints the old tally counted.
1408    pub old_failures: i64,
1409    /// The completed prints the new tally counts.
1410    pub new_successes: i64,
1411    /// The failed prints the new tally counts.
1412    pub new_failures: i64,
1413    /// What became of the prints the new generation counts.
1414    pub disposition: RebaselineDisposition,
1415}
1416
1417impl EventPayload for FileTallyRebaselinedPayload {
1418    const KIND: &'static str = "file_tally_rebaselined";
1419}
1420
1421impl Sample for FileTallyRebaselinedPayload {
1422    fn sample_full() -> Self {
1423        Self {
1424            file_name: "benchy.gcode".to_owned(),
1425            origin: "local".to_owned(),
1426            old_generation: 0,
1427            new_generation: 1,
1428            old_successes: 5,
1429            old_failures: 1,
1430            new_successes: 1,
1431            new_failures: 0,
1432            disposition: RebaselineDisposition::Unverified,
1433        }
1434    }
1435
1436    fn sample_alternates() -> Vec<Self> {
1437        vec![Self {
1438            disposition: RebaselineDisposition::Accounted,
1439            ..Self::sample_full()
1440        }]
1441    }
1442}
1443
1444/// The printer's connection changed into or out of `offline` or `error`: a
1445/// serial disconnect, a reconnect, a printer error.
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 PrinterConnectionChangedPayload {
1452    /// The state the previous read found.
1453    pub from: PrinterState,
1454    /// The state this read found.
1455    pub to: PrinterState,
1456    /// What the watch read, in words.
1457    pub detail: String,
1458}
1459
1460impl EventPayload for PrinterConnectionChangedPayload {
1461    const KIND: &'static str = "printer_connection_changed";
1462}
1463
1464impl Sample for PrinterConnectionChangedPayload {
1465    fn sample_full() -> Self {
1466        Self {
1467            from: PrinterState::Printing,
1468            to: PrinterState::Offline,
1469            detail: "the printer reports Offline after error: SerialTimeoutException: ".to_owned(),
1470        }
1471    }
1472
1473    fn sample_alternates() -> Vec<Self> {
1474        vec![Self {
1475            from: PrinterState::Offline,
1476            to: PrinterState::Operational,
1477            detail: "the printer reports Operational".to_owned(),
1478        }]
1479    }
1480}
1481
1482/// The printer reset: its firmware restarted, and whatever it held is gone.
1483///
1484/// Recorded on each reset the printer pushed, one while idle included, which
1485/// changes nothing a read of its state reports. The printer's rather than any
1486/// print's, so it is written with no print; `during_print` names the print it
1487/// happened during, when one was running.
1488#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1489#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1490#[schemars(crate = "printobserver_types::schemars")]
1491pub struct PrinterResetPayload {
1492    /// The print that was running when it reset, `null` when none was.
1493    #[serde(default)]
1494    pub during_print: Option<PrintId>,
1495    /// What the watch knew of it, in words.
1496    pub detail: String,
1497}
1498
1499impl EventPayload for PrinterResetPayload {
1500    const KIND: &'static str = "printer_reset";
1501}
1502
1503impl Sample for PrinterResetPayload {
1504    fn sample_full() -> Self {
1505        Self {
1506            during_print: Some(PrintId::sample_full()),
1507            detail: "the printer pushed a reset".to_owned(),
1508        }
1509    }
1510
1511    fn sample_minimal() -> Self {
1512        Self {
1513            during_print: None,
1514            detail: "the printer pushed a reset".to_owned(),
1515        }
1516    }
1517}
1518
1519/// One tool heater whose target was above zero.
1520#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1521#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1522#[schemars(crate = "printobserver_types::schemars")]
1523pub struct HeatedTool {
1524    /// The tool's number.
1525    pub tool: i64,
1526    /// Its target, in degrees Celsius.
1527    pub target_c: f64,
1528}
1529
1530impl Sample for HeatedTool {
1531    fn sample_full() -> Self {
1532        Self {
1533            tool: 0,
1534            target_c: 215.0,
1535        }
1536    }
1537}
1538
1539/// The printer heated or moved with no job running, soon after a print ended
1540/// `interrupted` or `failed`.
1541///
1542/// A transition rather than a reading: written once when such activity begins,
1543/// and again only when what it reports changes. The printer's rather than any
1544/// print's, so it is written with no print; `last_print_id` names the print it
1545/// came after.
1546#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1547#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1548#[schemars(crate = "printobserver_types::schemars")]
1549pub struct UnattendedPrinterActivityPayload {
1550    /// The print that ended before it.
1551    pub last_print_id: PrintId,
1552    /// Every tool whose target is above zero.
1553    pub tools: Vec<HeatedTool>,
1554    /// The bed's target, when it is above zero; `null` otherwise.
1555    #[serde(default)]
1556    pub bed_target_c: Option<f64>,
1557    /// Whether the print head moved since the last position read, `null` when
1558    /// no position could be read.
1559    #[serde(default)]
1560    pub moved: Option<bool>,
1561    /// What the watch read, in words.
1562    pub detail: String,
1563}
1564
1565impl EventPayload for UnattendedPrinterActivityPayload {
1566    const KIND: &'static str = "unattended_printer_activity";
1567}
1568
1569impl Sample for UnattendedPrinterActivityPayload {
1570    fn sample_full() -> Self {
1571        Self {
1572            last_print_id: PrintId::sample_full(),
1573            tools: vec![HeatedTool::sample_full()],
1574            bed_target_c: Some(60.0),
1575            moved: Some(true),
1576            detail: "tool 0 is heating to 215 °C with no job running".to_owned(),
1577        }
1578    }
1579
1580    fn sample_minimal() -> Self {
1581        Self {
1582            last_print_id: PrintId::sample_full(),
1583            tools: Vec::new(),
1584            bed_target_c: None,
1585            moved: None,
1586            detail: "the print head moved with no job running".to_owned(),
1587        }
1588    }
1589}
1590
1591/// What a check of the failure detector's own health found.
1592#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1593#[serde(
1594    crate = "printobserver_types::serde",
1595    rename_all = "snake_case",
1596    deny_unknown_fields
1597)]
1598#[schemars(crate = "printobserver_types::schemars")]
1599pub enum DetectorStatus {
1600    /// It answered its health check.
1601    Available,
1602    /// It did not: refused, reset, answered otherwise, or not in time.
1603    Unavailable,
1604}
1605
1606impl Sample for DetectorStatus {
1607    fn sample_full() -> Self {
1608        Self::Unavailable
1609    }
1610
1611    fn sample_alternates() -> Vec<Self> {
1612        vec![Self::Available]
1613    }
1614}
1615
1616/// The failure detector's own health changed.
1617///
1618/// The printer's rather than any print's, so it is written with no print.
1619#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1620#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1621#[schemars(crate = "printobserver_types::schemars")]
1622pub struct DetectorHealthChangedPayload {
1623    /// What the check found.
1624    pub status: DetectorStatus,
1625    /// What it was answered, in words.
1626    pub detail: String,
1627}
1628
1629impl EventPayload for DetectorHealthChangedPayload {
1630    const KIND: &'static str = "detector_health_changed";
1631}
1632
1633impl Sample for DetectorHealthChangedPayload {
1634    fn sample_full() -> Self {
1635        Self {
1636            status: DetectorStatus::Unavailable,
1637            detail: "the detector's health check answered 503".to_owned(),
1638        }
1639    }
1640
1641    fn sample_alternates() -> Vec<Self> {
1642        vec![Self {
1643            status: DetectorStatus::Available,
1644            detail: "the detector's health check answered 200".to_owned(),
1645        }]
1646    }
1647}
1648
1649/// A recovery action was asked for.
1650///
1651/// The printer's rather than any print's, so it is written with no print.
1652#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1653#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1654#[schemars(crate = "printobserver_types::schemars")]
1655pub struct RecoveryRequestedPayload {
1656    /// What was asked for.
1657    pub action: RecoveryAction,
1658    /// Who asked.
1659    pub actor: Actor,
1660    /// Why.
1661    pub reason: String,
1662    /// The operator's standing word that the bed is clear this request is
1663    /// decided on in place of an assertion of its own, when it is: the
1664    /// `bed_clear_asserted` event recording it. Absent otherwise.
1665    #[serde(default, skip_serializing_if = "Option::is_none")]
1666    pub bed_clear: Option<EventId>,
1667}
1668
1669impl EventPayload for RecoveryRequestedPayload {
1670    const KIND: &'static str = "recovery_requested";
1671}
1672
1673impl Sample for RecoveryRequestedPayload {
1674    fn sample_full() -> Self {
1675        Self {
1676            action: RecoveryAction::sample_full(),
1677            actor: Actor::Operator,
1678            reason: "free the nozzle from the part".to_owned(),
1679            bed_clear: Some(EventId::sample_full()),
1680        }
1681    }
1682
1683    fn sample_minimal() -> Self {
1684        Self {
1685            bed_clear: None,
1686            ..Self::sample_full()
1687        }
1688    }
1689}
1690
1691/// A recovery action reached the printer, and what the printer made of it.
1692#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1693#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1694#[schemars(crate = "printobserver_types::schemars")]
1695pub struct RecoveryExecutedPayload {
1696    /// What was asked for.
1697    pub action: RecoveryAction,
1698    /// Who asked.
1699    pub actor: Actor,
1700    /// Why.
1701    pub reason: String,
1702    /// What the printer made of it.
1703    pub outcome: crate::records::ExecutionOutcome,
1704    /// The operator's standing word that the bed is clear this action was
1705    /// carried out on in place of an assertion of its own, when it was: the
1706    /// `bed_clear_asserted` event recording it. Absent otherwise.
1707    #[serde(default, skip_serializing_if = "Option::is_none")]
1708    pub bed_clear: Option<EventId>,
1709}
1710
1711impl EventPayload for RecoveryExecutedPayload {
1712    const KIND: &'static str = "recovery_executed";
1713}
1714
1715impl Sample for RecoveryExecutedPayload {
1716    fn sample_full() -> Self {
1717        Self {
1718            action: RecoveryAction::RecoverLift { mm: 10.0 },
1719            actor: Actor::Operator,
1720            reason: "free the nozzle from the part".to_owned(),
1721            outcome: crate::records::ExecutionOutcome::Succeeded,
1722            bed_clear: Some(EventId::sample_full()),
1723        }
1724    }
1725
1726    fn sample_minimal() -> Self {
1727        Self {
1728            bed_clear: None,
1729            ..Self::sample_full()
1730        }
1731    }
1732
1733    fn sample_alternates() -> Vec<Self> {
1734        vec![Self {
1735            outcome: crate::records::ExecutionOutcome::Failed {
1736                reason: "the printer is unreachable: connection refused".to_owned(),
1737            },
1738            ..Self::sample_full()
1739        }]
1740    }
1741}
1742
1743/// A recovery action was refused, and reached nothing.
1744#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1745#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1746#[schemars(crate = "printobserver_types::schemars")]
1747pub struct RecoveryRejectedPayload {
1748    /// What was asked for.
1749    pub action: RecoveryAction,
1750    /// Who asked.
1751    pub actor: Actor,
1752    /// Why.
1753    pub reason: String,
1754    /// Why it was refused.
1755    pub rejection: RecoveryRejection,
1756}
1757
1758impl EventPayload for RecoveryRejectedPayload {
1759    const KIND: &'static str = "recovery_rejected";
1760}
1761
1762impl Sample for RecoveryRejectedPayload {
1763    fn sample_full() -> Self {
1764        Self {
1765            action: RecoveryAction::RecoverPark {
1766                clearance_asserted: false,
1767            },
1768            actor: Actor::Operator,
1769            reason: "move the head off the part".to_owned(),
1770            rejection: RecoveryRejection::sample_full(),
1771        }
1772    }
1773}
1774
1775/// The operator's word that the bed is clear: nothing is on it that homing Z
1776/// could crush or a move over the part could strike.
1777///
1778/// The printer's rather than any print's, so it is written with no print. It
1779/// stands until the next `print_started`, whichever way that print started,
1780/// and while it stands a recovery that needs the bed or the nozzle clear is
1781/// decided as though it carried the operator's assertion — read back out of
1782/// the event log, so a server started again holds it as the one before did.
1783/// Only the operator records one: an assertion is a person's word for what
1784/// they can see.
1785#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1786#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1787#[schemars(crate = "printobserver_types::schemars")]
1788pub struct BedClearAssertedPayload {
1789    /// Who said so: the operator, the one actor whose word this records.
1790    pub actor: BedClearActor,
1791    /// Why they say so.
1792    pub reason: String,
1793}
1794
1795/// Who may say the bed is clear: the operator, and no other actor.
1796///
1797/// Its own type rather than [`Actor`], so that a record of the agent's or the
1798/// system's word that the bed is clear is one no value can spell. On the wire
1799/// it is `"operator"`, as [`Actor::Operator`] is.
1800#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1801#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
1802#[schemars(crate = "printobserver_types::schemars")]
1803pub enum BedClearActor {
1804    /// A person: the operator.
1805    Operator,
1806}
1807
1808impl BedClearActor {
1809    /// The actor this is, in the vocabulary every other record names actors in.
1810    #[must_use]
1811    pub const fn actor(self) -> Actor {
1812        match self {
1813            Self::Operator => Actor::Operator,
1814        }
1815    }
1816}
1817
1818impl EventPayload for BedClearAssertedPayload {
1819    const KIND: &'static str = "bed_clear_asserted";
1820}
1821
1822impl Sample for BedClearAssertedPayload {
1823    fn sample_full() -> Self {
1824        Self {
1825            actor: BedClearActor::Operator,
1826            reason: "the cancelled print is off the bed and nothing else is on it".to_owned(),
1827        }
1828    }
1829}