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, SpoolCommand, SpoolId, SpoolRecord, SpoolTrust,
18};
19use printobserver_core::{DetectorHealth, PrintContext};
20use printobserver_printer_api::{JobSnapshot, PrinterSnapshot};
21use printobserver_supervisor_api::SupervisionSession;
22use printobserver_types::schemars::JsonSchema;
23use printobserver_types::serde::{Deserialize, Serialize};
24use printobserver_types::serde_json::{Map, Value};
25use printobserver_types::{EventId, EventRecord, FileName, PrintId, Timestamp};
26
27#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct BodyRefusal {
30 pub detail: String,
32}
33
34impl core::fmt::Display for BodyRefusal {
35 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
36 formatter.write_str(&self.detail)
37 }
38}
39
40#[derive(Debug, Clone, PartialEq, Deserialize)]
49#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
50pub struct ActionBody {
51 #[serde(default)]
53 pub reason: Option<String>,
54 pub actor: Actor,
56 #[serde(default)]
58 pub duration_s: Option<i64>,
59 #[serde(default)]
61 pub factor: Option<f64>,
62 #[serde(default)]
64 pub target_c: Option<f64>,
65 #[serde(default)]
67 pub percent: Option<f64>,
68 #[serde(default)]
70 pub tool: Option<i64>,
71 #[serde(default)]
73 pub file_name: Option<FileName>,
74 #[serde(default)]
76 pub manifest: Option<JobManifest>,
77 #[serde(default)]
81 pub override_filament_check: bool,
82 #[serde(default)]
84 pub event_id: Option<EventId>,
85 #[serde(default)]
87 pub disposition: Option<AcknowledgementDisposition>,
88 #[serde(default)]
90 pub outcome: Option<PrintOutcome>,
91}
92
93fn missing<T>(named: &str) -> Result<T, BodyRefusal> {
95 Err(BodyRefusal {
96 detail: format!("this operation needs `{named}`, and the request carries none"),
97 })
98}
99
100fn needed<T>(value: Option<T>, named: &str) -> Result<T, BodyRefusal> {
102 value.map_or_else(|| missing(named), Ok)
103}
104
105pub fn reason_of(reason: Option<&str>) -> Result<String, BodyRefusal> {
117 match reason.map(str::trim) {
118 Some(reason) if !reason.is_empty() => Ok(reason.to_owned()),
119 _ => Err(BodyRefusal {
120 detail: "every mutating request carries a `reason`, and this one carries none"
121 .to_owned(),
122 }),
123 }
124}
125
126#[derive(Debug, Clone, PartialEq, Deserialize)]
132#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
133pub struct ManifestBody {
134 #[serde(default)]
136 pub reason: Option<String>,
137 pub manifest: JobManifest,
139}
140
141impl ManifestBody {
142 pub fn reason(&self) -> Result<String, BodyRefusal> {
151 reason_of(self.reason.as_deref())
152 }
153}
154
155impl ActionBody {
156 pub fn reason(&self) -> Result<String, BodyRefusal> {
165 reason_of(self.reason.as_deref())
166 }
167
168 pub fn into_action(
176 self,
177 kind: ActionKind,
178 ) -> Result<printobserver_core::PrintAction, BodyRefusal> {
179 use printobserver_core::PrintAction as Action;
180
181 let reason = self.reason()?;
182 let actor = self.actor.clone();
183 let duration_s = self.duration_s;
184 Ok(match kind {
185 ActionKind::Pause => Action::Pause { reason, actor },
186 ActionKind::Resume => Action::Resume { reason, actor },
187 ActionKind::Cancel => Action::Cancel { reason, actor },
188 ActionKind::StartPrint => Action::StartPrint {
189 file_name: needed(self.file_name, "file_name")?,
190 manifest: needed(self.manifest, "manifest")?,
191 override_filament_check: self.override_filament_check,
192 reason,
193 actor,
194 },
195 ActionKind::SetFeedrateFactor => Action::SetFeedrateFactor {
196 factor: needed(self.factor, "factor")?,
197 duration_s,
198 reason,
199 actor,
200 },
201 ActionKind::SetFlowrateFactor => Action::SetFlowrateFactor {
202 factor: needed(self.factor, "factor")?,
203 duration_s,
204 reason,
205 actor,
206 },
207 ActionKind::SetToolTargetC => Action::SetToolTargetC {
208 tool: needed(self.tool, "tool")?,
209 target_c: needed(self.target_c, "target_c")?,
210 duration_s,
211 reason,
212 actor,
213 },
214 ActionKind::SetBedTargetC => Action::SetBedTargetC {
215 target_c: needed(self.target_c, "target_c")?,
216 duration_s,
217 reason,
218 actor,
219 },
220 ActionKind::SetFanPercent => Action::SetFanPercent {
221 percent: needed(self.percent, "percent")?,
222 duration_s,
223 reason,
224 actor,
225 },
226 ActionKind::AcknowledgeFailure => Action::AcknowledgeFailure {
227 event_id: needed(self.event_id, "event_id")?,
228 disposition: needed(self.disposition, "disposition")?,
229 reason,
230 actor,
231 },
232 ActionKind::ClosePrint => Action::ClosePrint {
233 outcome: needed(self.outcome, "outcome")?,
234 reason,
235 actor,
236 },
237 ActionKind::RegisterSpool
238 | ActionKind::LoadSpool
239 | ActionKind::UnloadSpool
240 | ActionKind::AdjustSpool
241 | ActionKind::RetireSpool => {
242 return Err(BodyRefusal {
243 detail: format!(
244 "{kind:?} is a spool command, and no print-action operation carries one"
245 ),
246 });
247 }
248 })
249 }
250}
251
252#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
254#[serde(crate = "printobserver_types::serde")]
255#[schemars(crate = "printobserver_types::schemars")]
256pub struct ActionAnswer {
257 pub record: ActionRecord,
261 #[serde(skip_serializing_if = "Option::is_none")]
263 pub intervention: Option<Intervention>,
264 #[serde(skip_serializing_if = "Option::is_none")]
266 pub printer_refusal: Option<String>,
267}
268
269pub fn spool_command_of(
283 kind: ActionKind,
284 spool_id: Option<SpoolId>,
285 body: Value,
286) -> Result<SpoolCommand, BodyRefusal> {
287 let Value::Object(mut fields) = body else {
288 return Err(BodyRefusal {
289 detail: "a spool command's body is a document of its fields".to_owned(),
290 });
291 };
292 let reason = reason_of(fields.get("reason").and_then(Value::as_str))?;
293 fields.insert("reason".to_owned(), Value::String(reason));
294 let tag = crate::operations::COMMAND_TAG;
295 for routed in [tag, "spool_id"] {
296 if fields.contains_key(routed) {
297 return Err(BodyRefusal {
298 detail: format!(
299 "a spool command's body does not carry `{routed}`: the operation it is \
300 sent to names it"
301 ),
302 });
303 }
304 }
305 let named = printobserver_types::serde_json::to_value(kind).map_err(|error| BodyRefusal {
306 detail: error.to_string(),
307 })?;
308 fields.insert(tag.to_owned(), named);
309 if let Some(spool_id) = spool_id {
310 fields.insert("spool_id".to_owned(), Value::String(spool_id.to_string()));
311 }
312 let command: SpoolCommand = printobserver_types::serde_json::from_value(Value::Object(fields))
313 .map_err(|error| BodyRefusal {
314 detail: format!("this is not a `{}` body: {error}", spool_command_name(kind)),
315 })?;
316 if command.kind() == kind {
317 Ok(command)
318 } else {
319 Err(BodyRefusal {
320 detail: format!("this body is not a `{}`", spool_command_name(kind)),
321 })
322 }
323}
324
325fn spool_command_name(kind: ActionKind) -> String {
327 printobserver_types::serde_json::to_value(kind)
328 .ok()
329 .and_then(|value| value.as_str().map(str::to_owned))
330 .unwrap_or_else(|| format!("{kind:?}"))
331}
332
333pub fn claimed_actor(body: &Map<String, Value>) -> Result<Actor, BodyRefusal> {
340 let Some(actor) = body.get("actor") else {
341 return missing("actor");
342 };
343 printobserver_types::serde_json::from_value(actor.clone()).map_err(|error| BodyRefusal {
344 detail: format!("`actor` is not an actor this system has: {error}"),
345 })
346}
347
348#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
354#[serde(crate = "printobserver_types::serde")]
355#[schemars(crate = "printobserver_types::schemars")]
356pub struct SpoolCommandAnswer {
357 pub decision: PolicyDecision,
359 #[serde(skip_serializing_if = "Option::is_none")]
361 pub spool: Option<SpoolRecord>,
362 pub events: Vec<EventRecord>,
364}
365
366#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
374#[serde(crate = "printobserver_types::serde")]
375#[schemars(crate = "printobserver_types::schemars")]
376pub struct SpoolsAnswer {
377 pub at_a_glance: Vec<String>,
379 pub spools: Vec<SpoolRecord>,
382 pub pending: Vec<PendingCharge>,
385}
386
387impl SpoolsAnswer {
388 #[must_use]
390 pub fn of(spools: Vec<SpoolRecord>, pending: Vec<PendingCharge>) -> Self {
391 Self {
392 at_a_glance: spools.iter().map(at_a_glance).collect(),
393 spools,
394 pending,
395 }
396 }
397}
398
399#[must_use]
407pub fn at_a_glance(spool: &SpoolRecord) -> String {
408 let place = spool
409 .loaded_tool()
410 .map_or_else(|| "not loaded".to_owned(), |tool| format!("on tool {tool}"));
411 let trust = match &spool.trust {
412 SpoolTrust::Verified => "verified".to_owned(),
413 SpoolTrust::Unverified { marks } => {
414 let oldest = marks.first().map_or_else(String::new, |mark| {
415 printobserver_types::serde_json::to_value(mark.reason.kind())
416 .ok()
417 .and_then(|named| named.as_str().map(str::to_owned))
418 .unwrap_or_default()
419 });
420 let more = marks.len().saturating_sub(1);
421 if more == 0 {
422 format!("unverified: {oldest}")
423 } else {
424 format!("unverified: {oldest} (+{more} more)")
425 }
426 }
427 };
428 let retired = if spool.is_retired() { " | retired" } else { "" };
429 format!(
430 "{} | {} | {:.1} g of {:.1} g left | {place} | {trust}{retired}",
431 spool.name, spool.material, spool.remaining_g, spool.initial_g
432 )
433}
434
435#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
438#[serde(crate = "printobserver_types::serde")]
439#[schemars(crate = "printobserver_types::schemars")]
440pub struct SpoolAnswer {
441 pub spool: SpoolRecord,
443 pub recent: Vec<EventRecord>,
445}
446
447#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
449#[serde(crate = "printobserver_types::serde")]
450#[schemars(crate = "printobserver_types::schemars")]
451pub struct TimelineAnswer {
452 pub events: Vec<EventRecord>,
454 #[serde(skip_serializing_if = "Option::is_none")]
457 pub next: Option<EventId>,
458}
459
460#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
462#[serde(crate = "printobserver_types::serde")]
463#[schemars(crate = "printobserver_types::schemars")]
464pub struct PreflightAnswer {
465 pub preflight: Preflight,
467}
468
469#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
471#[serde(crate = "printobserver_types::serde")]
472#[schemars(crate = "printobserver_types::schemars")]
473pub struct StatusAnswer {
474 pub print: PrintRecord,
476 #[serde(skip_serializing_if = "Option::is_none")]
478 pub printer: Option<PrinterSnapshot>,
479 #[serde(skip_serializing_if = "Option::is_none")]
481 pub job: Option<JobSnapshot>,
482 #[serde(skip_serializing_if = "Option::is_none")]
484 pub session: Option<SupervisionSession>,
485 pub interventions: Vec<Intervention>,
487 pub detector: DetectorHealth,
489}
490
491#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
500#[serde(crate = "printobserver_types::serde")]
501#[schemars(crate = "printobserver_types::schemars")]
502pub struct ContextAnswer {
503 pub context: PrintContext,
505 #[serde(skip_serializing_if = "Option::is_none")]
507 pub image_path: Option<PathBuf>,
508}
509
510pub type LookAnswer = printobserver_core::Look;
515
516#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
523#[serde(crate = "printobserver_types::serde")]
524#[schemars(crate = "printobserver_types::schemars")]
525pub struct ImageAnswer {
526 pub record: ImageRecord,
528 #[serde(skip_serializing_if = "Option::is_none")]
530 pub path: Option<PathBuf>,
531}
532
533impl From<ImageLookup> for ImageAnswer {
534 fn from(lookup: ImageLookup) -> Self {
535 match lookup {
536 ImageLookup::Found { record, path } => Self {
537 record,
538 path: Some(path),
539 },
540 ImageLookup::FileMissing { record } => Self { record, path: None },
541 }
542 }
543}
544
545#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
552#[serde(crate = "printobserver_types::serde")]
553#[schemars(crate = "printobserver_types::schemars")]
554pub struct PrintsAnswer {
555 pub prints: Vec<PrintRecord>,
557 #[serde(skip_serializing_if = "Option::is_none")]
561 pub active: Option<PrintId>,
562}
563
564#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
566#[serde(crate = "printobserver_types::serde")]
567#[schemars(crate = "printobserver_types::schemars")]
568pub struct HistoryAnswer {
569 pub events: Vec<EventRecord>,
571}
572
573#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
576#[serde(crate = "printobserver_types::serde")]
577#[schemars(crate = "printobserver_types::schemars")]
578#[schemars(transform = cursor_is_always_sent)]
579pub struct EventsAnswer {
580 pub events: Vec<EventRecord>,
583 pub cursor: Option<EventId>,
587 #[serde(default, skip_serializing_if = "Option::is_none")]
592 #[schemars(extend("x-null-is-sent" = true))]
593 pub print_ended: Option<Option<PrintEnded>>,
594}
595
596fn cursor_is_always_sent(schema: &mut printobserver_types::schemars::Schema) {
601 if let Some(Value::Array(required)) = schema.get_mut("required") {
602 required.push(Value::from("cursor"));
603 }
604}
605
606#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
608#[serde(crate = "printobserver_types::serde")]
609#[schemars(crate = "printobserver_types::schemars")]
610pub struct PrintEnded {
611 pub event_id: EventId,
613 pub received_at: Timestamp,
615 pub outcome: PrintOutcome,
617}
618
619#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
621#[serde(crate = "printobserver_types::serde")]
622#[schemars(crate = "printobserver_types::schemars")]
623pub struct ManifestAnswer {
624 #[serde(skip_serializing_if = "Option::is_none")]
626 pub manifest: Option<JobManifest>,
627 pub narrowings: Vec<ManifestNarrowing>,
631}
632
633#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
635#[serde(crate = "printobserver_types::serde")]
636#[schemars(crate = "printobserver_types::schemars")]
637pub struct ErrorAnswer {
638 pub error: String,
640}
641
642impl ErrorAnswer {
643 pub fn saying(detail: impl core::fmt::Display) -> Self {
645 Self {
646 error: detail.to_string(),
647 }
648 }
649}
650
651#[derive(Debug, Clone, Copy, PartialEq, Eq)]
657pub struct IngressAnswer;
658
659impl Serialize for IngressAnswer {
660 fn serialize<S: printobserver_types::serde::Serializer>(
661 &self,
662 serializer: S,
663 ) -> Result<S::Ok, S::Error> {
664 use printobserver_types::serde::ser::SerializeStruct as _;
665 let mut state = serializer.serialize_struct("IngressAnswer", 1)?;
666 state.serialize_field("accepted", &true)?;
667 state.end()
668 }
669}
670
671#[cfg(test)]
672mod tests {
673 use printobserver_core::{ActionKind, Actor, ImageRecord};
674 use printobserver_types::contract::Sample as _;
675
676 use super::{ActionBody, ErrorAnswer, ImageAnswer, ImageLookup};
677
678 fn bare() -> ActionBody {
680 ActionBody {
681 reason: Some("a test is asking".to_owned()),
682 actor: Actor::Operator,
683 duration_s: None,
684 factor: None,
685 target_c: None,
686 percent: None,
687 tool: None,
688 file_name: None,
689 manifest: None,
690 override_filament_check: false,
691 event_id: None,
692 disposition: None,
693 outcome: None,
694 }
695 }
696
697 #[test]
703 fn every_action_that_needs_a_value_it_was_not_given_is_refused_naming_it() {
704 let needed = [
705 (ActionKind::StartPrint, "file_name"),
706 (ActionKind::SetFeedrateFactor, "factor"),
707 (ActionKind::SetFlowrateFactor, "factor"),
708 (ActionKind::SetToolTargetC, "tool"),
709 (ActionKind::SetBedTargetC, "target_c"),
710 (ActionKind::SetFanPercent, "percent"),
711 (ActionKind::AcknowledgeFailure, "event_id"),
712 (ActionKind::ClosePrint, "outcome"),
713 ];
714 for (kind, named) in needed {
715 let refusal = bare()
716 .into_action(kind)
717 .expect_err("this action needs a value the body does not carry");
718 assert!(
719 refusal.to_string().contains(named),
720 "{kind:?} was refused without naming `{named}`: {refusal}"
721 );
722 }
723 }
724
725 #[test]
728 fn a_spool_command_kind_is_refused_as_a_print_action() {
729 for kind in [
730 ActionKind::RegisterSpool,
731 ActionKind::LoadSpool,
732 ActionKind::UnloadSpool,
733 ActionKind::AdjustSpool,
734 ActionKind::RetireSpool,
735 ] {
736 let refusal = bare()
737 .into_action(kind)
738 .expect_err("a spool command is not a print action");
739 assert!(
740 refusal.to_string().contains("spool command"),
741 "{kind:?} was refused without saying why: {refusal}"
742 );
743 }
744 }
745
746 #[test]
748 fn the_second_value_a_two_valued_action_needs_is_named_in_its_turn() {
749 let mut starting = bare();
750 starting.file_name = Some(printobserver_types::FileName::new("a.gcode").expect("a name"));
751 assert!(
752 starting
753 .into_action(ActionKind::StartPrint)
754 .expect_err("a start needs a manifest")
755 .to_string()
756 .contains("manifest")
757 );
758
759 let mut tool = bare();
760 tool.tool = Some(0);
761 assert!(
762 tool.into_action(ActionKind::SetToolTargetC)
763 .expect_err("a tool target needs a temperature")
764 .to_string()
765 .contains("target_c")
766 );
767
768 let mut acknowledgement = bare();
769 acknowledgement.event_id = Some(printobserver_types::EventId::new());
770 assert!(
771 acknowledgement
772 .into_action(ActionKind::AcknowledgeFailure)
773 .expect_err("an acknowledgement needs a disposition")
774 .to_string()
775 .contains("disposition")
776 );
777 }
778
779 #[test]
781 fn a_reason_that_is_nothing_but_whitespace_is_no_reason() {
782 let mut blank = bare();
783 blank.reason = Some(" ".to_owned());
784 assert!(blank.reason().is_err());
785 let mut absent = bare();
786 absent.reason = None;
787 assert!(absent.reason().is_err());
788 assert_eq!(bare().reason().expect("a reason"), "a test is asking");
789 }
790
791 #[test]
796 fn an_image_whose_file_is_gone_answers_the_record_and_no_path() {
797 let record = ImageRecord::sample_full();
798 let missing = ImageAnswer::from(ImageLookup::FileMissing {
799 record: record.clone(),
800 });
801 assert_eq!(missing.record, record);
802 assert_eq!(missing.path, None);
803
804 let found = ImageAnswer::from(ImageLookup::Found {
805 record: record.clone(),
806 path: "/var/lib/printobserver/images/ab/cd".into(),
807 });
808 assert_eq!(
809 found.path.as_deref(),
810 Some(std::path::Path::new("/var/lib/printobserver/images/ab/cd"))
811 );
812 }
813
814 #[test]
816 fn a_refusal_answers_in_the_words_of_whatever_refused_it() {
817 assert_eq!(
818 ErrorAnswer::saying("the disk is full").error,
819 "the disk is full"
820 );
821 }
822}