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, ClearedMark,
21    FilePosition, InterventionId, InterventionOutcome, LoadedSpool, PendingCharge, PendingTaken,
22    PolicyDecision, Preflight, PrintAction, PrintOutcome, SpoolCommand, SpoolId, SpoolRecord,
23    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")]
497// llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
498pub struct FilamentConsumedPayload {
499    /// The durable identity of this debit.
500    pub charge_key: ChargeKey,
501    /// The tool that fed it.
502    pub tool: i64,
503    /// The spool charged; absent when nothing was tracked on the tool, and the
504    /// filament was recorded uncharged.
505    #[serde(default, skip_serializing_if = "Option::is_none")]
506    pub spool_id: Option<SpoolId>,
507    /// How the length was worked out.
508    pub method: ChargeMethod,
509    /// How much was fed, in millimetres.
510    pub length_mm: f64,
511    /// What that length weighs, in grams, when a spool gave its diameter and
512    /// density.
513    #[serde(default, skip_serializing_if = "Option::is_none")]
514    pub grams: Option<f64>,
515    /// The diameter the grams were worked out with, in millimetres.
516    #[serde(default, skip_serializing_if = "Option::is_none")]
517    pub diameter_mm: Option<f64>,
518    /// The density the grams were worked out with, in grams per cubic
519    /// centimetre.
520    #[serde(default, skip_serializing_if = "Option::is_none")]
521    pub density_g_cm3: Option<f64>,
522    /// The file's analysed length for the tool, in millimetres, when it had one.
523    #[serde(default, skip_serializing_if = "Option::is_none")]
524    pub analysed_length_mm: Option<f64>,
525    /// How far into the file the charge runs, when that was read.
526    #[serde(default, skip_serializing_if = "Option::is_none")]
527    pub position: Option<FilePosition>,
528    /// The spool's figure before the charge, in grams.
529    #[serde(default, skip_serializing_if = "Option::is_none")]
530    pub remaining_before_g: Option<f64>,
531    /// The spool's figure after it, in grams.
532    #[serde(default, skip_serializing_if = "Option::is_none")]
533    pub remaining_after_g: Option<f64>,
534    /// Anything a reader needs to make sense of the figure.
535    #[serde(default, skip_serializing_if = "Option::is_none")]
536    pub note: Option<String>,
537}
538
539impl EventPayload for FilamentConsumedPayload {
540    const KIND: &'static str = "filament_consumed";
541}
542
543impl Sample for FilamentConsumedPayload {
544    fn sample_full() -> Self {
545        Self {
546            charge_key: ChargeKey::sample_full(),
547            tool: 0,
548            spool_id: Some(sample_spool_id()),
549            method: ChargeMethod::GcodeExtrusion,
550            length_mm: 1_000.0,
551            grams: Some(2.98),
552            diameter_mm: Some(1.75),
553            density_g_cm3: Some(1.24),
554            analysed_length_mm: Some(5_120.0),
555            position: Some(FilePosition::sample_full()),
556            remaining_before_g: Some(745.48),
557            remaining_after_g: Some(742.5),
558            note: Some("charged up to the filament change".to_owned()),
559        }
560    }
561
562    fn sample_minimal() -> Self {
563        Self {
564            charge_key: ChargeKey::sample_full(),
565            tool: 0,
566            spool_id: None,
567            method: ChargeMethod::SlicerEstimate,
568            length_mm: 5_120.0,
569            grams: None,
570            diameter_mm: None,
571            density_g_cm3: None,
572            analysed_length_mm: None,
573            position: None,
574            remaining_before_g: None,
575            remaining_after_g: None,
576            note: None,
577        }
578    }
579}
580
581/// A spool was registered.
582#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
583#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
584#[schemars(crate = "printobserver_types::schemars")]
585pub struct SpoolRegisteredPayload {
586    /// The spool, as it was registered.
587    pub spool: SpoolRecord,
588    /// Who registered it.
589    pub actor: Actor,
590    /// Why.
591    pub reason: String,
592}
593
594impl EventPayload for SpoolRegisteredPayload {
595    const KIND: &'static str = "spool_registered";
596}
597
598impl Sample for SpoolRegisteredPayload {
599    fn sample_full() -> Self {
600        Self {
601            spool: SpoolRecord::sample_full(),
602            actor: Actor::Operator,
603            reason: sample_reason(),
604        }
605    }
606
607    fn sample_minimal() -> Self {
608        Self {
609            spool: SpoolRecord::sample_minimal(),
610            ..Self::sample_full()
611        }
612    }
613}
614
615/// A spool was loaded onto a tool, or confirmed as never having left it.
616#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
617#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
618#[schemars(crate = "printobserver_types::schemars")]
619pub struct SpoolLoadedPayload {
620    /// The spool loaded.
621    pub spool_id: SpoolId,
622    /// The tool, in the printer's own numbering.
623    pub tool: i64,
624    /// The spool the load swapped off the tool, when it was occupied.
625    #[serde(default, skip_serializing_if = "Option::is_none")]
626    pub replaced: Option<SpoolId>,
627    /// The pending charges the load took, each also its own
628    /// `filament_consumed` event under its key.
629    #[serde(default, skip_serializing_if = "Vec::is_empty")]
630    pub took_pending: Vec<PendingTaken>,
631    /// Every mark the load cleared, on either spool.
632    #[serde(default, skip_serializing_if = "Vec::is_empty")]
633    pub cleared_marks: Vec<ClearedMark>,
634    /// Who loaded it.
635    pub actor: Actor,
636    /// Why.
637    pub reason: String,
638}
639
640impl EventPayload for SpoolLoadedPayload {
641    const KIND: &'static str = "spool_loaded";
642}
643
644impl Sample for SpoolLoadedPayload {
645    fn sample_full() -> Self {
646        Self {
647            spool_id: sample_spool_id(),
648            tool: 0,
649            replaced: Some(ClearedMark::sample_full().spool_id),
650            took_pending: vec![PendingTaken::sample_full()],
651            cleared_marks: vec![ClearedMark::sample_full()],
652            actor: Actor::Operator,
653            reason: sample_reason(),
654        }
655    }
656
657    fn sample_minimal() -> Self {
658        Self {
659            replaced: None,
660            took_pending: Vec::new(),
661            cleared_marks: Vec::new(),
662            ..Self::sample_full()
663        }
664    }
665}
666
667/// A spool was unloaded from its tool.
668#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
669#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
670#[schemars(crate = "printobserver_types::schemars")]
671pub struct SpoolUnloadedPayload {
672    /// The spool unloaded.
673    pub spool_id: SpoolId,
674    /// The tool it left.
675    pub tool: i64,
676    /// Who unloaded it.
677    pub actor: Actor,
678    /// Why.
679    pub reason: String,
680}
681
682impl EventPayload for SpoolUnloadedPayload {
683    const KIND: &'static str = "spool_unloaded";
684}
685
686impl Sample for SpoolUnloadedPayload {
687    fn sample_full() -> Self {
688        Self {
689            spool_id: sample_spool_id(),
690            tool: 0,
691            actor: Actor::Operator,
692            reason: sample_reason(),
693        }
694    }
695}
696
697/// A spool's remaining figure was corrected.
698#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
699#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
700#[schemars(crate = "printobserver_types::schemars")]
701pub struct SpoolAdjustedPayload {
702    /// The spool corrected.
703    pub spool_id: SpoolId,
704    /// Its figure before, in grams, after any pending charge it took.
705    pub remaining_before_g: f64,
706    /// Its figure after, in grams.
707    pub remaining_after_g: f64,
708    /// The scale reading the figure was worked out from, when it was given as
709    /// one.
710    #[serde(default, skip_serializing_if = "Option::is_none")]
711    pub gross_g: Option<f64>,
712    /// The pending charges the correction took first, each also its own
713    /// `filament_consumed` event under its key.
714    #[serde(default, skip_serializing_if = "Vec::is_empty")]
715    pub took_pending: Vec<PendingTaken>,
716    /// Every mark the correction cleared.
717    #[serde(default, skip_serializing_if = "Vec::is_empty")]
718    pub cleared_marks: Vec<ClearedMark>,
719    /// Who corrected it.
720    pub actor: Actor,
721    /// Why.
722    pub reason: String,
723}
724
725impl EventPayload for SpoolAdjustedPayload {
726    const KIND: &'static str = "spool_adjusted";
727}
728
729impl Sample for SpoolAdjustedPayload {
730    fn sample_full() -> Self {
731        Self {
732            spool_id: sample_spool_id(),
733            remaining_before_g: 742.5,
734            remaining_after_g: 700.0,
735            gross_g: Some(950.0),
736            took_pending: vec![PendingTaken::sample_full()],
737            cleared_marks: vec![ClearedMark {
738                spool_id: sample_spool_id(),
739                reason: UnverifiedReason::sample_full(),
740            }],
741            actor: Actor::Operator,
742            reason: sample_reason(),
743        }
744    }
745
746    fn sample_minimal() -> Self {
747        Self {
748            gross_g: None,
749            took_pending: Vec::new(),
750            cleared_marks: Vec::new(),
751            ..Self::sample_full()
752        }
753    }
754}
755
756/// A spool was retired.
757#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
758#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
759#[schemars(crate = "printobserver_types::schemars")]
760pub struct SpoolRetiredPayload {
761    /// The spool retired.
762    pub spool_id: SpoolId,
763    /// Its figure as it was retired, in grams.
764    pub remaining_g: f64,
765    /// Who retired it.
766    pub actor: Actor,
767    /// Why.
768    pub reason: String,
769}
770
771impl EventPayload for SpoolRetiredPayload {
772    const KIND: &'static str = "spool_retired";
773}
774
775impl Sample for SpoolRetiredPayload {
776    fn sample_full() -> Self {
777        Self {
778            spool_id: sample_spool_id(),
779            remaining_g: 12.5,
780            actor: Actor::Operator,
781            reason: "the spool is empty".to_owned(),
782        }
783    }
784}
785
786/// A spool command was refused.
787#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
788#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
789#[schemars(crate = "printobserver_types::schemars")]
790pub struct SpoolCommandRejectedPayload {
791    /// The command, as it was asked for.
792    pub command: SpoolCommand,
793    /// The whole decision, carrying which refusal it was.
794    pub decision: PolicyDecision,
795}
796
797impl EventPayload for SpoolCommandRejectedPayload {
798    const KIND: &'static str = "spool_command_rejected";
799}
800
801impl Sample for SpoolCommandRejectedPayload {
802    fn sample_full() -> Self {
803        Self {
804            command: SpoolCommand::sample_full(),
805            decision: PolicyDecision::Rejected(crate::records::RejectionReason::SpoolRefused {
806                detail: "PEEK has no known density, so the spool needs one".to_owned(),
807            }),
808        }
809    }
810
811    fn sample_minimal() -> Self {
812        Self {
813            command: SpoolCommand::sample_minimal(),
814            ..Self::sample_full()
815        }
816    }
817}
818
819/// A spool was marked as one whose figure is in doubt.
820#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
821#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
822#[schemars(crate = "printobserver_types::schemars")]
823pub struct SpoolUnverifiedPayload {
824    /// The spool marked.
825    pub spool_id: SpoolId,
826    /// Why its figure is in doubt.
827    pub reason: UnverifiedReason,
828}
829
830impl EventPayload for SpoolUnverifiedPayload {
831    const KIND: &'static str = "spool_unverified";
832}
833
834impl Sample for SpoolUnverifiedPayload {
835    fn sample_full() -> Self {
836        Self {
837            spool_id: sample_spool_id(),
838            reason: UnverifiedReason::sample_full(),
839        }
840    }
841}
842
843/// A filament change was signalled during a print.
844#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
845#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
846#[schemars(crate = "printobserver_types::schemars")]
847pub struct FilamentChangeSignalledPayload {
848    /// The tool the change was signalled for, when it is known.
849    #[serde(default, skip_serializing_if = "Option::is_none")]
850    pub tool: Option<i64>,
851    /// The spool that was on it, when one was tracked.
852    #[serde(default, skip_serializing_if = "Option::is_none")]
853    pub spool_id: Option<SpoolId>,
854    /// The kind of the alert that carried the signal.
855    pub source_kind: EventKind,
856    /// The position the spool was charged up to, when one was known.
857    #[serde(default, skip_serializing_if = "Option::is_none")]
858    pub position: Option<FilePosition>,
859    /// Whether that position was read when the signal was handled, rather than
860    /// being the last one recorded; never with no position at all.
861    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
862    pub position_read_at_signal: bool,
863}
864
865impl EventPayload for FilamentChangeSignalledPayload {
866    const KIND: &'static str = "filament_change_signalled";
867}
868
869impl Sample for FilamentChangeSignalledPayload {
870    fn sample_full() -> Self {
871        Self {
872            tool: Some(0),
873            spool_id: Some(sample_spool_id()),
874            source_kind: EventKind::new("obico_printer_notification").expect("a kind name"),
875            position: Some(FilePosition::sample_full()),
876            position_read_at_signal: true,
877        }
878    }
879
880    fn sample_minimal() -> Self {
881        Self {
882            tool: None,
883            spool_id: None,
884            position: None,
885            position_read_at_signal: false,
886            ..Self::sample_full()
887        }
888    }
889}
890
891/// A print this system never saw was found in the printer's own tally.
892#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
893#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
894#[schemars(crate = "printobserver_types::schemars")]
895pub struct UnaccountedPrintPayload {
896    /// The file that was printed.
897    pub file_name: String,
898    /// When it was printed, when the printer says.
899    #[serde(default, skip_serializing_if = "Option::is_none")]
900    pub printed_at: Option<Timestamp>,
901    /// Whether it completed.
902    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
903    pub success: bool,
904    /// Whether it was charged against a spool.
905    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
906    pub charged: bool,
907}
908
909impl EventPayload for UnaccountedPrintPayload {
910    const KIND: &'static str = "unaccounted_print";
911}
912
913impl Sample for UnaccountedPrintPayload {
914    fn sample_full() -> Self {
915        Self {
916            file_name: "benchy.gcode".to_owned(),
917            printed_at: Some(Timestamp::sample_full()),
918            success: true,
919            charged: true,
920        }
921    }
922
923    fn sample_minimal() -> Self {
924        Self {
925            printed_at: None,
926            success: false,
927            charged: false,
928            ..Self::sample_full()
929        }
930    }
931}
932
933/// The filament check before a start was made.
934#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
935#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
936#[schemars(crate = "printobserver_types::schemars")]
937pub struct PreflightCheckedPayload {
938    /// What the check found.
939    pub preflight: Preflight,
940    /// The start it was made for, when it was made for one.
941    #[serde(default, skip_serializing_if = "Option::is_none")]
942    pub action_id: Option<ActionId>,
943}
944
945impl EventPayload for PreflightCheckedPayload {
946    const KIND: &'static str = "preflight_checked";
947}
948
949impl Sample for PreflightCheckedPayload {
950    fn sample_full() -> Self {
951        Self {
952            preflight: Preflight::sample_full(),
953            action_id: Some(ActionId::sample_full()),
954        }
955    }
956
957    fn sample_minimal() -> Self {
958        Self {
959            action_id: None,
960            ..Self::sample_full()
961        }
962    }
963}
964
965/// Filament a tool fed after an unconfirmed filament change was held for the
966/// next spool loaded onto that tool, or confirmed on it.
967#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
968#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
969#[schemars(crate = "printobserver_types::schemars")]
970pub struct ChargePendedPayload {
971    /// What was held.
972    pub pending: PendingCharge,
973}
974
975impl EventPayload for ChargePendedPayload {
976    const KIND: &'static str = "charge_pended";
977}
978
979impl Sample for ChargePendedPayload {
980    fn sample_full() -> Self {
981        Self {
982            pending: PendingCharge::sample_full(),
983        }
984    }
985
986    fn sample_minimal() -> Self {
987        Self {
988            pending: PendingCharge::sample_minimal(),
989        }
990    }
991}
992
993/// A print that was already open when spool tracking was installed: it is
994/// never charged, and this says why it carries no charge.
995#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
996#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
997#[schemars(crate = "printobserver_types::schemars")]
998pub struct PrintUntrackedPayload {
999    /// Why the print carries no charge.
1000    pub reason: String,
1001}
1002
1003impl EventPayload for PrintUntrackedPayload {
1004    const KIND: &'static str = "print_untracked";
1005}
1006
1007impl Sample for PrintUntrackedPayload {
1008    fn sample_full() -> Self {
1009        Self {
1010            reason: "the print was already running when spool tracking was installed".to_owned(),
1011        }
1012    }
1013}
1014
1015/// What became of the prints a file's new tally generation counts.
1016#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1017#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
1018#[schemars(crate = "printobserver_types::schemars")]
1019pub enum RebaselineDisposition {
1020    /// They were accounted as prints this system never saw.
1021    Accounted,
1022    /// It could not be told which of them this system already settled, so the
1023    /// loaded spool was marked unverified rather than charged on a guess.
1024    Unverified,
1025}
1026
1027impl Sample for RebaselineDisposition {
1028    fn sample_full() -> Self {
1029        Self::Unverified
1030    }
1031}
1032
1033/// The printer's tally for a file went down — the file was deleted and
1034/// uploaded again — so the file's tally generation advanced, and the new count
1035/// is that generation's growth from zero.
1036///
1037/// The rebaseline itself marks no spool; only an `unverified` disposition does.
1038#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1039#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1040#[schemars(crate = "printobserver_types::schemars")]
1041pub struct FileTallyRebaselinedPayload {
1042    /// The file whose tally went down.
1043    pub file_name: String,
1044    /// Where it lives, in the printer's own vocabulary.
1045    pub origin: String,
1046    /// The generation the tally was in.
1047    pub old_generation: u32,
1048    /// The generation it is in now.
1049    pub new_generation: u32,
1050    /// The completed prints the old tally counted.
1051    pub old_successes: i64,
1052    /// The failed prints the old tally counted.
1053    pub old_failures: i64,
1054    /// The completed prints the new tally counts.
1055    pub new_successes: i64,
1056    /// The failed prints the new tally counts.
1057    pub new_failures: i64,
1058    /// What became of the prints the new generation counts.
1059    pub disposition: RebaselineDisposition,
1060}
1061
1062impl EventPayload for FileTallyRebaselinedPayload {
1063    const KIND: &'static str = "file_tally_rebaselined";
1064}
1065
1066impl Sample for FileTallyRebaselinedPayload {
1067    fn sample_full() -> Self {
1068        Self {
1069            file_name: "benchy.gcode".to_owned(),
1070            origin: "local".to_owned(),
1071            old_generation: 0,
1072            new_generation: 1,
1073            old_successes: 5,
1074            old_failures: 1,
1075            new_successes: 1,
1076            new_failures: 0,
1077            disposition: RebaselineDisposition::Unverified,
1078        }
1079    }
1080
1081    fn sample_alternates() -> Vec<Self> {
1082        vec![Self {
1083            disposition: RebaselineDisposition::Accounted,
1084            ..Self::sample_full()
1085        }]
1086    }
1087}