1use std::path::PathBuf;
12
13use printobserver_core::store::ImageLookup;
14use printobserver_core::{
15 AcknowledgementDisposition, ActionKind, ActionRecord, Actor, ImageRecord, Intervention,
16 JobManifest, ManifestNarrowing, PendingCharge, PolicyDecision, Preflight, PrintOutcome,
17 PrintRecord, RecoveryAction, RecoveryActionKind, RecoveryDecision, SpoolCommand, SpoolId,
18 SpoolRecord, SpoolTrust,
19};
20use printobserver_core::{DetectorHealth, PrintContext};
21use printobserver_printer_api::{JobSnapshot, PrinterSnapshot};
22use printobserver_supervisor_api::SupervisionSession;
23use printobserver_types::schemars::JsonSchema;
24use printobserver_types::serde::{Deserialize, Serialize};
25use printobserver_types::serde_json::{Map, Value};
26use printobserver_types::{EventId, EventRecord, FileName, PrintId, Timestamp};
27
28#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct BodyRefusal {
31 pub detail: String,
33}
34
35impl core::fmt::Display for BodyRefusal {
36 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
37 formatter.write_str(&self.detail)
38 }
39}
40
41#[derive(Debug, Clone, PartialEq, Deserialize)]
50#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
51pub struct ActionBody {
52 #[serde(default)]
54 pub reason: Option<String>,
55 pub actor: Actor,
57 #[serde(default)]
59 pub duration_s: Option<i64>,
60 #[serde(default)]
62 pub factor: Option<f64>,
63 #[serde(default)]
65 pub target_c: Option<f64>,
66 #[serde(default)]
68 pub percent: Option<f64>,
69 #[serde(default)]
71 pub tool: Option<i64>,
72 #[serde(default)]
74 pub file_name: Option<FileName>,
75 #[serde(default)]
77 pub manifest: Option<JobManifest>,
78 #[serde(default)]
82 pub override_filament_check: bool,
83 #[serde(default)]
85 pub event_id: Option<EventId>,
86 #[serde(default)]
88 pub disposition: Option<AcknowledgementDisposition>,
89 #[serde(default)]
91 pub outcome: Option<PrintOutcome>,
92}
93
94fn missing<T>(named: &str) -> Result<T, BodyRefusal> {
96 Err(BodyRefusal {
97 detail: format!("this operation needs `{named}`, and the request carries none"),
98 })
99}
100
101fn needed<T>(value: Option<T>, named: &str) -> Result<T, BodyRefusal> {
103 value.map_or_else(|| missing(named), Ok)
104}
105
106pub fn reason_of(reason: Option<&str>) -> Result<String, BodyRefusal> {
118 match reason.map(str::trim) {
119 Some(reason) if !reason.is_empty() => Ok(reason.to_owned()),
120 _ => Err(BodyRefusal {
121 detail: "every mutating request carries a `reason`, and this one carries none"
122 .to_owned(),
123 }),
124 }
125}
126
127#[derive(Debug, Clone, PartialEq, Deserialize)]
133#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
134pub struct ManifestBody {
135 #[serde(default)]
137 pub reason: Option<String>,
138 pub manifest: JobManifest,
140}
141
142impl ManifestBody {
143 pub fn reason(&self) -> Result<String, BodyRefusal> {
152 reason_of(self.reason.as_deref())
153 }
154}
155
156impl ActionBody {
157 pub fn reason(&self) -> Result<String, BodyRefusal> {
166 reason_of(self.reason.as_deref())
167 }
168
169 pub fn into_action(
177 self,
178 kind: ActionKind,
179 ) -> Result<printobserver_core::PrintAction, BodyRefusal> {
180 use printobserver_core::PrintAction as Action;
181
182 let reason = self.reason()?;
183 let actor = self.actor.clone();
184 let duration_s = self.duration_s;
185 Ok(match kind {
186 ActionKind::Pause => Action::Pause { reason, actor },
187 ActionKind::Resume => Action::Resume { reason, actor },
188 ActionKind::Cancel => Action::Cancel { reason, actor },
189 ActionKind::StartPrint => Action::StartPrint {
190 file_name: needed(self.file_name, "file_name")?,
191 manifest: needed(self.manifest, "manifest")?,
192 override_filament_check: self.override_filament_check,
193 reason,
194 actor,
195 },
196 ActionKind::SetFeedrateFactor => Action::SetFeedrateFactor {
197 factor: needed(self.factor, "factor")?,
198 duration_s,
199 reason,
200 actor,
201 },
202 ActionKind::SetFlowrateFactor => Action::SetFlowrateFactor {
203 factor: needed(self.factor, "factor")?,
204 duration_s,
205 reason,
206 actor,
207 },
208 ActionKind::SetToolTargetC => Action::SetToolTargetC {
209 tool: needed(self.tool, "tool")?,
210 target_c: needed(self.target_c, "target_c")?,
211 duration_s,
212 reason,
213 actor,
214 },
215 ActionKind::SetBedTargetC => Action::SetBedTargetC {
216 target_c: needed(self.target_c, "target_c")?,
217 duration_s,
218 reason,
219 actor,
220 },
221 ActionKind::SetFanPercent => Action::SetFanPercent {
222 percent: needed(self.percent, "percent")?,
223 duration_s,
224 reason,
225 actor,
226 },
227 ActionKind::AcknowledgeFailure => Action::AcknowledgeFailure {
228 event_id: needed(self.event_id, "event_id")?,
229 disposition: needed(self.disposition, "disposition")?,
230 reason,
231 actor,
232 },
233 ActionKind::ClosePrint => Action::ClosePrint {
234 outcome: needed(self.outcome, "outcome")?,
235 reason,
236 actor,
237 },
238 ActionKind::RegisterSpool
239 | ActionKind::LoadSpool
240 | ActionKind::UnloadSpool
241 | ActionKind::AdjustSpool
242 | ActionKind::RetireSpool => {
243 return Err(BodyRefusal {
244 detail: format!(
245 "{kind:?} is a spool command, and no print-action operation carries one"
246 ),
247 });
248 }
249 })
250 }
251}
252
253#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
255#[serde(crate = "printobserver_types::serde")]
256#[schemars(crate = "printobserver_types::schemars")]
257pub struct ActionAnswer {
258 pub record: ActionRecord,
262 #[serde(skip_serializing_if = "Option::is_none")]
264 pub intervention: Option<Intervention>,
265 #[serde(skip_serializing_if = "Option::is_none")]
267 pub printer_refusal: Option<String>,
268}
269
270pub fn spool_command_of(
284 kind: ActionKind,
285 spool_id: Option<SpoolId>,
286 body: Value,
287) -> Result<SpoolCommand, BodyRefusal> {
288 let Value::Object(mut fields) = body else {
289 return Err(BodyRefusal {
290 detail: "a spool command's body is a document of its fields".to_owned(),
291 });
292 };
293 let reason = reason_of(fields.get("reason").and_then(Value::as_str))?;
294 fields.insert("reason".to_owned(), Value::String(reason));
295 let tag = crate::operations::COMMAND_TAG;
296 for routed in [tag, "spool_id"] {
297 if fields.contains_key(routed) {
298 return Err(BodyRefusal {
299 detail: format!(
300 "a spool command's body does not carry `{routed}`: the operation it is \
301 sent to names it"
302 ),
303 });
304 }
305 }
306 let named = printobserver_types::serde_json::to_value(kind).map_err(|error| BodyRefusal {
307 detail: error.to_string(),
308 })?;
309 fields.insert(tag.to_owned(), named);
310 if let Some(spool_id) = spool_id {
311 fields.insert("spool_id".to_owned(), Value::String(spool_id.to_string()));
312 }
313 let command: SpoolCommand = printobserver_types::serde_json::from_value(Value::Object(fields))
314 .map_err(|error| BodyRefusal {
315 detail: format!("this is not a `{}` body: {error}", spool_command_name(kind)),
316 })?;
317 if command.kind() == kind {
318 Ok(command)
319 } else {
320 Err(BodyRefusal {
321 detail: format!("this body is not a `{}`", spool_command_name(kind)),
322 })
323 }
324}
325
326fn spool_command_name(kind: ActionKind) -> String {
328 printobserver_types::serde_json::to_value(kind)
329 .ok()
330 .and_then(|value| value.as_str().map(str::to_owned))
331 .unwrap_or_else(|| format!("{kind:?}"))
332}
333
334pub fn claimed_actor(body: &Map<String, Value>) -> Result<Actor, BodyRefusal> {
341 let Some(actor) = body.get("actor") else {
342 return missing("actor");
343 };
344 printobserver_types::serde_json::from_value(actor.clone()).map_err(|error| BodyRefusal {
345 detail: format!("`actor` is not an actor this system has: {error}"),
346 })
347}
348
349pub fn recovery_of(
362 kind: RecoveryActionKind,
363 body: Value,
364) -> Result<(RecoveryAction, Actor, String), BodyRefusal> {
365 let Value::Object(mut fields) = body else {
366 return Err(BodyRefusal {
367 detail: "a recovery action's body is a document of its fields".to_owned(),
368 });
369 };
370 let reason = reason_of(fields.get("reason").and_then(Value::as_str))?;
371 let actor = claimed_actor(&fields)?;
372 fields.remove("reason");
373 fields.remove("actor");
374 if fields.contains_key("action") {
375 return Err(BodyRefusal {
376 detail: "a recovery action's body does not carry `action`: the operation it is \
377 sent to names it"
378 .to_owned(),
379 });
380 }
381 fields.insert("action".to_owned(), Value::String(kind.as_str().to_owned()));
382 let action: RecoveryAction = printobserver_types::serde_json::from_value(Value::Object(fields))
383 .map_err(|error| BodyRefusal {
384 detail: format!("this is not a `{kind}` body: {error}"),
385 })?;
386 if action.kind() == kind {
387 Ok((action, actor, reason))
388 } else {
389 Err(BodyRefusal {
390 detail: format!("this body is not a `{kind}`"),
391 })
392 }
393}
394
395#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
401#[serde(crate = "printobserver_types::serde")]
402#[schemars(crate = "printobserver_types::schemars")]
403pub struct RecoveryAnswer {
404 pub action: RecoveryAction,
406 pub decision: RecoveryDecision,
408 pub detail: String,
411 pub events: Vec<EventRecord>,
414}
415
416pub type RecoveryStatusAnswer = printobserver_core::RecoveryStatus;
419
420#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
426#[serde(crate = "printobserver_types::serde")]
427#[schemars(crate = "printobserver_types::schemars")]
428pub struct SpoolCommandAnswer {
429 pub decision: PolicyDecision,
431 #[serde(skip_serializing_if = "Option::is_none")]
433 pub spool: Option<SpoolRecord>,
434 pub events: Vec<EventRecord>,
436}
437
438#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
446#[serde(crate = "printobserver_types::serde")]
447#[schemars(crate = "printobserver_types::schemars")]
448pub struct SpoolsAnswer {
449 pub at_a_glance: Vec<String>,
451 pub spools: Vec<SpoolRecord>,
454 pub pending: Vec<PendingCharge>,
457}
458
459impl SpoolsAnswer {
460 #[must_use]
462 pub fn of(spools: Vec<SpoolRecord>, pending: Vec<PendingCharge>) -> Self {
463 Self {
464 at_a_glance: spools.iter().map(at_a_glance).collect(),
465 spools,
466 pending,
467 }
468 }
469}
470
471#[must_use]
479pub fn at_a_glance(spool: &SpoolRecord) -> String {
480 let place = spool
481 .loaded_tool()
482 .map_or_else(|| "not loaded".to_owned(), |tool| format!("on tool {tool}"));
483 let trust = match &spool.trust {
484 SpoolTrust::Verified => "verified".to_owned(),
485 SpoolTrust::Unverified { marks } => {
486 let oldest = marks.first().map_or_else(String::new, |mark| {
487 printobserver_types::serde_json::to_value(mark.reason.kind())
488 .ok()
489 .and_then(|named| named.as_str().map(str::to_owned))
490 .unwrap_or_default()
491 });
492 let more = marks.len().saturating_sub(1);
493 if more == 0 {
494 format!("unverified: {oldest}")
495 } else {
496 format!("unverified: {oldest} (+{more} more)")
497 }
498 }
499 };
500 let retired = if spool.is_retired() { " | retired" } else { "" };
501 format!(
502 "{} | {} | {:.1} g of {:.1} g left | {place} | {trust}{retired}",
503 spool.name, spool.material, spool.remaining_g, spool.initial_g
504 )
505}
506
507#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
510#[serde(crate = "printobserver_types::serde")]
511#[schemars(crate = "printobserver_types::schemars")]
512pub struct SpoolAnswer {
513 pub spool: SpoolRecord,
515 pub recent: Vec<EventRecord>,
517}
518
519#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
521#[serde(crate = "printobserver_types::serde")]
522#[schemars(crate = "printobserver_types::schemars")]
523pub struct TimelineAnswer {
524 pub events: Vec<EventRecord>,
526 #[serde(skip_serializing_if = "Option::is_none")]
529 pub next: Option<EventId>,
530}
531
532#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
534#[serde(crate = "printobserver_types::serde")]
535#[schemars(crate = "printobserver_types::schemars")]
536pub struct PreflightAnswer {
537 pub preflight: Preflight,
539}
540
541#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
543#[serde(crate = "printobserver_types::serde")]
544#[schemars(crate = "printobserver_types::schemars")]
545pub struct StatusAnswer {
546 pub print: PrintRecord,
548 #[serde(skip_serializing_if = "Option::is_none")]
550 pub printer: Option<PrinterSnapshot>,
551 #[serde(skip_serializing_if = "Option::is_none")]
553 pub job: Option<JobSnapshot>,
554 #[serde(skip_serializing_if = "Option::is_none")]
556 pub session: Option<SupervisionSession>,
557 pub interventions: Vec<Intervention>,
559 pub detector: DetectorHealth,
561}
562
563#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
572#[serde(crate = "printobserver_types::serde")]
573#[schemars(crate = "printobserver_types::schemars")]
574pub struct ContextAnswer {
575 pub context: PrintContext,
577 #[serde(skip_serializing_if = "Option::is_none")]
579 pub image_path: Option<PathBuf>,
580}
581
582pub type LookAnswer = printobserver_core::Look;
587
588#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
595#[serde(crate = "printobserver_types::serde")]
596#[schemars(crate = "printobserver_types::schemars")]
597pub struct ImageAnswer {
598 pub record: ImageRecord,
600 #[serde(skip_serializing_if = "Option::is_none")]
602 pub path: Option<PathBuf>,
603}
604
605impl From<ImageLookup> for ImageAnswer {
606 fn from(lookup: ImageLookup) -> Self {
607 match lookup {
608 ImageLookup::Found { record, path } => Self {
609 record,
610 path: Some(path),
611 },
612 ImageLookup::FileMissing { record } => Self { record, path: None },
613 }
614 }
615}
616
617#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
624#[serde(crate = "printobserver_types::serde")]
625#[schemars(crate = "printobserver_types::schemars")]
626pub struct PrintsAnswer {
627 pub prints: Vec<PrintRecord>,
629 #[serde(skip_serializing_if = "Option::is_none")]
633 pub active: Option<PrintId>,
634}
635
636#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
638#[serde(crate = "printobserver_types::serde")]
639#[schemars(crate = "printobserver_types::schemars")]
640pub struct HistoryAnswer {
641 pub events: Vec<EventRecord>,
643}
644
645#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
648#[serde(crate = "printobserver_types::serde")]
649#[schemars(crate = "printobserver_types::schemars")]
650#[schemars(transform = cursor_is_always_sent)]
651pub struct EventsAnswer {
652 pub events: Vec<EventRecord>,
655 pub cursor: Option<EventId>,
659 #[serde(default, skip_serializing_if = "Option::is_none")]
664 #[schemars(extend("x-null-is-sent" = true))]
665 pub print_ended: Option<Option<PrintEnded>>,
666}
667
668fn cursor_is_always_sent(schema: &mut printobserver_types::schemars::Schema) {
673 if let Some(Value::Array(required)) = schema.get_mut("required") {
674 required.push(Value::from("cursor"));
675 }
676}
677
678#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
680#[serde(crate = "printobserver_types::serde")]
681#[schemars(crate = "printobserver_types::schemars")]
682pub struct PrintEnded {
683 pub event_id: EventId,
685 pub received_at: Timestamp,
687 pub outcome: PrintOutcome,
689}
690
691#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
693#[serde(crate = "printobserver_types::serde")]
694#[schemars(crate = "printobserver_types::schemars")]
695pub struct ManifestAnswer {
696 #[serde(skip_serializing_if = "Option::is_none")]
698 pub manifest: Option<JobManifest>,
699 pub narrowings: Vec<ManifestNarrowing>,
703}
704
705#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
707#[serde(crate = "printobserver_types::serde")]
708#[schemars(crate = "printobserver_types::schemars")]
709pub struct ErrorAnswer {
710 pub error: String,
712}
713
714impl ErrorAnswer {
715 pub fn saying(detail: impl core::fmt::Display) -> Self {
717 Self {
718 error: detail.to_string(),
719 }
720 }
721}
722
723#[derive(Debug, Clone, Copy, PartialEq, Eq)]
729pub struct IngressAnswer;
730
731impl Serialize for IngressAnswer {
732 fn serialize<S: printobserver_types::serde::Serializer>(
733 &self,
734 serializer: S,
735 ) -> Result<S::Ok, S::Error> {
736 use printobserver_types::serde::ser::SerializeStruct as _;
737 let mut state = serializer.serialize_struct("IngressAnswer", 1)?;
738 state.serialize_field("accepted", &true)?;
739 state.end()
740 }
741}
742
743#[cfg(test)]
744mod tests {
745 use printobserver_core::{ActionKind, Actor, ImageRecord};
746 use printobserver_types::contract::Sample as _;
747
748 use super::{ActionBody, ErrorAnswer, ImageAnswer, ImageLookup};
749
750 fn bare() -> ActionBody {
752 ActionBody {
753 reason: Some("a test is asking".to_owned()),
754 actor: Actor::Operator,
755 duration_s: None,
756 factor: None,
757 target_c: None,
758 percent: None,
759 tool: None,
760 file_name: None,
761 manifest: None,
762 override_filament_check: false,
763 event_id: None,
764 disposition: None,
765 outcome: None,
766 }
767 }
768
769 #[test]
775 fn every_action_that_needs_a_value_it_was_not_given_is_refused_naming_it() {
776 let needed = [
777 (ActionKind::StartPrint, "file_name"),
778 (ActionKind::SetFeedrateFactor, "factor"),
779 (ActionKind::SetFlowrateFactor, "factor"),
780 (ActionKind::SetToolTargetC, "tool"),
781 (ActionKind::SetBedTargetC, "target_c"),
782 (ActionKind::SetFanPercent, "percent"),
783 (ActionKind::AcknowledgeFailure, "event_id"),
784 (ActionKind::ClosePrint, "outcome"),
785 ];
786 for (kind, named) in needed {
787 let refusal = bare()
788 .into_action(kind)
789 .expect_err("this action needs a value the body does not carry");
790 assert!(
791 refusal.to_string().contains(named),
792 "{kind:?} was refused without naming `{named}`: {refusal}"
793 );
794 }
795 }
796
797 #[test]
800 fn a_spool_command_kind_is_refused_as_a_print_action() {
801 for kind in [
802 ActionKind::RegisterSpool,
803 ActionKind::LoadSpool,
804 ActionKind::UnloadSpool,
805 ActionKind::AdjustSpool,
806 ActionKind::RetireSpool,
807 ] {
808 let refusal = bare()
809 .into_action(kind)
810 .expect_err("a spool command is not a print action");
811 assert!(
812 refusal.to_string().contains("spool command"),
813 "{kind:?} was refused without saying why: {refusal}"
814 );
815 }
816 }
817
818 #[test]
820 fn the_second_value_a_two_valued_action_needs_is_named_in_its_turn() {
821 let mut starting = bare();
822 starting.file_name = Some(printobserver_types::FileName::new("a.gcode").expect("a name"));
823 assert!(
824 starting
825 .into_action(ActionKind::StartPrint)
826 .expect_err("a start needs a manifest")
827 .to_string()
828 .contains("manifest")
829 );
830
831 let mut tool = bare();
832 tool.tool = Some(0);
833 assert!(
834 tool.into_action(ActionKind::SetToolTargetC)
835 .expect_err("a tool target needs a temperature")
836 .to_string()
837 .contains("target_c")
838 );
839
840 let mut acknowledgement = bare();
841 acknowledgement.event_id = Some(printobserver_types::EventId::new());
842 assert!(
843 acknowledgement
844 .into_action(ActionKind::AcknowledgeFailure)
845 .expect_err("an acknowledgement needs a disposition")
846 .to_string()
847 .contains("disposition")
848 );
849 }
850
851 #[test]
853 fn a_reason_that_is_nothing_but_whitespace_is_no_reason() {
854 let mut blank = bare();
855 blank.reason = Some(" ".to_owned());
856 assert!(blank.reason().is_err());
857 let mut absent = bare();
858 absent.reason = None;
859 assert!(absent.reason().is_err());
860 assert_eq!(bare().reason().expect("a reason"), "a test is asking");
861 }
862
863 #[test]
868 fn an_image_whose_file_is_gone_answers_the_record_and_no_path() {
869 let record = ImageRecord::sample_full();
870 let missing = ImageAnswer::from(ImageLookup::FileMissing {
871 record: record.clone(),
872 });
873 assert_eq!(missing.record, record);
874 assert_eq!(missing.path, None);
875
876 let found = ImageAnswer::from(ImageLookup::Found {
877 record: record.clone(),
878 path: "/var/lib/printobserver/images/ab/cd".into(),
879 });
880 assert_eq!(
881 found.path.as_deref(),
882 Some(std::path::Path::new("/var/lib/printobserver/images/ab/cd"))
883 );
884 }
885
886 #[test]
888 fn a_refusal_answers_in_the_words_of_whatever_refused_it() {
889 assert_eq!(
890 ErrorAnswer::saying("the disk is full").error,
891 "the disk is full"
892 );
893 }
894}