1use std::path::PathBuf;
12
13use printobserver_core::PrintContext;
14use printobserver_core::store::ImageLookup;
15use printobserver_core::{
16 AcknowledgementDisposition, ActionKind, ActionRecord, Actor, ImageRecord, Intervention,
17 JobManifest, ManifestNarrowing, PendingCharge, PolicyDecision, Preflight, PrintOutcome,
18 PrintRecord, SpoolCommand, SpoolId, SpoolRecord, SpoolTrust,
19};
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}
488
489#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
498#[serde(crate = "printobserver_types::serde")]
499#[schemars(crate = "printobserver_types::schemars")]
500pub struct ContextAnswer {
501 pub context: PrintContext,
503 #[serde(skip_serializing_if = "Option::is_none")]
505 pub image_path: Option<PathBuf>,
506}
507
508pub type LookAnswer = printobserver_core::Look;
513
514#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
521#[serde(crate = "printobserver_types::serde")]
522#[schemars(crate = "printobserver_types::schemars")]
523pub struct ImageAnswer {
524 pub record: ImageRecord,
526 #[serde(skip_serializing_if = "Option::is_none")]
528 pub path: Option<PathBuf>,
529}
530
531impl From<ImageLookup> for ImageAnswer {
532 fn from(lookup: ImageLookup) -> Self {
533 match lookup {
534 ImageLookup::Found { record, path } => Self {
535 record,
536 path: Some(path),
537 },
538 ImageLookup::FileMissing { record } => Self { record, path: None },
539 }
540 }
541}
542
543#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
550#[serde(crate = "printobserver_types::serde")]
551#[schemars(crate = "printobserver_types::schemars")]
552pub struct PrintsAnswer {
553 pub prints: Vec<PrintRecord>,
555 #[serde(skip_serializing_if = "Option::is_none")]
559 pub active: Option<PrintId>,
560}
561
562#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
564#[serde(crate = "printobserver_types::serde")]
565#[schemars(crate = "printobserver_types::schemars")]
566pub struct HistoryAnswer {
567 pub events: Vec<EventRecord>,
569}
570
571#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
574#[serde(crate = "printobserver_types::serde")]
575#[schemars(crate = "printobserver_types::schemars")]
576#[schemars(transform = cursor_is_always_sent)]
577pub struct EventsAnswer {
578 pub events: Vec<EventRecord>,
581 pub cursor: Option<EventId>,
585 #[serde(default, skip_serializing_if = "Option::is_none")]
590 #[schemars(extend("x-null-is-sent" = true))]
591 pub print_ended: Option<Option<PrintEnded>>,
592}
593
594fn cursor_is_always_sent(schema: &mut printobserver_types::schemars::Schema) {
599 if let Some(Value::Array(required)) = schema.get_mut("required") {
600 required.push(Value::from("cursor"));
601 }
602}
603
604#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
606#[serde(crate = "printobserver_types::serde")]
607#[schemars(crate = "printobserver_types::schemars")]
608pub struct PrintEnded {
609 pub event_id: EventId,
611 pub received_at: Timestamp,
613 pub outcome: PrintOutcome,
615}
616
617#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
619#[serde(crate = "printobserver_types::serde")]
620#[schemars(crate = "printobserver_types::schemars")]
621pub struct ManifestAnswer {
622 #[serde(skip_serializing_if = "Option::is_none")]
624 pub manifest: Option<JobManifest>,
625 pub narrowings: Vec<ManifestNarrowing>,
629}
630
631#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
633#[serde(crate = "printobserver_types::serde")]
634#[schemars(crate = "printobserver_types::schemars")]
635pub struct ErrorAnswer {
636 pub error: String,
638}
639
640impl ErrorAnswer {
641 pub fn saying(detail: impl core::fmt::Display) -> Self {
643 Self {
644 error: detail.to_string(),
645 }
646 }
647}
648
649#[derive(Debug, Clone, Copy, PartialEq, Eq)]
655pub struct IngressAnswer;
656
657impl Serialize for IngressAnswer {
658 fn serialize<S: printobserver_types::serde::Serializer>(
659 &self,
660 serializer: S,
661 ) -> Result<S::Ok, S::Error> {
662 use printobserver_types::serde::ser::SerializeStruct as _;
663 let mut state = serializer.serialize_struct("IngressAnswer", 1)?;
664 state.serialize_field("accepted", &true)?;
665 state.end()
666 }
667}
668
669#[cfg(test)]
670mod tests {
671 use printobserver_core::{ActionKind, Actor, ImageRecord};
672 use printobserver_types::contract::Sample as _;
673
674 use super::{ActionBody, ErrorAnswer, ImageAnswer, ImageLookup};
675
676 fn bare() -> ActionBody {
678 ActionBody {
679 reason: Some("a test is asking".to_owned()),
680 actor: Actor::Operator,
681 duration_s: None,
682 factor: None,
683 target_c: None,
684 percent: None,
685 tool: None,
686 file_name: None,
687 manifest: None,
688 override_filament_check: false,
689 event_id: None,
690 disposition: None,
691 outcome: None,
692 }
693 }
694
695 #[test]
701 fn every_action_that_needs_a_value_it_was_not_given_is_refused_naming_it() {
702 let needed = [
703 (ActionKind::StartPrint, "file_name"),
704 (ActionKind::SetFeedrateFactor, "factor"),
705 (ActionKind::SetFlowrateFactor, "factor"),
706 (ActionKind::SetToolTargetC, "tool"),
707 (ActionKind::SetBedTargetC, "target_c"),
708 (ActionKind::SetFanPercent, "percent"),
709 (ActionKind::AcknowledgeFailure, "event_id"),
710 (ActionKind::ClosePrint, "outcome"),
711 ];
712 for (kind, named) in needed {
713 let refusal = bare()
714 .into_action(kind)
715 .expect_err("this action needs a value the body does not carry");
716 assert!(
717 refusal.to_string().contains(named),
718 "{kind:?} was refused without naming `{named}`: {refusal}"
719 );
720 }
721 }
722
723 #[test]
726 fn a_spool_command_kind_is_refused_as_a_print_action() {
727 for kind in [
728 ActionKind::RegisterSpool,
729 ActionKind::LoadSpool,
730 ActionKind::UnloadSpool,
731 ActionKind::AdjustSpool,
732 ActionKind::RetireSpool,
733 ] {
734 let refusal = bare()
735 .into_action(kind)
736 .expect_err("a spool command is not a print action");
737 assert!(
738 refusal.to_string().contains("spool command"),
739 "{kind:?} was refused without saying why: {refusal}"
740 );
741 }
742 }
743
744 #[test]
746 fn the_second_value_a_two_valued_action_needs_is_named_in_its_turn() {
747 let mut starting = bare();
748 starting.file_name = Some(printobserver_types::FileName::new("a.gcode").expect("a name"));
749 assert!(
750 starting
751 .into_action(ActionKind::StartPrint)
752 .expect_err("a start needs a manifest")
753 .to_string()
754 .contains("manifest")
755 );
756
757 let mut tool = bare();
758 tool.tool = Some(0);
759 assert!(
760 tool.into_action(ActionKind::SetToolTargetC)
761 .expect_err("a tool target needs a temperature")
762 .to_string()
763 .contains("target_c")
764 );
765
766 let mut acknowledgement = bare();
767 acknowledgement.event_id = Some(printobserver_types::EventId::new());
768 assert!(
769 acknowledgement
770 .into_action(ActionKind::AcknowledgeFailure)
771 .expect_err("an acknowledgement needs a disposition")
772 .to_string()
773 .contains("disposition")
774 );
775 }
776
777 #[test]
779 fn a_reason_that_is_nothing_but_whitespace_is_no_reason() {
780 let mut blank = bare();
781 blank.reason = Some(" ".to_owned());
782 assert!(blank.reason().is_err());
783 let mut absent = bare();
784 absent.reason = None;
785 assert!(absent.reason().is_err());
786 assert_eq!(bare().reason().expect("a reason"), "a test is asking");
787 }
788
789 #[test]
794 fn an_image_whose_file_is_gone_answers_the_record_and_no_path() {
795 let record = ImageRecord::sample_full();
796 let missing = ImageAnswer::from(ImageLookup::FileMissing {
797 record: record.clone(),
798 });
799 assert_eq!(missing.record, record);
800 assert_eq!(missing.path, None);
801
802 let found = ImageAnswer::from(ImageLookup::Found {
803 record: record.clone(),
804 path: "/var/lib/printobserver/images/ab/cd".into(),
805 });
806 assert_eq!(
807 found.path.as_deref(),
808 Some(std::path::Path::new("/var/lib/printobserver/images/ab/cd"))
809 );
810 }
811
812 #[test]
814 fn a_refusal_answers_in_the_words_of_whatever_refused_it() {
815 assert_eq!(
816 ErrorAnswer::saying("the disk is full").error,
817 "the disk is full"
818 );
819 }
820}