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::{AgentContext, DetectorHealth};
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)]
87 pub override_material_check: bool,
88 #[serde(default)]
92 pub override_sheet_check: bool,
93 #[serde(default)]
95 pub event_id: Option<EventId>,
96 #[serde(default)]
98 pub disposition: Option<AcknowledgementDisposition>,
99 #[serde(default)]
101 pub outcome: Option<PrintOutcome>,
102}
103
104fn missing<T>(named: &str) -> Result<T, BodyRefusal> {
106 Err(BodyRefusal {
107 detail: format!("this operation needs `{named}`, and the request carries none"),
108 })
109}
110
111fn needed<T>(value: Option<T>, named: &str) -> Result<T, BodyRefusal> {
113 value.map_or_else(|| missing(named), Ok)
114}
115
116pub fn reason_of(reason: Option<&str>) -> Result<String, BodyRefusal> {
128 match reason.map(str::trim) {
129 Some(reason) if !reason.is_empty() => Ok(reason.to_owned()),
130 _ => Err(BodyRefusal {
131 detail: "every mutating request carries a `reason`, and this one carries none"
132 .to_owned(),
133 }),
134 }
135}
136
137#[derive(Debug, Clone, PartialEq, Deserialize)]
143#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
144pub struct ManifestBody {
145 #[serde(default)]
147 pub reason: Option<String>,
148 pub manifest: JobManifest,
150}
151
152impl ManifestBody {
153 pub fn reason(&self) -> Result<String, BodyRefusal> {
162 reason_of(self.reason.as_deref())
163 }
164}
165
166impl ActionBody {
167 pub fn reason(&self) -> Result<String, BodyRefusal> {
176 reason_of(self.reason.as_deref())
177 }
178
179 pub fn into_action(
187 self,
188 kind: ActionKind,
189 ) -> Result<printobserver_core::PrintAction, BodyRefusal> {
190 use printobserver_core::PrintAction as Action;
191
192 let reason = self.reason()?;
193 let actor = self.actor.clone();
194 let duration_s = self.duration_s;
195 Ok(match kind {
196 ActionKind::Pause => Action::Pause { reason, actor },
197 ActionKind::Resume => Action::Resume { reason, actor },
198 ActionKind::Cancel => Action::Cancel { reason, actor },
199 ActionKind::StartPrint => Action::StartPrint {
200 file_name: needed(self.file_name, "file_name")?,
201 manifest: needed(self.manifest, "manifest")?,
202 override_filament_check: self.override_filament_check,
203 override_material_check: self.override_material_check,
204 override_sheet_check: self.override_sheet_check,
205 reason,
206 actor,
207 },
208 ActionKind::SetFeedrateFactor => Action::SetFeedrateFactor {
209 factor: needed(self.factor, "factor")?,
210 duration_s,
211 reason,
212 actor,
213 },
214 ActionKind::SetFlowrateFactor => Action::SetFlowrateFactor {
215 factor: needed(self.factor, "factor")?,
216 duration_s,
217 reason,
218 actor,
219 },
220 ActionKind::SetToolTargetC => Action::SetToolTargetC {
221 tool: needed(self.tool, "tool")?,
222 target_c: needed(self.target_c, "target_c")?,
223 duration_s,
224 reason,
225 actor,
226 },
227 ActionKind::SetBedTargetC => Action::SetBedTargetC {
228 target_c: needed(self.target_c, "target_c")?,
229 duration_s,
230 reason,
231 actor,
232 },
233 ActionKind::SetFanPercent => Action::SetFanPercent {
234 percent: needed(self.percent, "percent")?,
235 duration_s,
236 reason,
237 actor,
238 },
239 ActionKind::AcknowledgeFailure => Action::AcknowledgeFailure {
240 event_id: needed(self.event_id, "event_id")?,
241 disposition: needed(self.disposition, "disposition")?,
242 reason,
243 actor,
244 },
245 ActionKind::ClosePrint => Action::ClosePrint {
246 outcome: needed(self.outcome, "outcome")?,
247 reason,
248 actor,
249 },
250 ActionKind::RegisterSpool
251 | ActionKind::LoadSpool
252 | ActionKind::UnloadSpool
253 | ActionKind::AdjustSpool
254 | ActionKind::RetireSpool => {
255 return Err(BodyRefusal {
256 detail: format!(
257 "{kind:?} is a spool command, and no print-action operation carries one"
258 ),
259 });
260 }
261 })
262 }
263}
264
265#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
267#[serde(crate = "printobserver_types::serde")]
268#[schemars(crate = "printobserver_types::schemars")]
269pub struct ActionAnswer {
270 pub record: ActionRecord,
274 #[serde(skip_serializing_if = "Option::is_none")]
276 pub intervention: Option<Intervention>,
277 #[serde(skip_serializing_if = "Option::is_none")]
279 pub printer_refusal: Option<String>,
280}
281
282pub fn spool_command_of(
296 kind: ActionKind,
297 spool_id: Option<SpoolId>,
298 body: Value,
299) -> Result<SpoolCommand, BodyRefusal> {
300 let Value::Object(mut fields) = body else {
301 return Err(BodyRefusal {
302 detail: "a spool command's body is a document of its fields".to_owned(),
303 });
304 };
305 let reason = reason_of(fields.get("reason").and_then(Value::as_str))?;
306 fields.insert("reason".to_owned(), Value::String(reason));
307 let tag = crate::operations::COMMAND_TAG;
308 for routed in [tag, "spool_id"] {
309 if fields.contains_key(routed) {
310 return Err(BodyRefusal {
311 detail: format!(
312 "a spool command's body does not carry `{routed}`: the operation it is \
313 sent to names it"
314 ),
315 });
316 }
317 }
318 let named = printobserver_types::serde_json::to_value(kind).map_err(|error| BodyRefusal {
319 detail: error.to_string(),
320 })?;
321 fields.insert(tag.to_owned(), named);
322 if let Some(spool_id) = spool_id {
323 fields.insert("spool_id".to_owned(), Value::String(spool_id.to_string()));
324 }
325 let command: SpoolCommand = printobserver_types::serde_json::from_value(Value::Object(fields))
326 .map_err(|error| BodyRefusal {
327 detail: format!("this is not a `{}` body: {error}", spool_command_name(kind)),
328 })?;
329 if command.kind() == kind {
330 Ok(command)
331 } else {
332 Err(BodyRefusal {
333 detail: format!("this body is not a `{}`", spool_command_name(kind)),
334 })
335 }
336}
337
338fn spool_command_name(kind: ActionKind) -> String {
340 printobserver_types::serde_json::to_value(kind)
341 .ok()
342 .and_then(|value| value.as_str().map(str::to_owned))
343 .unwrap_or_else(|| format!("{kind:?}"))
344}
345
346pub fn claimed_actor(body: &Map<String, Value>) -> Result<Actor, BodyRefusal> {
353 let Some(actor) = body.get("actor") else {
354 return missing("actor");
355 };
356 printobserver_types::serde_json::from_value(actor.clone()).map_err(|error| BodyRefusal {
357 detail: format!("`actor` is not an actor this system has: {error}"),
358 })
359}
360
361pub fn recovery_of(
374 kind: RecoveryActionKind,
375 body: Value,
376) -> Result<(RecoveryAction, Actor, String), BodyRefusal> {
377 let Value::Object(mut fields) = body else {
378 return Err(BodyRefusal {
379 detail: "a recovery action's body is a document of its fields".to_owned(),
380 });
381 };
382 let reason = reason_of(fields.get("reason").and_then(Value::as_str))?;
383 let actor = claimed_actor(&fields)?;
384 fields.remove("reason");
385 fields.remove("actor");
386 if fields.contains_key("action") {
387 return Err(BodyRefusal {
388 detail: "a recovery action's body does not carry `action`: the operation it is \
389 sent to names it"
390 .to_owned(),
391 });
392 }
393 fields.insert("action".to_owned(), Value::String(kind.as_str().to_owned()));
394 let action: RecoveryAction = printobserver_types::serde_json::from_value(Value::Object(fields))
395 .map_err(|error| BodyRefusal {
396 detail: format!("this is not a `{kind}` body: {error}"),
397 })?;
398 if action.kind() == kind {
399 Ok((action, actor, reason))
400 } else {
401 Err(BodyRefusal {
402 detail: format!("this body is not a `{kind}`"),
403 })
404 }
405}
406
407#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
413#[serde(crate = "printobserver_types::serde")]
414#[schemars(crate = "printobserver_types::schemars")]
415pub struct RecoveryAnswer {
416 pub action: RecoveryAction,
418 pub decision: RecoveryDecision,
420 pub detail: String,
423 pub events: Vec<EventRecord>,
426}
427
428pub type RecoveryStatusAnswer = printobserver_core::RecoveryStatus;
431
432#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
438#[serde(crate = "printobserver_types::serde")]
439#[schemars(crate = "printobserver_types::schemars")]
440pub struct SpoolCommandAnswer {
441 pub decision: PolicyDecision,
443 #[serde(skip_serializing_if = "Option::is_none")]
445 pub spool: Option<SpoolRecord>,
446 pub events: Vec<EventRecord>,
448}
449
450#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
458#[serde(crate = "printobserver_types::serde")]
459#[schemars(crate = "printobserver_types::schemars")]
460pub struct SpoolsAnswer {
461 pub at_a_glance: Vec<String>,
463 pub spools: Vec<SpoolRecord>,
466 pub pending: Vec<PendingCharge>,
469}
470
471impl SpoolsAnswer {
472 #[must_use]
474 pub fn of(spools: Vec<SpoolRecord>, pending: Vec<PendingCharge>) -> Self {
475 Self {
476 at_a_glance: spools.iter().map(at_a_glance).collect(),
477 spools,
478 pending,
479 }
480 }
481}
482
483#[must_use]
491pub fn at_a_glance(spool: &SpoolRecord) -> String {
492 let place = spool
493 .loaded_tool()
494 .map_or_else(|| "not loaded".to_owned(), |tool| format!("on tool {tool}"));
495 let trust = match &spool.trust {
496 SpoolTrust::Verified => "verified".to_owned(),
497 SpoolTrust::Unverified { marks } => {
498 let oldest = marks.first().map_or_else(String::new, |mark| {
499 printobserver_types::serde_json::to_value(mark.reason.kind())
500 .ok()
501 .and_then(|named| named.as_str().map(str::to_owned))
502 .unwrap_or_default()
503 });
504 let more = marks.len().saturating_sub(1);
505 if more == 0 {
506 format!("unverified: {oldest}")
507 } else {
508 format!("unverified: {oldest} (+{more} more)")
509 }
510 }
511 };
512 let retired = if spool.is_retired() { " | retired" } else { "" };
513 format!(
514 "{} | {} | {:.1} g of {:.1} g left | {place} | {trust}{retired}",
515 spool.name, spool.material, spool.remaining_g, spool.initial_g
516 )
517}
518
519#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
522#[serde(crate = "printobserver_types::serde")]
523#[schemars(crate = "printobserver_types::schemars")]
524pub struct SpoolAnswer {
525 pub spool: SpoolRecord,
527 pub recent: Vec<EventRecord>,
529}
530
531#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
533#[serde(crate = "printobserver_types::serde")]
534#[schemars(crate = "printobserver_types::schemars")]
535pub struct TimelineAnswer {
536 pub events: Vec<EventRecord>,
538 #[serde(skip_serializing_if = "Option::is_none")]
541 pub next: Option<EventId>,
542}
543
544#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
546#[serde(crate = "printobserver_types::serde")]
547#[schemars(crate = "printobserver_types::schemars")]
548pub struct PreflightAnswer {
549 pub preflight: Preflight,
551}
552
553#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
555#[serde(crate = "printobserver_types::serde")]
556#[schemars(crate = "printobserver_types::schemars")]
557pub struct StatusAnswer {
558 pub print: PrintRecord,
560 #[serde(skip_serializing_if = "Option::is_none")]
562 pub printer: Option<PrinterSnapshot>,
563 #[serde(skip_serializing_if = "Option::is_none")]
565 pub job: Option<JobSnapshot>,
566 #[serde(skip_serializing_if = "Option::is_none")]
568 pub session: Option<SupervisionSession>,
569 pub interventions: Vec<Intervention>,
571 pub detector: DetectorHealth,
573}
574
575#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
587#[serde(crate = "printobserver_types::serde")]
588#[schemars(crate = "printobserver_types::schemars")]
589pub struct ContextAnswer {
590 pub context: AgentContext,
592 #[serde(skip_serializing_if = "Option::is_none")]
594 pub image_path: Option<PathBuf>,
595}
596
597pub type LookAnswer = printobserver_core::Look;
602
603#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
610#[serde(crate = "printobserver_types::serde")]
611#[schemars(crate = "printobserver_types::schemars")]
612pub struct ImageAnswer {
613 pub record: ImageRecord,
615 #[serde(skip_serializing_if = "Option::is_none")]
617 pub path: Option<PathBuf>,
618}
619
620impl From<ImageLookup> for ImageAnswer {
621 fn from(lookup: ImageLookup) -> Self {
622 match lookup {
623 ImageLookup::Found { record, path } => Self {
624 record,
625 path: Some(path),
626 },
627 ImageLookup::FileMissing { record } => Self { record, path: None },
628 }
629 }
630}
631
632#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
639#[serde(crate = "printobserver_types::serde")]
640#[schemars(crate = "printobserver_types::schemars")]
641pub struct PrintsAnswer {
642 pub prints: Vec<PrintRecord>,
644 #[serde(skip_serializing_if = "Option::is_none")]
648 pub active: Option<PrintId>,
649}
650
651#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
653#[serde(crate = "printobserver_types::serde")]
654#[schemars(crate = "printobserver_types::schemars")]
655pub struct HistoryAnswer {
656 pub events: Vec<EventRecord>,
658}
659
660#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
663#[serde(crate = "printobserver_types::serde")]
664#[schemars(crate = "printobserver_types::schemars")]
665#[schemars(transform = cursor_is_always_sent)]
666pub struct EventsAnswer {
667 pub events: Vec<EventRecord>,
670 pub cursor: Option<EventId>,
674 #[serde(default, skip_serializing_if = "Option::is_none")]
679 #[schemars(extend("x-null-is-sent" = true))]
680 pub print_ended: Option<Option<PrintEnded>>,
681}
682
683fn cursor_is_always_sent(schema: &mut printobserver_types::schemars::Schema) {
688 if let Some(Value::Array(required)) = schema.get_mut("required") {
689 required.push(Value::from("cursor"));
690 }
691}
692
693#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
695#[serde(crate = "printobserver_types::serde")]
696#[schemars(crate = "printobserver_types::schemars")]
697pub struct PrintEnded {
698 pub event_id: EventId,
700 pub received_at: Timestamp,
702 pub outcome: PrintOutcome,
704}
705
706#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
708#[serde(crate = "printobserver_types::serde")]
709#[schemars(crate = "printobserver_types::schemars")]
710pub struct ManifestAnswer {
711 #[serde(skip_serializing_if = "Option::is_none")]
713 pub manifest: Option<JobManifest>,
714 pub narrowings: Vec<ManifestNarrowing>,
718}
719
720#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
722#[serde(crate = "printobserver_types::serde")]
723#[schemars(crate = "printobserver_types::schemars")]
724pub struct ErrorAnswer {
725 pub error: String,
727}
728
729impl ErrorAnswer {
730 pub fn saying(detail: impl core::fmt::Display) -> Self {
732 Self {
733 error: detail.to_string(),
734 }
735 }
736}
737
738#[derive(Debug, Clone, Copy, PartialEq, Eq)]
744pub struct IngressAnswer;
745
746impl Serialize for IngressAnswer {
747 fn serialize<S: printobserver_types::serde::Serializer>(
748 &self,
749 serializer: S,
750 ) -> Result<S::Ok, S::Error> {
751 use printobserver_types::serde::ser::SerializeStruct as _;
752 let mut state = serializer.serialize_struct("IngressAnswer", 1)?;
753 state.serialize_field("accepted", &true)?;
754 state.end()
755 }
756}
757
758#[cfg(test)]
759mod tests {
760 use printobserver_core::{ActionKind, Actor, ImageRecord};
761 use printobserver_types::contract::Sample as _;
762
763 use super::{ActionBody, ErrorAnswer, ImageAnswer, ImageLookup};
764
765 fn bare() -> ActionBody {
767 ActionBody {
768 reason: Some("a test is asking".to_owned()),
769 actor: Actor::Operator,
770 duration_s: None,
771 factor: None,
772 target_c: None,
773 percent: None,
774 tool: None,
775 file_name: None,
776 manifest: None,
777 override_filament_check: false,
778 override_material_check: false,
779 override_sheet_check: false,
780 event_id: None,
781 disposition: None,
782 outcome: None,
783 }
784 }
785
786 #[test]
792 fn every_action_that_needs_a_value_it_was_not_given_is_refused_naming_it() {
793 let needed = [
794 (ActionKind::StartPrint, "file_name"),
795 (ActionKind::SetFeedrateFactor, "factor"),
796 (ActionKind::SetFlowrateFactor, "factor"),
797 (ActionKind::SetToolTargetC, "tool"),
798 (ActionKind::SetBedTargetC, "target_c"),
799 (ActionKind::SetFanPercent, "percent"),
800 (ActionKind::AcknowledgeFailure, "event_id"),
801 (ActionKind::ClosePrint, "outcome"),
802 ];
803 for (kind, named) in needed {
804 let refusal = bare()
805 .into_action(kind)
806 .expect_err("this action needs a value the body does not carry");
807 assert!(
808 refusal.to_string().contains(named),
809 "{kind:?} was refused without naming `{named}`: {refusal}"
810 );
811 }
812 }
813
814 #[test]
817 fn a_spool_command_kind_is_refused_as_a_print_action() {
818 for kind in [
819 ActionKind::RegisterSpool,
820 ActionKind::LoadSpool,
821 ActionKind::UnloadSpool,
822 ActionKind::AdjustSpool,
823 ActionKind::RetireSpool,
824 ] {
825 let refusal = bare()
826 .into_action(kind)
827 .expect_err("a spool command is not a print action");
828 assert!(
829 refusal.to_string().contains("spool command"),
830 "{kind:?} was refused without saying why: {refusal}"
831 );
832 }
833 }
834
835 #[test]
837 fn the_second_value_a_two_valued_action_needs_is_named_in_its_turn() {
838 let mut starting = bare();
839 starting.file_name = Some(printobserver_types::FileName::new("a.gcode").expect("a name"));
840 assert!(
841 starting
842 .into_action(ActionKind::StartPrint)
843 .expect_err("a start needs a manifest")
844 .to_string()
845 .contains("manifest")
846 );
847
848 let mut tool = bare();
849 tool.tool = Some(0);
850 assert!(
851 tool.into_action(ActionKind::SetToolTargetC)
852 .expect_err("a tool target needs a temperature")
853 .to_string()
854 .contains("target_c")
855 );
856
857 let mut acknowledgement = bare();
858 acknowledgement.event_id = Some(printobserver_types::EventId::new());
859 assert!(
860 acknowledgement
861 .into_action(ActionKind::AcknowledgeFailure)
862 .expect_err("an acknowledgement needs a disposition")
863 .to_string()
864 .contains("disposition")
865 );
866 }
867
868 #[test]
870 fn a_reason_that_is_nothing_but_whitespace_is_no_reason() {
871 let mut blank = bare();
872 blank.reason = Some(" ".to_owned());
873 assert!(blank.reason().is_err());
874 let mut absent = bare();
875 absent.reason = None;
876 assert!(absent.reason().is_err());
877 assert_eq!(bare().reason().expect("a reason"), "a test is asking");
878 }
879
880 #[test]
885 fn an_image_whose_file_is_gone_answers_the_record_and_no_path() {
886 let record = ImageRecord::sample_full();
887 let missing = ImageAnswer::from(ImageLookup::FileMissing {
888 record: record.clone(),
889 });
890 assert_eq!(missing.record, record);
891 assert_eq!(missing.path, None);
892
893 let found = ImageAnswer::from(ImageLookup::Found {
894 record: record.clone(),
895 path: "/var/lib/printobserver/images/ab/cd".into(),
896 });
897 assert_eq!(
898 found.path.as_deref(),
899 Some(std::path::Path::new("/var/lib/printobserver/images/ab/cd"))
900 );
901 }
902
903 #[test]
905 fn a_refusal_answers_in_the_words_of_whatever_refused_it() {
906 assert_eq!(
907 ErrorAnswer::saying("the disk is full").error,
908 "the disk is full"
909 );
910 }
911}