Skip to main content

printobserver_core/
kinds.rs

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