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}
89
90fn missing<T>(named: &str) -> Result<T, BodyRefusal> {
92 Err(BodyRefusal {
93 detail: format!("this operation needs `{named}`, and the request carries none"),
94 })
95}
96
97pub fn reason_of(reason: Option<&str>) -> Result<String, BodyRefusal> {
109 match reason.map(str::trim) {
110 Some(reason) if !reason.is_empty() => Ok(reason.to_owned()),
111 _ => Err(BodyRefusal {
112 detail: "every mutating request carries a `reason`, and this one carries none"
113 .to_owned(),
114 }),
115 }
116}
117
118#[derive(Debug, Clone, PartialEq, Deserialize)]
124#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
125pub struct ManifestBody {
126 #[serde(default)]
128 pub reason: Option<String>,
129 pub manifest: JobManifest,
131}
132
133impl ManifestBody {
134 pub fn reason(&self) -> Result<String, BodyRefusal> {
143 reason_of(self.reason.as_deref())
144 }
145}
146
147impl ActionBody {
148 pub fn reason(&self) -> Result<String, BodyRefusal> {
157 reason_of(self.reason.as_deref())
158 }
159
160 pub fn into_action(
168 self,
169 kind: ActionKind,
170 ) -> Result<printobserver_core::PrintAction, BodyRefusal> {
171 use printobserver_core::PrintAction as Action;
172
173 let reason = self.reason()?;
174 let actor = self.actor.clone();
175 let duration_s = self.duration_s;
176 Ok(match kind {
177 ActionKind::Pause => Action::Pause { reason, actor },
178 ActionKind::Resume => Action::Resume { reason, actor },
179 ActionKind::Cancel => Action::Cancel { reason, actor },
180 ActionKind::StartPrint => Action::StartPrint {
181 file_name: match self.file_name {
182 Some(name) => name,
183 None => return missing("file_name"),
184 },
185 manifest: match self.manifest {
186 Some(manifest) => manifest,
187 None => return missing("manifest"),
188 },
189 override_filament_check: self.override_filament_check,
190 reason,
191 actor,
192 },
193 ActionKind::SetFeedrateFactor => Action::SetFeedrateFactor {
194 factor: match self.factor {
195 Some(factor) => factor,
196 None => return missing("factor"),
197 },
198 duration_s,
199 reason,
200 actor,
201 },
202 ActionKind::SetFlowrateFactor => Action::SetFlowrateFactor {
203 factor: match self.factor {
204 Some(factor) => factor,
205 None => return missing("factor"),
206 },
207 duration_s,
208 reason,
209 actor,
210 },
211 ActionKind::SetToolTargetC => Action::SetToolTargetC {
212 tool: match self.tool {
213 Some(tool) => tool,
214 None => return missing("tool"),
215 },
216 target_c: match self.target_c {
217 Some(target) => target,
218 None => return missing("target_c"),
219 },
220 duration_s,
221 reason,
222 actor,
223 },
224 ActionKind::SetBedTargetC => Action::SetBedTargetC {
225 target_c: match self.target_c {
226 Some(target) => target,
227 None => return missing("target_c"),
228 },
229 duration_s,
230 reason,
231 actor,
232 },
233 ActionKind::SetFanPercent => Action::SetFanPercent {
234 percent: match self.percent {
235 Some(percent) => percent,
236 None => return missing("percent"),
237 },
238 duration_s,
239 reason,
240 actor,
241 },
242 ActionKind::AcknowledgeFailure => Action::AcknowledgeFailure {
243 event_id: match self.event_id {
244 Some(event_id) => event_id,
245 None => return missing("event_id"),
246 },
247 disposition: match self.disposition {
248 Some(disposition) => disposition,
249 None => return missing("disposition"),
250 },
251 reason,
252 actor,
253 },
254 ActionKind::RegisterSpool
255 | ActionKind::LoadSpool
256 | ActionKind::UnloadSpool
257 | ActionKind::AdjustSpool
258 | ActionKind::RetireSpool => {
259 return Err(BodyRefusal {
260 detail: format!(
261 "{kind:?} is a spool command, and no print-action operation carries one"
262 ),
263 });
264 }
265 })
266 }
267}
268
269#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
271#[serde(crate = "printobserver_types::serde")]
272#[schemars(crate = "printobserver_types::schemars")]
273pub struct ActionAnswer {
274 pub record: ActionRecord,
278 #[serde(skip_serializing_if = "Option::is_none")]
280 pub intervention: Option<Intervention>,
281 #[serde(skip_serializing_if = "Option::is_none")]
283 pub printer_refusal: Option<String>,
284}
285
286pub fn spool_command_of(
300 kind: ActionKind,
301 spool_id: Option<SpoolId>,
302 body: Value,
303) -> Result<SpoolCommand, BodyRefusal> {
304 let Value::Object(mut fields) = body else {
305 return Err(BodyRefusal {
306 detail: "a spool command's body is a document of its fields".to_owned(),
307 });
308 };
309 let reason = reason_of(fields.get("reason").and_then(Value::as_str))?;
310 fields.insert("reason".to_owned(), Value::String(reason));
311 let tag = crate::operations::COMMAND_TAG;
312 for routed in [tag, "spool_id"] {
313 if fields.contains_key(routed) {
314 return Err(BodyRefusal {
315 detail: format!(
316 "a spool command's body does not carry `{routed}`: the operation it is \
317 sent to names it"
318 ),
319 });
320 }
321 }
322 let named = printobserver_types::serde_json::to_value(kind).map_err(|error| BodyRefusal {
323 detail: error.to_string(),
324 })?;
325 fields.insert(tag.to_owned(), named);
326 if let Some(spool_id) = spool_id {
327 fields.insert("spool_id".to_owned(), Value::String(spool_id.to_string()));
328 }
329 let command: SpoolCommand = printobserver_types::serde_json::from_value(Value::Object(fields))
330 .map_err(|error| BodyRefusal {
331 detail: format!("this is not a `{}` body: {error}", spool_command_name(kind)),
332 })?;
333 if command.kind() == kind {
334 Ok(command)
335 } else {
336 Err(BodyRefusal {
337 detail: format!("this body is not a `{}`", spool_command_name(kind)),
338 })
339 }
340}
341
342fn spool_command_name(kind: ActionKind) -> String {
344 printobserver_types::serde_json::to_value(kind)
345 .ok()
346 .and_then(|value| value.as_str().map(str::to_owned))
347 .unwrap_or_else(|| format!("{kind:?}"))
348}
349
350pub fn claimed_actor(body: &Map<String, Value>) -> Result<Actor, BodyRefusal> {
357 let Some(actor) = body.get("actor") else {
358 return missing("actor");
359 };
360 printobserver_types::serde_json::from_value(actor.clone()).map_err(|error| BodyRefusal {
361 detail: format!("`actor` is not an actor this system has: {error}"),
362 })
363}
364
365#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
371#[serde(crate = "printobserver_types::serde")]
372#[schemars(crate = "printobserver_types::schemars")]
373pub struct SpoolCommandAnswer {
374 pub decision: PolicyDecision,
376 #[serde(skip_serializing_if = "Option::is_none")]
378 pub spool: Option<SpoolRecord>,
379 pub events: Vec<EventRecord>,
381}
382
383#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
391#[serde(crate = "printobserver_types::serde")]
392#[schemars(crate = "printobserver_types::schemars")]
393pub struct SpoolsAnswer {
394 pub at_a_glance: Vec<String>,
396 pub spools: Vec<SpoolRecord>,
399 pub pending: Vec<PendingCharge>,
402}
403
404impl SpoolsAnswer {
405 #[must_use]
407 pub fn of(spools: Vec<SpoolRecord>, pending: Vec<PendingCharge>) -> Self {
408 Self {
409 at_a_glance: spools.iter().map(at_a_glance).collect(),
410 spools,
411 pending,
412 }
413 }
414}
415
416#[must_use]
424pub fn at_a_glance(spool: &SpoolRecord) -> String {
425 let place = spool
426 .loaded_on_tool
427 .map_or_else(|| "not loaded".to_owned(), |tool| format!("on tool {tool}"));
428 let trust = match &spool.trust {
429 SpoolTrust::Verified => "verified".to_owned(),
430 SpoolTrust::Unverified { marks } => {
431 let oldest = marks.first().map_or_else(String::new, |mark| {
432 printobserver_types::serde_json::to_value(mark.reason.kind())
433 .ok()
434 .and_then(|named| named.as_str().map(str::to_owned))
435 .unwrap_or_default()
436 });
437 let more = marks.len().saturating_sub(1);
438 if more == 0 {
439 format!("unverified: {oldest}")
440 } else {
441 format!("unverified: {oldest} (+{more} more)")
442 }
443 }
444 };
445 let retired = if spool.retired_at.is_some() {
446 " | retired"
447 } else {
448 ""
449 };
450 format!(
451 "{} | {} | {:.1} g of {:.1} g left | {place} | {trust}{retired}",
452 spool.name, spool.material, spool.remaining_g, spool.initial_g
453 )
454}
455
456#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
459#[serde(crate = "printobserver_types::serde")]
460#[schemars(crate = "printobserver_types::schemars")]
461pub struct SpoolAnswer {
462 pub spool: SpoolRecord,
464 pub recent: Vec<EventRecord>,
466}
467
468#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
470#[serde(crate = "printobserver_types::serde")]
471#[schemars(crate = "printobserver_types::schemars")]
472pub struct TimelineAnswer {
473 pub events: Vec<EventRecord>,
475 #[serde(skip_serializing_if = "Option::is_none")]
478 pub next: Option<EventId>,
479}
480
481#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
483#[serde(crate = "printobserver_types::serde")]
484#[schemars(crate = "printobserver_types::schemars")]
485pub struct PreflightAnswer {
486 pub preflight: Preflight,
488}
489
490#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
492#[serde(crate = "printobserver_types::serde")]
493#[schemars(crate = "printobserver_types::schemars")]
494pub struct StatusAnswer {
495 pub print: PrintRecord,
497 #[serde(skip_serializing_if = "Option::is_none")]
499 pub printer: Option<PrinterSnapshot>,
500 #[serde(skip_serializing_if = "Option::is_none")]
502 pub job: Option<JobSnapshot>,
503 #[serde(skip_serializing_if = "Option::is_none")]
505 pub session: Option<SupervisionSession>,
506 pub interventions: Vec<Intervention>,
508}
509
510#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
519#[serde(crate = "printobserver_types::serde")]
520#[schemars(crate = "printobserver_types::schemars")]
521pub struct ContextAnswer {
522 pub context: PrintContext,
524 #[serde(skip_serializing_if = "Option::is_none")]
526 pub image_path: Option<PathBuf>,
527}
528
529pub type LookAnswer = printobserver_core::Look;
534
535#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
542#[serde(crate = "printobserver_types::serde")]
543#[schemars(crate = "printobserver_types::schemars")]
544pub struct ImageAnswer {
545 pub record: ImageRecord,
547 #[serde(skip_serializing_if = "Option::is_none")]
549 pub path: Option<PathBuf>,
550}
551
552impl From<ImageLookup> for ImageAnswer {
553 fn from(lookup: ImageLookup) -> Self {
554 match lookup {
555 ImageLookup::Found { record, path } => Self {
556 record,
557 path: Some(path),
558 },
559 ImageLookup::FileMissing { record } => Self { record, path: None },
560 }
561 }
562}
563
564#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
571#[serde(crate = "printobserver_types::serde")]
572#[schemars(crate = "printobserver_types::schemars")]
573pub struct PrintsAnswer {
574 pub prints: Vec<PrintRecord>,
576 #[serde(skip_serializing_if = "Option::is_none")]
580 pub active: Option<PrintId>,
581}
582
583#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
585#[serde(crate = "printobserver_types::serde")]
586#[schemars(crate = "printobserver_types::schemars")]
587pub struct HistoryAnswer {
588 pub events: Vec<EventRecord>,
590}
591
592#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
595#[serde(crate = "printobserver_types::serde")]
596#[schemars(crate = "printobserver_types::schemars")]
597#[schemars(transform = cursor_is_always_sent)]
598pub struct EventsAnswer {
599 pub events: Vec<EventRecord>,
602 pub cursor: Option<EventId>,
606 #[serde(default, skip_serializing_if = "Option::is_none")]
611 #[schemars(extend("x-null-is-sent" = true))]
612 pub print_ended: Option<Option<PrintEnded>>,
613}
614
615fn cursor_is_always_sent(schema: &mut printobserver_types::schemars::Schema) {
620 if let Some(Value::Array(required)) = schema.get_mut("required") {
621 required.push(Value::from("cursor"));
622 }
623}
624
625#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
627#[serde(crate = "printobserver_types::serde")]
628#[schemars(crate = "printobserver_types::schemars")]
629pub struct PrintEnded {
630 pub event_id: EventId,
632 pub received_at: Timestamp,
634 pub outcome: PrintOutcome,
636}
637
638#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
640#[serde(crate = "printobserver_types::serde")]
641#[schemars(crate = "printobserver_types::schemars")]
642pub struct ManifestAnswer {
643 #[serde(skip_serializing_if = "Option::is_none")]
645 pub manifest: Option<JobManifest>,
646 pub narrowings: Vec<ManifestNarrowing>,
650}
651
652#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
654#[serde(crate = "printobserver_types::serde")]
655#[schemars(crate = "printobserver_types::schemars")]
656pub struct ErrorAnswer {
657 pub error: String,
659}
660
661impl ErrorAnswer {
662 pub fn saying(detail: impl core::fmt::Display) -> Self {
664 Self {
665 error: detail.to_string(),
666 }
667 }
668}
669
670#[derive(Debug, Clone, Copy, PartialEq, Eq)]
676pub struct IngressAnswer;
677
678impl Serialize for IngressAnswer {
679 fn serialize<S: printobserver_types::serde::Serializer>(
680 &self,
681 serializer: S,
682 ) -> Result<S::Ok, S::Error> {
683 use printobserver_types::serde::ser::SerializeStruct as _;
684 let mut state = serializer.serialize_struct("IngressAnswer", 1)?;
685 state.serialize_field("accepted", &true)?;
686 state.end()
687 }
688}
689
690#[cfg(test)]
691mod tests {
692 use printobserver_core::{ActionKind, Actor, ImageRecord};
693 use printobserver_types::contract::Sample as _;
694
695 use super::{ActionBody, ErrorAnswer, ImageAnswer, ImageLookup};
696
697 fn bare() -> ActionBody {
699 ActionBody {
700 reason: Some("a test is asking".to_owned()),
701 actor: Actor::Operator,
702 duration_s: None,
703 factor: None,
704 target_c: None,
705 percent: None,
706 tool: None,
707 file_name: None,
708 manifest: None,
709 override_filament_check: false,
710 event_id: None,
711 disposition: None,
712 }
713 }
714
715 #[test]
721 fn every_action_that_needs_a_value_it_was_not_given_is_refused_naming_it() {
722 let needed = [
723 (ActionKind::StartPrint, "file_name"),
724 (ActionKind::SetFeedrateFactor, "factor"),
725 (ActionKind::SetFlowrateFactor, "factor"),
726 (ActionKind::SetToolTargetC, "tool"),
727 (ActionKind::SetBedTargetC, "target_c"),
728 (ActionKind::SetFanPercent, "percent"),
729 (ActionKind::AcknowledgeFailure, "event_id"),
730 ];
731 for (kind, named) in needed {
732 let refusal = bare()
733 .into_action(kind)
734 .expect_err("this action needs a value the body does not carry");
735 assert!(
736 refusal.to_string().contains(named),
737 "{kind:?} was refused without naming `{named}`: {refusal}"
738 );
739 }
740 }
741
742 #[test]
745 fn a_spool_command_kind_is_refused_as_a_print_action() {
746 for kind in [
747 ActionKind::RegisterSpool,
748 ActionKind::LoadSpool,
749 ActionKind::UnloadSpool,
750 ActionKind::AdjustSpool,
751 ActionKind::RetireSpool,
752 ] {
753 let refusal = bare()
754 .into_action(kind)
755 .expect_err("a spool command is not a print action");
756 assert!(
757 refusal.to_string().contains("spool command"),
758 "{kind:?} was refused without saying why: {refusal}"
759 );
760 }
761 }
762
763 #[test]
765 fn the_second_value_a_two_valued_action_needs_is_named_in_its_turn() {
766 let mut starting = bare();
767 starting.file_name = Some(printobserver_types::FileName::new("a.gcode").expect("a name"));
768 assert!(
769 starting
770 .into_action(ActionKind::StartPrint)
771 .expect_err("a start needs a manifest")
772 .to_string()
773 .contains("manifest")
774 );
775
776 let mut tool = bare();
777 tool.tool = Some(0);
778 assert!(
779 tool.into_action(ActionKind::SetToolTargetC)
780 .expect_err("a tool target needs a temperature")
781 .to_string()
782 .contains("target_c")
783 );
784
785 let mut acknowledgement = bare();
786 acknowledgement.event_id = Some(printobserver_types::EventId::new());
787 assert!(
788 acknowledgement
789 .into_action(ActionKind::AcknowledgeFailure)
790 .expect_err("an acknowledgement needs a disposition")
791 .to_string()
792 .contains("disposition")
793 );
794 }
795
796 #[test]
798 fn a_reason_that_is_nothing_but_whitespace_is_no_reason() {
799 let mut blank = bare();
800 blank.reason = Some(" ".to_owned());
801 assert!(blank.reason().is_err());
802 let mut absent = bare();
803 absent.reason = None;
804 assert!(absent.reason().is_err());
805 assert_eq!(bare().reason().expect("a reason"), "a test is asking");
806 }
807
808 #[test]
813 fn an_image_whose_file_is_gone_answers_the_record_and_no_path() {
814 let record = ImageRecord::sample_full();
815 let missing = ImageAnswer::from(ImageLookup::FileMissing {
816 record: record.clone(),
817 });
818 assert_eq!(missing.record, record);
819 assert_eq!(missing.path, None);
820
821 let found = ImageAnswer::from(ImageLookup::Found {
822 record: record.clone(),
823 path: "/var/lib/printobserver/images/ab/cd".into(),
824 });
825 assert_eq!(
826 found.path.as_deref(),
827 Some(std::path::Path::new("/var/lib/printobserver/images/ab/cd"))
828 );
829 }
830
831 #[test]
833 fn a_refusal_answers_in_the_words_of_whatever_refused_it() {
834 assert_eq!(
835 ErrorAnswer::saying("the disk is full").error,
836 "the disk is full"
837 );
838 }
839}