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_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.is_retired() { " | retired" } else { "" };
446 format!(
447 "{} | {} | {:.1} g of {:.1} g left | {place} | {trust}{retired}",
448 spool.name, spool.material, spool.remaining_g, spool.initial_g
449 )
450}
451
452#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
455#[serde(crate = "printobserver_types::serde")]
456#[schemars(crate = "printobserver_types::schemars")]
457pub struct SpoolAnswer {
458 pub spool: SpoolRecord,
460 pub recent: Vec<EventRecord>,
462}
463
464#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
466#[serde(crate = "printobserver_types::serde")]
467#[schemars(crate = "printobserver_types::schemars")]
468pub struct TimelineAnswer {
469 pub events: Vec<EventRecord>,
471 #[serde(skip_serializing_if = "Option::is_none")]
474 pub next: Option<EventId>,
475}
476
477#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
479#[serde(crate = "printobserver_types::serde")]
480#[schemars(crate = "printobserver_types::schemars")]
481pub struct PreflightAnswer {
482 pub preflight: Preflight,
484}
485
486#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
488#[serde(crate = "printobserver_types::serde")]
489#[schemars(crate = "printobserver_types::schemars")]
490pub struct StatusAnswer {
491 pub print: PrintRecord,
493 #[serde(skip_serializing_if = "Option::is_none")]
495 pub printer: Option<PrinterSnapshot>,
496 #[serde(skip_serializing_if = "Option::is_none")]
498 pub job: Option<JobSnapshot>,
499 #[serde(skip_serializing_if = "Option::is_none")]
501 pub session: Option<SupervisionSession>,
502 pub interventions: Vec<Intervention>,
504}
505
506#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
515#[serde(crate = "printobserver_types::serde")]
516#[schemars(crate = "printobserver_types::schemars")]
517pub struct ContextAnswer {
518 pub context: PrintContext,
520 #[serde(skip_serializing_if = "Option::is_none")]
522 pub image_path: Option<PathBuf>,
523}
524
525pub type LookAnswer = printobserver_core::Look;
530
531#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
538#[serde(crate = "printobserver_types::serde")]
539#[schemars(crate = "printobserver_types::schemars")]
540pub struct ImageAnswer {
541 pub record: ImageRecord,
543 #[serde(skip_serializing_if = "Option::is_none")]
545 pub path: Option<PathBuf>,
546}
547
548impl From<ImageLookup> for ImageAnswer {
549 fn from(lookup: ImageLookup) -> Self {
550 match lookup {
551 ImageLookup::Found { record, path } => Self {
552 record,
553 path: Some(path),
554 },
555 ImageLookup::FileMissing { record } => Self { record, path: None },
556 }
557 }
558}
559
560#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
567#[serde(crate = "printobserver_types::serde")]
568#[schemars(crate = "printobserver_types::schemars")]
569pub struct PrintsAnswer {
570 pub prints: Vec<PrintRecord>,
572 #[serde(skip_serializing_if = "Option::is_none")]
576 pub active: Option<PrintId>,
577}
578
579#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
581#[serde(crate = "printobserver_types::serde")]
582#[schemars(crate = "printobserver_types::schemars")]
583pub struct HistoryAnswer {
584 pub events: Vec<EventRecord>,
586}
587
588#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
591#[serde(crate = "printobserver_types::serde")]
592#[schemars(crate = "printobserver_types::schemars")]
593#[schemars(transform = cursor_is_always_sent)]
594pub struct EventsAnswer {
595 pub events: Vec<EventRecord>,
598 pub cursor: Option<EventId>,
602 #[serde(default, skip_serializing_if = "Option::is_none")]
607 #[schemars(extend("x-null-is-sent" = true))]
608 pub print_ended: Option<Option<PrintEnded>>,
609}
610
611fn cursor_is_always_sent(schema: &mut printobserver_types::schemars::Schema) {
616 if let Some(Value::Array(required)) = schema.get_mut("required") {
617 required.push(Value::from("cursor"));
618 }
619}
620
621#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
623#[serde(crate = "printobserver_types::serde")]
624#[schemars(crate = "printobserver_types::schemars")]
625pub struct PrintEnded {
626 pub event_id: EventId,
628 pub received_at: Timestamp,
630 pub outcome: PrintOutcome,
632}
633
634#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
636#[serde(crate = "printobserver_types::serde")]
637#[schemars(crate = "printobserver_types::schemars")]
638pub struct ManifestAnswer {
639 #[serde(skip_serializing_if = "Option::is_none")]
641 pub manifest: Option<JobManifest>,
642 pub narrowings: Vec<ManifestNarrowing>,
646}
647
648#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
650#[serde(crate = "printobserver_types::serde")]
651#[schemars(crate = "printobserver_types::schemars")]
652pub struct ErrorAnswer {
653 pub error: String,
655}
656
657impl ErrorAnswer {
658 pub fn saying(detail: impl core::fmt::Display) -> Self {
660 Self {
661 error: detail.to_string(),
662 }
663 }
664}
665
666#[derive(Debug, Clone, Copy, PartialEq, Eq)]
672pub struct IngressAnswer;
673
674impl Serialize for IngressAnswer {
675 fn serialize<S: printobserver_types::serde::Serializer>(
676 &self,
677 serializer: S,
678 ) -> Result<S::Ok, S::Error> {
679 use printobserver_types::serde::ser::SerializeStruct as _;
680 let mut state = serializer.serialize_struct("IngressAnswer", 1)?;
681 state.serialize_field("accepted", &true)?;
682 state.end()
683 }
684}
685
686#[cfg(test)]
687mod tests {
688 use printobserver_core::{ActionKind, Actor, ImageRecord};
689 use printobserver_types::contract::Sample as _;
690
691 use super::{ActionBody, ErrorAnswer, ImageAnswer, ImageLookup};
692
693 fn bare() -> ActionBody {
695 ActionBody {
696 reason: Some("a test is asking".to_owned()),
697 actor: Actor::Operator,
698 duration_s: None,
699 factor: None,
700 target_c: None,
701 percent: None,
702 tool: None,
703 file_name: None,
704 manifest: None,
705 override_filament_check: false,
706 event_id: None,
707 disposition: None,
708 }
709 }
710
711 #[test]
717 fn every_action_that_needs_a_value_it_was_not_given_is_refused_naming_it() {
718 let needed = [
719 (ActionKind::StartPrint, "file_name"),
720 (ActionKind::SetFeedrateFactor, "factor"),
721 (ActionKind::SetFlowrateFactor, "factor"),
722 (ActionKind::SetToolTargetC, "tool"),
723 (ActionKind::SetBedTargetC, "target_c"),
724 (ActionKind::SetFanPercent, "percent"),
725 (ActionKind::AcknowledgeFailure, "event_id"),
726 ];
727 for (kind, named) in needed {
728 let refusal = bare()
729 .into_action(kind)
730 .expect_err("this action needs a value the body does not carry");
731 assert!(
732 refusal.to_string().contains(named),
733 "{kind:?} was refused without naming `{named}`: {refusal}"
734 );
735 }
736 }
737
738 #[test]
741 fn a_spool_command_kind_is_refused_as_a_print_action() {
742 for kind in [
743 ActionKind::RegisterSpool,
744 ActionKind::LoadSpool,
745 ActionKind::UnloadSpool,
746 ActionKind::AdjustSpool,
747 ActionKind::RetireSpool,
748 ] {
749 let refusal = bare()
750 .into_action(kind)
751 .expect_err("a spool command is not a print action");
752 assert!(
753 refusal.to_string().contains("spool command"),
754 "{kind:?} was refused without saying why: {refusal}"
755 );
756 }
757 }
758
759 #[test]
761 fn the_second_value_a_two_valued_action_needs_is_named_in_its_turn() {
762 let mut starting = bare();
763 starting.file_name = Some(printobserver_types::FileName::new("a.gcode").expect("a name"));
764 assert!(
765 starting
766 .into_action(ActionKind::StartPrint)
767 .expect_err("a start needs a manifest")
768 .to_string()
769 .contains("manifest")
770 );
771
772 let mut tool = bare();
773 tool.tool = Some(0);
774 assert!(
775 tool.into_action(ActionKind::SetToolTargetC)
776 .expect_err("a tool target needs a temperature")
777 .to_string()
778 .contains("target_c")
779 );
780
781 let mut acknowledgement = bare();
782 acknowledgement.event_id = Some(printobserver_types::EventId::new());
783 assert!(
784 acknowledgement
785 .into_action(ActionKind::AcknowledgeFailure)
786 .expect_err("an acknowledgement needs a disposition")
787 .to_string()
788 .contains("disposition")
789 );
790 }
791
792 #[test]
794 fn a_reason_that_is_nothing_but_whitespace_is_no_reason() {
795 let mut blank = bare();
796 blank.reason = Some(" ".to_owned());
797 assert!(blank.reason().is_err());
798 let mut absent = bare();
799 absent.reason = None;
800 assert!(absent.reason().is_err());
801 assert_eq!(bare().reason().expect("a reason"), "a test is asking");
802 }
803
804 #[test]
809 fn an_image_whose_file_is_gone_answers_the_record_and_no_path() {
810 let record = ImageRecord::sample_full();
811 let missing = ImageAnswer::from(ImageLookup::FileMissing {
812 record: record.clone(),
813 });
814 assert_eq!(missing.record, record);
815 assert_eq!(missing.path, None);
816
817 let found = ImageAnswer::from(ImageLookup::Found {
818 record: record.clone(),
819 path: "/var/lib/printobserver/images/ab/cd".into(),
820 });
821 assert_eq!(
822 found.path.as_deref(),
823 Some(std::path::Path::new("/var/lib/printobserver/images/ab/cd"))
824 );
825 }
826
827 #[test]
829 fn a_refusal_answers_in_the_words_of_whatever_refused_it() {
830 assert_eq!(
831 ErrorAnswer::saying("the disk is full").error,
832 "the disk is full"
833 );
834 }
835}