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