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)]
142#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
143pub struct BedClearBody {
144 pub actor: Actor,
146 #[serde(default)]
148 pub reason: Option<String>,
149}
150
151#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
154#[serde(crate = "printobserver_types::serde")]
155#[schemars(crate = "printobserver_types::schemars")]
156pub struct BedClearAnswer {
157 pub event: EventRecord,
159 pub detail: String,
161}
162
163#[derive(Debug, Clone, PartialEq, Deserialize)]
169#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
170pub struct ManifestBody {
171 #[serde(default)]
173 pub reason: Option<String>,
174 pub manifest: JobManifest,
176}
177
178impl ManifestBody {
179 pub fn reason(&self) -> Result<String, BodyRefusal> {
188 reason_of(self.reason.as_deref())
189 }
190}
191
192impl ActionBody {
193 pub fn reason(&self) -> Result<String, BodyRefusal> {
202 reason_of(self.reason.as_deref())
203 }
204
205 pub fn into_action(
213 self,
214 kind: ActionKind,
215 ) -> Result<printobserver_core::PrintAction, BodyRefusal> {
216 use printobserver_core::PrintAction as Action;
217
218 let reason = self.reason()?;
219 let actor = self.actor.clone();
220 let duration_s = self.duration_s;
221 Ok(match kind {
222 ActionKind::Pause => Action::Pause { reason, actor },
223 ActionKind::Resume => Action::Resume { reason, actor },
224 ActionKind::Cancel => Action::Cancel { reason, actor },
225 ActionKind::StartPrint => Action::StartPrint {
226 file_name: needed(self.file_name, "file_name")?,
227 manifest: needed(self.manifest, "manifest")?,
228 override_filament_check: self.override_filament_check,
229 override_material_check: self.override_material_check,
230 override_sheet_check: self.override_sheet_check,
231 reason,
232 actor,
233 },
234 ActionKind::SetFeedrateFactor => Action::SetFeedrateFactor {
235 factor: needed(self.factor, "factor")?,
236 duration_s,
237 reason,
238 actor,
239 },
240 ActionKind::SetFlowrateFactor => Action::SetFlowrateFactor {
241 factor: needed(self.factor, "factor")?,
242 duration_s,
243 reason,
244 actor,
245 },
246 ActionKind::SetToolTargetC => Action::SetToolTargetC {
247 tool: needed(self.tool, "tool")?,
248 target_c: needed(self.target_c, "target_c")?,
249 duration_s,
250 reason,
251 actor,
252 },
253 ActionKind::SetBedTargetC => Action::SetBedTargetC {
254 target_c: needed(self.target_c, "target_c")?,
255 duration_s,
256 reason,
257 actor,
258 },
259 ActionKind::SetFanPercent => Action::SetFanPercent {
260 percent: needed(self.percent, "percent")?,
261 duration_s,
262 reason,
263 actor,
264 },
265 ActionKind::AcknowledgeFailure => Action::AcknowledgeFailure {
266 event_id: needed(self.event_id, "event_id")?,
267 disposition: needed(self.disposition, "disposition")?,
268 reason,
269 actor,
270 },
271 ActionKind::ClosePrint => Action::ClosePrint {
272 outcome: needed(self.outcome, "outcome")?,
273 reason,
274 actor,
275 },
276 ActionKind::RegisterSpool
277 | ActionKind::LoadSpool
278 | ActionKind::UnloadSpool
279 | ActionKind::AdjustSpool
280 | ActionKind::RetireSpool => {
281 return Err(BodyRefusal {
282 detail: format!(
283 "{kind:?} is a spool command, and no print-action operation carries one"
284 ),
285 });
286 }
287 })
288 }
289}
290
291#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
293#[serde(crate = "printobserver_types::serde")]
294#[schemars(crate = "printobserver_types::schemars")]
295pub struct ActionAnswer {
296 pub record: ActionRecord,
300 #[serde(skip_serializing_if = "Option::is_none")]
302 pub intervention: Option<Intervention>,
303 #[serde(skip_serializing_if = "Option::is_none")]
305 pub printer_refusal: Option<String>,
306}
307
308pub fn spool_command_of(
322 kind: ActionKind,
323 spool_id: Option<SpoolId>,
324 body: Value,
325) -> Result<SpoolCommand, BodyRefusal> {
326 let Value::Object(mut fields) = body else {
327 return Err(BodyRefusal {
328 detail: "a spool command's body is a document of its fields".to_owned(),
329 });
330 };
331 let reason = reason_of(fields.get("reason").and_then(Value::as_str))?;
332 fields.insert("reason".to_owned(), Value::String(reason));
333 let tag = crate::operations::COMMAND_TAG;
334 for routed in [tag, "spool_id"] {
335 if fields.contains_key(routed) {
336 return Err(BodyRefusal {
337 detail: format!(
338 "a spool command's body does not carry `{routed}`: the operation it is \
339 sent to names it"
340 ),
341 });
342 }
343 }
344 let named = printobserver_types::serde_json::to_value(kind).map_err(|error| BodyRefusal {
345 detail: error.to_string(),
346 })?;
347 fields.insert(tag.to_owned(), named);
348 if let Some(spool_id) = spool_id {
349 fields.insert("spool_id".to_owned(), Value::String(spool_id.to_string()));
350 }
351 let command: SpoolCommand = printobserver_types::serde_json::from_value(Value::Object(fields))
352 .map_err(|error| BodyRefusal {
353 detail: format!("this is not a `{}` body: {error}", spool_command_name(kind)),
354 })?;
355 if command.kind() == kind {
356 Ok(command)
357 } else {
358 Err(BodyRefusal {
359 detail: format!("this body is not a `{}`", spool_command_name(kind)),
360 })
361 }
362}
363
364fn spool_command_name(kind: ActionKind) -> String {
366 printobserver_types::serde_json::to_value(kind)
367 .ok()
368 .and_then(|value| value.as_str().map(str::to_owned))
369 .unwrap_or_else(|| format!("{kind:?}"))
370}
371
372pub fn claimed_actor(body: &Map<String, Value>) -> Result<Actor, BodyRefusal> {
379 let Some(actor) = body.get("actor") else {
380 return missing("actor");
381 };
382 printobserver_types::serde_json::from_value(actor.clone()).map_err(|error| BodyRefusal {
383 detail: format!("`actor` is not an actor this system has: {error}"),
384 })
385}
386
387pub fn recovery_of(
400 kind: RecoveryActionKind,
401 body: Value,
402) -> Result<(RecoveryAction, Actor, String), BodyRefusal> {
403 let Value::Object(mut fields) = body else {
404 return Err(BodyRefusal {
405 detail: "a recovery action's body is a document of its fields".to_owned(),
406 });
407 };
408 let reason = reason_of(fields.get("reason").and_then(Value::as_str))?;
409 let actor = claimed_actor(&fields)?;
410 fields.remove("reason");
411 fields.remove("actor");
412 if fields.contains_key("action") {
413 return Err(BodyRefusal {
414 detail: "a recovery action's body does not carry `action`: the operation it is \
415 sent to names it"
416 .to_owned(),
417 });
418 }
419 fields.insert("action".to_owned(), Value::String(kind.as_str().to_owned()));
420 let action: RecoveryAction = printobserver_types::serde_json::from_value(Value::Object(fields))
421 .map_err(|error| BodyRefusal {
422 detail: format!("this is not a `{kind}` body: {error}"),
423 })?;
424 if action.kind() == kind {
425 Ok((action, actor, reason))
426 } else {
427 Err(BodyRefusal {
428 detail: format!("this body is not a `{kind}`"),
429 })
430 }
431}
432
433#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
439#[serde(crate = "printobserver_types::serde")]
440#[schemars(crate = "printobserver_types::schemars")]
441pub struct RecoveryAnswer {
442 pub action: RecoveryAction,
444 pub decision: RecoveryDecision,
446 pub detail: String,
449 pub events: Vec<EventRecord>,
452}
453
454pub type RecoveryStatusAnswer = printobserver_core::RecoveryStatus;
457
458#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
464#[serde(crate = "printobserver_types::serde")]
465#[schemars(crate = "printobserver_types::schemars")]
466pub struct SpoolCommandAnswer {
467 pub decision: PolicyDecision,
469 #[serde(skip_serializing_if = "Option::is_none")]
471 pub spool: Option<SpoolRecord>,
472 pub events: Vec<EventRecord>,
474}
475
476#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
484#[serde(crate = "printobserver_types::serde")]
485#[schemars(crate = "printobserver_types::schemars")]
486pub struct SpoolsAnswer {
487 pub at_a_glance: Vec<String>,
489 pub spools: Vec<SpoolRecord>,
492 pub pending: Vec<PendingCharge>,
495}
496
497impl SpoolsAnswer {
498 #[must_use]
500 pub fn of(spools: Vec<SpoolRecord>, pending: Vec<PendingCharge>) -> Self {
501 Self {
502 at_a_glance: spools.iter().map(at_a_glance).collect(),
503 spools,
504 pending,
505 }
506 }
507}
508
509#[must_use]
517pub fn at_a_glance(spool: &SpoolRecord) -> String {
518 let place = spool
519 .loaded_tool()
520 .map_or_else(|| "not loaded".to_owned(), |tool| format!("on tool {tool}"));
521 let trust = match &spool.trust {
522 SpoolTrust::Verified => "verified".to_owned(),
523 SpoolTrust::Unverified { marks } => {
524 let oldest = marks.first().map_or_else(String::new, |mark| {
525 printobserver_types::serde_json::to_value(mark.reason.kind())
526 .ok()
527 .and_then(|named| named.as_str().map(str::to_owned))
528 .unwrap_or_default()
529 });
530 let more = marks.len().saturating_sub(1);
531 if more == 0 {
532 format!("unverified: {oldest}")
533 } else {
534 format!("unverified: {oldest} (+{more} more)")
535 }
536 }
537 };
538 let retired = if spool.is_retired() { " | retired" } else { "" };
539 format!(
540 "{} | {} | {:.1} g of {:.1} g left | {place} | {trust}{retired}",
541 spool.name, spool.material, spool.remaining_g, spool.initial_g
542 )
543}
544
545#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
548#[serde(crate = "printobserver_types::serde")]
549#[schemars(crate = "printobserver_types::schemars")]
550pub struct SpoolAnswer {
551 pub spool: SpoolRecord,
553 pub recent: Vec<EventRecord>,
555}
556
557#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
559#[serde(crate = "printobserver_types::serde")]
560#[schemars(crate = "printobserver_types::schemars")]
561pub struct TimelineAnswer {
562 pub events: Vec<EventRecord>,
564 #[serde(skip_serializing_if = "Option::is_none")]
567 pub next: Option<EventId>,
568}
569
570#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
572#[serde(crate = "printobserver_types::serde")]
573#[schemars(crate = "printobserver_types::schemars")]
574pub struct PreflightAnswer {
575 pub preflight: Preflight,
577}
578
579#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
581#[serde(crate = "printobserver_types::serde")]
582#[schemars(crate = "printobserver_types::schemars")]
583pub struct StatusAnswer {
584 pub print: PrintRecord,
586 #[serde(skip_serializing_if = "Option::is_none")]
588 pub printer: Option<PrinterSnapshot>,
589 #[serde(skip_serializing_if = "Option::is_none")]
591 pub job: Option<JobSnapshot>,
592 #[serde(skip_serializing_if = "Option::is_none")]
594 pub session: Option<SupervisionSession>,
595 pub interventions: Vec<Intervention>,
597 pub detector: DetectorHealth,
599}
600
601#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
613#[serde(crate = "printobserver_types::serde")]
614#[schemars(crate = "printobserver_types::schemars")]
615pub struct ContextAnswer {
616 pub context: AgentContext,
618 #[serde(skip_serializing_if = "Option::is_none")]
620 pub image_path: Option<PathBuf>,
621}
622
623pub type LookAnswer = printobserver_core::Look;
628
629#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
636#[serde(crate = "printobserver_types::serde")]
637#[schemars(crate = "printobserver_types::schemars")]
638pub struct ImageAnswer {
639 pub record: ImageRecord,
641 #[serde(skip_serializing_if = "Option::is_none")]
643 pub path: Option<PathBuf>,
644}
645
646impl From<ImageLookup> for ImageAnswer {
647 fn from(lookup: ImageLookup) -> Self {
648 match lookup {
649 ImageLookup::Found { record, path } => Self {
650 record,
651 path: Some(path),
652 },
653 ImageLookup::FileMissing { record } => Self { record, path: None },
654 }
655 }
656}
657
658#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
665#[serde(crate = "printobserver_types::serde")]
666#[schemars(crate = "printobserver_types::schemars")]
667pub struct PrintsAnswer {
668 pub prints: Vec<PrintRecord>,
670 #[serde(skip_serializing_if = "Option::is_none")]
674 pub active: Option<PrintId>,
675}
676
677#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
679#[serde(crate = "printobserver_types::serde")]
680#[schemars(crate = "printobserver_types::schemars")]
681pub struct HistoryAnswer {
682 pub events: Vec<EventRecord>,
684}
685
686#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
689#[serde(crate = "printobserver_types::serde")]
690#[schemars(crate = "printobserver_types::schemars")]
691#[schemars(transform = cursor_is_always_sent)]
692pub struct EventsAnswer {
693 pub events: Vec<EventRecord>,
696 pub cursor: Option<EventId>,
700 #[serde(default, skip_serializing_if = "Option::is_none")]
705 #[schemars(extend("x-null-is-sent" = true))]
706 pub print_ended: Option<Option<PrintEnded>>,
707}
708
709fn cursor_is_always_sent(schema: &mut printobserver_types::schemars::Schema) {
714 if let Some(Value::Array(required)) = schema.get_mut("required") {
715 required.push(Value::from("cursor"));
716 }
717}
718
719#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
721#[serde(crate = "printobserver_types::serde")]
722#[schemars(crate = "printobserver_types::schemars")]
723pub struct PrintEnded {
724 pub event_id: EventId,
726 pub received_at: Timestamp,
728 pub outcome: PrintOutcome,
730}
731
732#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
734#[serde(crate = "printobserver_types::serde")]
735#[schemars(crate = "printobserver_types::schemars")]
736pub struct ManifestAnswer {
737 #[serde(skip_serializing_if = "Option::is_none")]
739 pub manifest: Option<JobManifest>,
740 pub narrowings: Vec<ManifestNarrowing>,
744}
745
746#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
748#[serde(crate = "printobserver_types::serde")]
749#[schemars(crate = "printobserver_types::schemars")]
750pub struct ErrorAnswer {
751 pub error: String,
753}
754
755impl ErrorAnswer {
756 pub fn saying(detail: impl core::fmt::Display) -> Self {
758 Self {
759 error: detail.to_string(),
760 }
761 }
762}
763
764#[derive(Debug, Clone, Copy, PartialEq, Eq)]
770pub struct IngressAnswer;
771
772impl Serialize for IngressAnswer {
773 fn serialize<S: printobserver_types::serde::Serializer>(
774 &self,
775 serializer: S,
776 ) -> Result<S::Ok, S::Error> {
777 use printobserver_types::serde::ser::SerializeStruct as _;
778 let mut state = serializer.serialize_struct("IngressAnswer", 1)?;
779 state.serialize_field("accepted", &true)?;
780 state.end()
781 }
782}
783
784#[cfg(test)]
785mod tests {
786 use printobserver_core::{ActionKind, Actor, ImageRecord};
787 use printobserver_types::contract::Sample as _;
788
789 use super::{ActionBody, ErrorAnswer, ImageAnswer, ImageLookup};
790
791 fn bare() -> ActionBody {
793 ActionBody {
794 reason: Some("a test is asking".to_owned()),
795 actor: Actor::Operator,
796 duration_s: None,
797 factor: None,
798 target_c: None,
799 percent: None,
800 tool: None,
801 file_name: None,
802 manifest: None,
803 override_filament_check: false,
804 override_material_check: false,
805 override_sheet_check: false,
806 event_id: None,
807 disposition: None,
808 outcome: None,
809 }
810 }
811
812 #[test]
818 fn every_action_that_needs_a_value_it_was_not_given_is_refused_naming_it() {
819 let needed = [
820 (ActionKind::StartPrint, "file_name"),
821 (ActionKind::SetFeedrateFactor, "factor"),
822 (ActionKind::SetFlowrateFactor, "factor"),
823 (ActionKind::SetToolTargetC, "tool"),
824 (ActionKind::SetBedTargetC, "target_c"),
825 (ActionKind::SetFanPercent, "percent"),
826 (ActionKind::AcknowledgeFailure, "event_id"),
827 (ActionKind::ClosePrint, "outcome"),
828 ];
829 for (kind, named) in needed {
830 let refusal = bare()
831 .into_action(kind)
832 .expect_err("this action needs a value the body does not carry");
833 assert!(
834 refusal.to_string().contains(named),
835 "{kind:?} was refused without naming `{named}`: {refusal}"
836 );
837 }
838 }
839
840 #[test]
843 fn a_spool_command_kind_is_refused_as_a_print_action() {
844 for kind in [
845 ActionKind::RegisterSpool,
846 ActionKind::LoadSpool,
847 ActionKind::UnloadSpool,
848 ActionKind::AdjustSpool,
849 ActionKind::RetireSpool,
850 ] {
851 let refusal = bare()
852 .into_action(kind)
853 .expect_err("a spool command is not a print action");
854 assert!(
855 refusal.to_string().contains("spool command"),
856 "{kind:?} was refused without saying why: {refusal}"
857 );
858 }
859 }
860
861 #[test]
863 fn the_second_value_a_two_valued_action_needs_is_named_in_its_turn() {
864 let mut starting = bare();
865 starting.file_name = Some(printobserver_types::FileName::new("a.gcode").expect("a name"));
866 assert!(
867 starting
868 .into_action(ActionKind::StartPrint)
869 .expect_err("a start needs a manifest")
870 .to_string()
871 .contains("manifest")
872 );
873
874 let mut tool = bare();
875 tool.tool = Some(0);
876 assert!(
877 tool.into_action(ActionKind::SetToolTargetC)
878 .expect_err("a tool target needs a temperature")
879 .to_string()
880 .contains("target_c")
881 );
882
883 let mut acknowledgement = bare();
884 acknowledgement.event_id = Some(printobserver_types::EventId::new());
885 assert!(
886 acknowledgement
887 .into_action(ActionKind::AcknowledgeFailure)
888 .expect_err("an acknowledgement needs a disposition")
889 .to_string()
890 .contains("disposition")
891 );
892 }
893
894 #[test]
896 fn a_reason_that_is_nothing_but_whitespace_is_no_reason() {
897 let mut blank = bare();
898 blank.reason = Some(" ".to_owned());
899 assert!(blank.reason().is_err());
900 let mut absent = bare();
901 absent.reason = None;
902 assert!(absent.reason().is_err());
903 assert_eq!(bare().reason().expect("a reason"), "a test is asking");
904 }
905
906 #[test]
911 fn an_image_whose_file_is_gone_answers_the_record_and_no_path() {
912 let record = ImageRecord::sample_full();
913 let missing = ImageAnswer::from(ImageLookup::FileMissing {
914 record: record.clone(),
915 });
916 assert_eq!(missing.record, record);
917 assert_eq!(missing.path, None);
918
919 let found = ImageAnswer::from(ImageLookup::Found {
920 record: record.clone(),
921 path: "/var/lib/printobserver/images/ab/cd".into(),
922 });
923 assert_eq!(
924 found.path.as_deref(),
925 Some(std::path::Path::new("/var/lib/printobserver/images/ab/cd"))
926 );
927 }
928
929 #[test]
931 fn a_refusal_answers_in_the_words_of_whatever_refused_it() {
932 assert_eq!(
933 ErrorAnswer::saying("the disk is full").error,
934 "the disk is full"
935 );
936 }
937}