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