1use printobserver_types::serde_json::{Value, json};
63
64pub use printobserver_core::{
69 ActionKind, PrintAction, RecoveryAction, RecoveryActionKind, SpoolCommand,
70};
71
72pub const VERSION_PREFIX: &str = "/v1";
74
75pub const MEDIA_TYPE: &str = "application/json";
77
78pub const INGRESS_PATH: &str = "/obico/webhook";
81
82pub const CONTEXT_IMAGE_PATH_FIELD: &str = "image_path";
84
85pub const IMAGE_PATH_FIELD: &str = "path";
87
88const ACTION_TAG: &str = "action";
91
92pub const COMMAND_TAG: &str = "command";
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
98pub enum Method {
99 Get,
101 Post,
103 Put,
105}
106
107impl Method {
108 #[must_use]
110 pub const fn as_str(self) -> &'static str {
111 match self {
112 Self::Get => "GET",
113 Self::Post => "POST",
114 Self::Put => "PUT",
115 }
116 }
117}
118
119impl core::fmt::Display for Method {
120 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
121 formatter.write_str(self.as_str())
122 }
123}
124
125#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
127pub enum Located {
128 Path,
130 Query,
132 Body,
134}
135
136#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
143pub enum ValueKind {
144 Text,
146 Number,
148 Integer,
150 Boolean,
152 Structured,
154}
155
156impl ValueKind {
157 #[must_use]
159 pub const fn structured(self) -> bool {
160 matches!(self, Self::Structured)
161 }
162}
163
164#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
170pub struct Declared {
171 pub name: &'static str,
173 pub required: bool,
175 pub kind: ValueKind,
177 pub shape: Option<&'static str>,
184 pub repeated: bool,
187}
188
189impl Declared {
190 #[must_use]
192 pub const fn once(name: &'static str, required: bool, kind: ValueKind) -> Self {
193 Self {
194 name,
195 required,
196 kind,
197 shape: None,
198 repeated: false,
199 }
200 }
201}
202
203#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
205pub struct Parameter {
206 pub name: String,
208 pub required: bool,
210 pub located: Located,
212 pub kind: ValueKind,
214 pub repeated: bool,
216}
217
218#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
220pub enum Answer {
221 Success,
223 Rejected,
225}
226
227impl Answer {
228 #[must_use]
230 pub const fn as_str(self) -> &'static str {
231 match self {
232 Self::Success => "success",
233 Self::Rejected => "rejected",
234 }
235 }
236}
237
238impl core::fmt::Display for Answer {
239 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
240 formatter.write_str(self.as_str())
241 }
242}
243
244#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
246pub enum Effect {
247 Read,
249 Mutating(ActionKind),
251 Command(SpoolCommandKind),
255 Recovery(RecoveryActionKind),
259 Write,
261}
262
263#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
270pub enum SpoolCommandKind {
271 RegisterSpool,
273 LoadSpool,
275 UnloadSpool,
277 AdjustSpool,
279 RetireSpool,
281}
282
283impl SpoolCommandKind {
284 pub const ALL: [Self; 5] = [
286 Self::RegisterSpool,
287 Self::LoadSpool,
288 Self::UnloadSpool,
289 Self::AdjustSpool,
290 Self::RetireSpool,
291 ];
292
293 #[must_use]
295 pub const fn action_kind(self) -> ActionKind {
296 match self {
297 Self::RegisterSpool => ActionKind::RegisterSpool,
298 Self::LoadSpool => ActionKind::LoadSpool,
299 Self::UnloadSpool => ActionKind::UnloadSpool,
300 Self::AdjustSpool => ActionKind::AdjustSpool,
301 Self::RetireSpool => ActionKind::RetireSpool,
302 }
303 }
304}
305
306#[derive(Debug, Clone, Copy, PartialEq, Eq)]
308pub struct Operation {
309 pub name: &'static str,
312 pub method: Method,
314 pub path: &'static str,
316 pub effect: Effect,
318 pub accepts: Option<&'static str>,
320 pub answers: &'static str,
322 pub query: &'static [Declared],
324 pub body: &'static [Declared],
329 pub image_path_field: Option<&'static str>,
338 pub printer_wide: Option<&'static Operation>,
347}
348
349impl Operation {
350 #[must_use]
352 pub fn full_path(&self) -> String {
353 format!("{VERSION_PREFIX}{}", self.path)
354 }
355
356 #[must_use]
358 pub const fn action_kind(&self) -> Option<ActionKind> {
359 match self.effect {
360 Effect::Mutating(kind) => Some(kind),
361 _ => None,
362 }
363 }
364
365 #[must_use]
367 pub const fn command_kind(&self) -> Option<ActionKind> {
368 match self.effect {
369 Effect::Command(kind) => Some(kind.action_kind()),
370 _ => None,
371 }
372 }
373
374 #[must_use]
377 pub const fn granted_as(&self) -> Option<ActionKind> {
378 match self.effect {
379 Effect::Mutating(kind) => Some(kind),
380 Effect::Command(kind) => Some(kind.action_kind()),
381 Effect::Read | Effect::Write | Effect::Recovery(_) => None,
382 }
383 }
384
385 #[must_use]
388 pub const fn recovery_kind(&self) -> Option<RecoveryActionKind> {
389 match self.effect {
390 Effect::Recovery(kind) => Some(kind),
391 _ => None,
392 }
393 }
394
395 #[must_use]
402 pub const fn is_mutating(&self) -> bool {
403 matches!(
404 self.effect,
405 Effect::Mutating(_) | Effect::Command(_) | Effect::Recovery(_) | Effect::Write
406 )
407 }
408
409 #[must_use]
424 pub fn request(&self) -> Vec<Parameter> {
425 let mut found = path_parameters(self.path);
426 found.extend(declared(self.query, Located::Query));
427 match Vocabulary::of(self.effect) {
428 Some((vocabulary, kind)) => {
429 let routed: Vec<String> = found.iter().map(|path| path.name.clone()).collect();
430 found.extend(
431 action_parameters(vocabulary, &kind)
432 .into_iter()
433 .filter(|field| !routed.contains(&field.name)),
434 );
435 }
436 None => found.extend(declared(self.body, Located::Body)),
437 }
438 found
439 }
440
441 #[must_use]
459 pub fn request_shapes(&self) -> Vec<(Parameter, Value)> {
460 let action = match Vocabulary::of(self.effect) {
461 Some((vocabulary, kind)) => action_shapes(vocabulary, &kind),
462 None => Vec::new(),
463 };
464 self.request()
465 .into_iter()
466 .map(|parameter| {
467 let shape = match parameter.located {
468 Located::Path => json!({ "type": "string" }),
471 Located::Query => declared_shape(self.query, ¶meter.name),
472 Located::Body if action.is_empty() => {
473 declared_shape(self.body, ¶meter.name)
474 }
475 Located::Body => action
476 .iter()
477 .find(|(name, _)| *name == parameter.name)
478 .map_or_else(
479 || {
480 panic!(
481 "`{}` takes `{}` in its body, and the action it names \
482 declares no such field",
483 self.name, parameter.name
484 )
485 },
486 |(_, shape)| shape.clone(),
487 ),
488 };
489 (parameter, shape)
490 })
491 .collect()
492 }
493
494 #[must_use]
501 pub const fn answers_with(&self) -> &'static [Answer] {
502 match self.effect {
503 Effect::Mutating(_) | Effect::Command(_) | Effect::Recovery(_) => {
504 &[Answer::Success, Answer::Rejected]
505 }
506 Effect::Read | Effect::Write => &[Answer::Success],
507 }
508 }
509
510 #[must_use]
521 pub fn response_schema(&self, answer: Answer) -> Value {
522 use printobserver_types::schemars::schema_for;
523 debug_assert!(
524 self.answers_with().contains(&answer),
525 "`{}` produces no {answer} answer",
526 self.name
527 );
528 let schema = match (self.name, self.effect) {
529 (_, Effect::Mutating(_)) => schema_for!(crate::wire::ActionAnswer),
530 (_, Effect::Command(_)) => schema_for!(crate::wire::SpoolCommandAnswer),
531 (_, Effect::Recovery(_)) => schema_for!(crate::wire::RecoveryAnswer),
532 (RECOVERY_STATUS, _) => schema_for!(crate::wire::RecoveryStatusAnswer),
533 ("spools", _) => schema_for!(crate::wire::SpoolsAnswer),
534 ("spool", _) => schema_for!(crate::wire::SpoolAnswer),
535 ("printer_history", _) => schema_for!(crate::wire::TimelineAnswer),
536 ("preflight", _) => schema_for!(crate::wire::PreflightAnswer),
537 ("prints", _) => schema_for!(crate::wire::PrintsAnswer),
538 ("status", _) => schema_for!(crate::wire::StatusAnswer),
539 ("context", _) => schema_for!(crate::wire::ContextAnswer),
540 ("image", _) => schema_for!(crate::wire::ImageAnswer),
541 ("history", _) => schema_for!(crate::wire::HistoryAnswer),
542 ("events", _) => schema_for!(crate::wire::EventsAnswer),
543 ("look" | "printer_look", _) => schema_for!(crate::wire::LookAnswer),
544 ("manifest_get" | "manifest_set", _) => schema_for!(crate::wire::ManifestAnswer),
545 (name, _) => panic!("the operation `{name}` has no declared answer shape"),
546 };
547 schema.to_value()
548 }
549}
550
551fn declared(entries: &'static [Declared], located: Located) -> impl Iterator<Item = Parameter> {
553 entries.iter().map(move |entry| Parameter {
554 name: entry.name.to_owned(),
555 required: entry.required,
556 located,
557 kind: entry.kind,
558 repeated: entry.repeated,
559 })
560}
561
562fn declared_shape(entries: &'static [Declared], name: &str) -> Value {
568 let Some(entry) = entries.iter().find(|entry| entry.name == name) else {
569 return json!({ "type": "string" });
570 };
571 let one = if let Some(shape) = entry.shape {
572 json!({ "$ref": format!("#/$defs/{shape}") })
573 } else {
574 match entry.kind {
575 ValueKind::Text => json!({ "type": "string" }),
576 ValueKind::Number => json!({ "type": "number" }),
577 ValueKind::Integer => json!({ "type": "integer" }),
578 ValueKind::Boolean => json!({ "type": "boolean" }),
579 ValueKind::Structured => json!({ "type": "object" }),
580 }
581 };
582 if entry.repeated {
585 json!({ "type": "array", "items": one })
586 } else {
587 one
588 }
589}
590
591#[derive(Debug, Clone, Copy, PartialEq, Eq)]
594enum Vocabulary {
595 Actions,
597 Commands,
599 Recovery,
602}
603
604impl Vocabulary {
605 fn of(effect: Effect) -> Option<(Self, String)> {
607 let tag = |kind: ActionKind| {
608 printobserver_types::serde_json::to_value(kind)
609 .ok()
610 .and_then(|value| value.as_str().map(str::to_owned))
611 .unwrap_or_else(|| panic!("`{kind:?}` renders as the tag it is spelled by"))
612 };
613 match effect {
614 Effect::Mutating(kind) => Some((Self::Actions, tag(kind))),
615 Effect::Command(kind) => Some((Self::Commands, tag(kind.action_kind()))),
616 Effect::Recovery(kind) => Some((Self::Recovery, kind.as_str().to_owned())),
617 Effect::Read | Effect::Write => None,
618 }
619 }
620
621 const fn tag(self) -> &'static str {
623 match self {
624 Self::Actions | Self::Recovery => ACTION_TAG,
625 Self::Commands => COMMAND_TAG,
626 }
627 }
628
629 fn schema(self) -> Value {
635 use printobserver_types::schemars::schema_for;
636 match self {
637 Self::Actions => schema_for!(PrintAction).to_value(),
638 Self::Commands => schema_for!(SpoolCommand).to_value(),
639 Self::Recovery => recovery_request_schema(),
640 }
641 }
642}
643
644fn recovery_request_schema() -> Value {
647 use printobserver_types::schemars::schema_for;
648 let mut schema = schema_for!(RecoveryAction).to_value();
649 let actor = schema_for!(printobserver_core::Actor).to_value();
650 if let Some(variants) = schema.get_mut("oneOf").and_then(Value::as_array_mut) {
651 for variant in variants {
652 if let Some(properties) = variant.get_mut("properties").and_then(Value::as_object_mut) {
653 properties.insert(
654 "actor".to_owned(),
655 json!({ "$ref": "#/$defs/Actor", "description": "Who is asking." }),
656 );
657 properties.insert(
658 "reason".to_owned(),
659 json!({ "type": "string", "description": "Why the actor is asking for this." }),
660 );
661 }
662 if let Some(required) = variant.get_mut("required").and_then(Value::as_array_mut) {
663 required.push(json!("actor"));
664 required.push(json!("reason"));
665 }
666 }
667 }
668 let defs = schema
669 .as_object_mut()
670 .map(|top| top.entry("$defs").or_insert_with(|| json!({})));
671 if let Some(Value::Object(defs)) = defs {
672 if let Some(Value::Object(nested)) = actor.get("$defs") {
673 for (name, shape) in nested {
674 defs.insert(name.clone(), shape.clone());
675 }
676 }
677 let mut own = actor.clone();
678 if let Some(top) = own.as_object_mut() {
679 top.remove("$defs");
680 top.remove("$schema");
681 }
682 defs.insert("Actor".to_owned(), own);
683 }
684 schema
685}
686
687fn action_shapes(vocabulary: Vocabulary, kind: &str) -> Vec<(String, Value)> {
698 let schema = vocabulary.schema();
699 let variant = action_variant(&schema, vocabulary, kind);
700 variant
701 .get("properties")
702 .and_then(Value::as_object)
703 .unwrap_or_else(|| panic!("the action `{kind}` declares no properties"))
704 .iter()
705 .filter(|(name, _)| name.as_str() != vocabulary.tag())
706 .map(|(name, field)| (name.clone(), field.clone()))
707 .collect()
708}
709
710fn action_variant(schema: &Value, vocabulary: Vocabulary, tag: &str) -> Value {
717 schema
718 .get("oneOf")
719 .and_then(Value::as_array)
720 .and_then(|variants| {
721 variants.iter().find(|variant| {
722 variant.pointer(&format!("/properties/{}/const", vocabulary.tag()))
723 == Some(&json!(tag))
724 })
725 })
726 .cloned()
727 .unwrap_or_else(|| panic!("the contracts declare no action tagged `{tag}`"))
728}
729
730fn path_parameters(path: &str) -> Vec<Parameter> {
732 path.split('/')
733 .filter_map(|segment| segment.strip_prefix('{')?.strip_suffix('}'))
734 .map(|name| Parameter {
735 name: name.to_owned(),
736 required: true,
739 located: Located::Path,
740 kind: ValueKind::Text,
743 repeated: false,
744 })
745 .collect()
746}
747
748fn action_parameters(vocabulary: Vocabulary, kind: &str) -> Vec<Parameter> {
755 let schema = vocabulary.schema();
756 let variant = action_variant(&schema, vocabulary, kind);
757 let required: Vec<&str> = variant
758 .get("required")
759 .and_then(Value::as_array)
760 .map(|names| names.iter().filter_map(Value::as_str).collect())
761 .unwrap_or_default();
762 let properties = variant
763 .get("properties")
764 .and_then(Value::as_object)
765 .unwrap_or_else(|| panic!("the action `{kind}` declares no properties"));
766 properties
767 .iter()
768 .filter(|(name, _)| name.as_str() != vocabulary.tag())
769 .map(|(name, field)| Parameter {
770 name: name.clone(),
771 required: required.contains(&name.as_str()),
772 located: Located::Body,
773 kind: kind_of(&resolve(&schema, field)),
774 repeated: false,
775 })
776 .collect()
777}
778
779fn resolve(schema: &Value, field: &Value) -> Value {
781 let Some(reference) = field.get("$ref").and_then(Value::as_str) else {
782 return field.clone();
783 };
784 reference
785 .strip_prefix("#/")
786 .and_then(|rest| schema.pointer(&format!("/{rest}")))
787 .cloned()
788 .unwrap_or_else(|| field.clone())
789}
790
791fn kind_of(shape: &Value) -> ValueKind {
799 if let Some(declared) = shape.get("type") {
800 let named = |name: &str| match declared {
801 Value::String(one) => one == name,
802 Value::Array(many) => many.iter().any(|one| one == name),
803 _ => false,
804 };
805 if named("object") || named("array") {
806 return ValueKind::Structured;
807 }
808 if named("string") {
809 return ValueKind::Text;
810 }
811 if named("integer") {
812 return ValueKind::Integer;
813 }
814 if named("number") {
815 return ValueKind::Number;
816 }
817 if named("boolean") {
818 return ValueKind::Boolean;
819 }
820 }
821 match shape.get("oneOf").or_else(|| shape.get("anyOf")) {
822 Some(Value::Array(branches)) if !branches.is_empty() => {
823 let kinds: Vec<ValueKind> = branches
824 .iter()
825 .map(|branch| match branch.get("const") {
826 Some(Value::String(_)) => ValueKind::Text,
827 _ => kind_of(branch),
828 })
829 .collect();
830 let first = kinds[0];
831 if kinds.iter().all(|kind| *kind == first) {
832 first
833 } else {
834 ValueKind::Structured
835 }
836 }
837 _ => ValueKind::Structured,
838 }
839}
840
841const fn action(name: &'static str, path: &'static str, kind: ActionKind) -> Operation {
843 Operation {
844 name,
845 method: Method::Post,
846 path,
847 effect: Effect::Mutating(kind),
848 accepts: Some(MEDIA_TYPE),
849 answers: MEDIA_TYPE,
850 query: &[],
851 body: &[],
852 image_path_field: None,
853 printer_wide: None,
854 }
855}
856
857const fn command(name: &'static str, path: &'static str, kind: SpoolCommandKind) -> Operation {
859 Operation {
860 effect: Effect::Command(kind),
861 ..action(name, path, kind.action_kind())
862 }
863}
864
865const fn recovery(name: &'static str, path: &'static str, kind: RecoveryActionKind) -> Operation {
867 Operation {
868 name,
869 method: Method::Post,
870 path,
871 effect: Effect::Recovery(kind),
872 accepts: Some(MEDIA_TYPE),
873 answers: MEDIA_TYPE,
874 query: &[],
875 body: &[],
876 image_path_field: None,
877 printer_wide: None,
878 }
879}
880
881const fn read(name: &'static str, path: &'static str) -> Operation {
883 Operation {
884 name,
885 method: Method::Get,
886 path,
887 effect: Effect::Read,
888 accepts: None,
889 answers: MEDIA_TYPE,
890 query: &[],
891 body: &[],
892 image_path_field: None,
893 printer_wide: None,
894 }
895}
896
897#[must_use]
904pub fn command_for(operation: &str) -> String {
905 operation.replace('_', "-")
906}
907
908pub const OPERATIONS: [Operation; 38] = [
910 read("prints", "/prints"),
914 read("status", "/prints/{print_id}/status"),
915 Operation {
916 image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
917 ..read("context", "/prints/{print_id}/context")
918 },
919 Operation {
920 image_path_field: Some(IMAGE_PATH_FIELD),
921 ..read("image", "/images/{image_id}")
922 },
923 Operation {
924 query: &[Declared::once("limit", false, ValueKind::Integer)],
925 ..read("history", "/prints/{print_id}/history")
926 },
927 Operation {
931 query: &[
932 Declared::once("after", false, ValueKind::Text),
933 Declared::once("print_id", false, ValueKind::Text),
934 Declared {
935 repeated: true,
936 ..Declared::once("kinds", false, ValueKind::Text)
937 },
938 Declared {
939 repeated: true,
940 ..Declared::once("exclude_kinds", false, ValueKind::Text)
941 },
942 Declared::once("wait_s", false, ValueKind::Integer),
943 Declared::once("limit", false, ValueKind::Integer),
944 ],
945 ..read("events", "/events")
946 },
947 read("manifest_get", "/prints/{print_id}/manifest"),
948 Operation {
953 query: &[Declared::once("wait_s", false, ValueKind::Integer)],
954 image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
955 printer_wide: Some(&PRINTER_LOOK_OPERATION),
956 ..read("look", "/prints/{print_id}/look")
957 },
958 PRINTER_LOOK_OPERATION,
959 Operation {
960 name: "manifest_set",
961 method: Method::Put,
962 path: "/prints/{print_id}/manifest",
963 effect: Effect::Write,
964 accepts: Some(MEDIA_TYPE),
965 answers: MEDIA_TYPE,
966 query: &[],
967 body: &[
968 Declared::once("reason", true, ValueKind::Text),
969 Declared {
970 shape: Some("JobManifest"),
971 ..Declared::once("manifest", true, ValueKind::Structured)
972 },
973 ],
974 image_path_field: None,
975 printer_wide: None,
976 },
977 Operation {
981 query: &[Declared::once("include_retired", false, ValueKind::Boolean)],
982 ..read("spools", "/spools")
983 },
984 read("spool", "/spools/{spool_id}"),
985 Operation {
989 query: &[
990 Declared {
991 repeated: true,
992 ..Declared::once("kinds", false, ValueKind::Text)
993 },
994 Declared::once("since", false, ValueKind::Text),
995 Declared::once("until", false, ValueKind::Text),
996 Declared::once("spool_id", false, ValueKind::Text),
997 Declared::once("before", false, ValueKind::Text),
998 Declared::once("limit", false, ValueKind::Integer),
999 ],
1000 ..read("printer_history", "/history")
1001 },
1002 Operation {
1005 query: &[Declared::once("file_name", true, ValueKind::Text)],
1006 ..read("preflight", "/preflight")
1007 },
1008 action(
1009 "pause",
1010 "/prints/{print_id}/actions/pause",
1011 ActionKind::Pause,
1012 ),
1013 action(
1014 "resume",
1015 "/prints/{print_id}/actions/resume",
1016 ActionKind::Resume,
1017 ),
1018 action(
1019 "cancel",
1020 "/prints/{print_id}/actions/cancel",
1021 ActionKind::Cancel,
1022 ),
1023 action(
1024 "start_print",
1025 "/prints/{print_id}/actions/start_print",
1026 ActionKind::StartPrint,
1027 ),
1028 action(
1029 "set_feedrate_factor",
1030 "/prints/{print_id}/actions/set_feedrate_factor",
1031 ActionKind::SetFeedrateFactor,
1032 ),
1033 action(
1034 "set_flowrate_factor",
1035 "/prints/{print_id}/actions/set_flowrate_factor",
1036 ActionKind::SetFlowrateFactor,
1037 ),
1038 action(
1039 "set_tool_target_c",
1040 "/prints/{print_id}/actions/set_tool_target_c",
1041 ActionKind::SetToolTargetC,
1042 ),
1043 action(
1044 "set_bed_target_c",
1045 "/prints/{print_id}/actions/set_bed_target_c",
1046 ActionKind::SetBedTargetC,
1047 ),
1048 action(
1049 "set_fan_percent",
1050 "/prints/{print_id}/actions/set_fan_percent",
1051 ActionKind::SetFanPercent,
1052 ),
1053 action(
1054 "acknowledge_failure",
1055 "/prints/{print_id}/actions/acknowledge_failure",
1056 ActionKind::AcknowledgeFailure,
1057 ),
1058 action(
1060 "close_print",
1061 "/prints/{print_id}/actions/close_print",
1062 ActionKind::ClosePrint,
1063 ),
1064 command(
1065 "register_spool",
1066 "/spools/actions/register_spool",
1067 SpoolCommandKind::RegisterSpool,
1068 ),
1069 command(
1070 "load_spool",
1071 "/spools/{spool_id}/actions/load_spool",
1072 SpoolCommandKind::LoadSpool,
1073 ),
1074 command(
1075 "unload_spool",
1076 "/spools/{spool_id}/actions/unload_spool",
1077 SpoolCommandKind::UnloadSpool,
1078 ),
1079 command(
1080 "adjust_spool",
1081 "/spools/{spool_id}/actions/adjust_spool",
1082 SpoolCommandKind::AdjustSpool,
1083 ),
1084 command(
1085 "retire_spool",
1086 "/spools/{spool_id}/actions/retire_spool",
1087 SpoolCommandKind::RetireSpool,
1088 ),
1089 read(RECOVERY_STATUS, "/printer/recovery"),
1092 recovery(
1093 "recover_lift",
1094 "/printer/recovery/recover_lift",
1095 RecoveryActionKind::RecoverLift,
1096 ),
1097 recovery(
1098 "recover_cool",
1099 "/printer/recovery/recover_cool",
1100 RecoveryActionKind::RecoverCool,
1101 ),
1102 recovery(
1103 "recover_fan",
1104 "/printer/recovery/recover_fan",
1105 RecoveryActionKind::RecoverFan,
1106 ),
1107 recovery(
1108 "recover_heat",
1109 "/printer/recovery/recover_heat",
1110 RecoveryActionKind::RecoverHeat,
1111 ),
1112 recovery(
1113 "recover_park",
1114 "/printer/recovery/recover_park",
1115 RecoveryActionKind::RecoverPark,
1116 ),
1117 recovery(
1118 "recover_home_xy",
1119 "/printer/recovery/recover_home_xy",
1120 RecoveryActionKind::RecoverHomeXy,
1121 ),
1122 recovery(
1123 "recover_home_z",
1124 "/printer/recovery/recover_home_z",
1125 RecoveryActionKind::RecoverHomeZ,
1126 ),
1127];
1128
1129pub const RECOVERY_STATUS: &str = "recover_status";
1132
1133pub const BESIDE_THE_ACTIONS: [&str; 14] = [
1142 "prints",
1143 "status",
1144 "context",
1145 "image",
1146 "history",
1147 "events",
1148 "manifest_get",
1149 "look",
1150 PRINTER_LOOK,
1151 "manifest_set",
1152 "spools",
1153 "spool",
1154 "printer_history",
1155 "preflight",
1156];
1157
1158pub const PRINTER_LOOK: &str = "printer_look";
1161
1162const PRINTER_LOOK_OPERATION: Operation = Operation {
1169 query: &[Declared::once("wait_s", false, ValueKind::Integer)],
1170 image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
1171 ..read(PRINTER_LOOK, "/look")
1172};
1173
1174#[must_use]
1177pub fn printer_wide_of(name: &str) -> Option<&'static Operation> {
1178 OPERATIONS
1179 .iter()
1180 .find(|declared| declared.printer_wide.is_some_and(|wide| wide.name == name))
1181}
1182
1183#[must_use]
1185pub fn operation(name: &str) -> Option<&'static Operation> {
1186 OPERATIONS.iter().find(|declared| declared.name == name)
1187}
1188
1189#[cfg(test)]
1190mod tests {
1191 use printobserver_core::ActionKind;
1192
1193 use super::{Effect, MEDIA_TYPE, Method, OPERATIONS, VERSION_PREFIX, operation};
1194
1195 #[test]
1197 fn every_method_is_spelled_as_the_wire_spells_it() {
1198 for (method, spelling) in [
1199 (Method::Get, "GET"),
1200 (Method::Post, "POST"),
1201 (Method::Put, "PUT"),
1202 ] {
1203 assert_eq!(method.as_str(), spelling);
1204 assert_eq!(method.to_string(), spelling);
1205 }
1206 }
1207
1208 #[test]
1210 fn every_operation_sits_beneath_the_one_versioned_prefix() {
1211 for declared in OPERATIONS {
1212 let whole = declared.full_path();
1213 assert!(
1214 whole.starts_with(VERSION_PREFIX),
1215 "`{}` is served at {whole}",
1216 declared.name
1217 );
1218 assert_eq!(declared.answers, MEDIA_TYPE);
1219 }
1220 }
1221
1222 #[test]
1224 fn a_mutating_operation_names_its_action_and_a_read_names_none() {
1225 for declared in OPERATIONS {
1226 match declared.effect {
1227 Effect::Mutating(kind) => {
1228 assert_eq!(declared.action_kind(), Some(kind));
1229 assert_eq!(declared.command_kind(), None);
1230 assert_eq!(declared.granted_as(), Some(kind));
1231 assert!(declared.is_mutating());
1232 }
1233 Effect::Command(kind) => {
1234 assert_eq!(declared.action_kind(), None);
1235 assert_eq!(declared.command_kind(), Some(kind.action_kind()));
1236 assert_eq!(declared.granted_as(), Some(kind.action_kind()));
1237 assert!(declared.is_mutating());
1238 }
1239 Effect::Recovery(kind) => {
1240 assert_eq!(declared.action_kind(), None);
1241 assert_eq!(declared.granted_as(), None);
1242 assert_eq!(declared.recovery_kind(), Some(kind));
1243 assert!(declared.is_mutating());
1244 }
1245 Effect::Write => {
1246 assert_eq!(declared.action_kind(), None);
1247 assert!(
1248 declared.is_mutating(),
1249 "`{}` writes a record and is not held to the reason every \
1250 change carries",
1251 declared.name
1252 );
1253 }
1254 Effect::Read => {
1255 assert_eq!(declared.action_kind(), None);
1256 assert!(!declared.is_mutating());
1257 }
1258 }
1259 }
1260 }
1261
1262 #[test]
1267 fn a_mutating_operation_takes_a_body_and_a_read_takes_none() {
1268 let mutating = super::action(
1269 "pause",
1270 "/prints/{print_id}/actions/pause",
1271 ActionKind::Pause,
1272 );
1273 assert_eq!(mutating.method, Method::Post);
1274 assert_eq!(mutating.accepts, Some(MEDIA_TYPE));
1275 assert_eq!(mutating.answers, MEDIA_TYPE);
1276 assert_eq!(mutating.action_kind(), Some(ActionKind::Pause));
1277
1278 let reading = super::read("status", "/prints/{print_id}/status");
1279 assert_eq!(reading.method, Method::Get);
1280 assert_eq!(reading.accepts, None);
1281 assert_eq!(reading.answers, MEDIA_TYPE);
1282 assert_eq!(reading.effect, Effect::Read);
1283 }
1284
1285 #[test]
1288 fn a_spool_commands_body_is_its_fields_less_the_tag_and_the_routed_spool() {
1289 let load = operation("load_spool").expect("the load is served");
1290 let names: Vec<(String, super::Located)> = load
1291 .request()
1292 .into_iter()
1293 .map(|parameter| (parameter.name, parameter.located))
1294 .collect();
1295 assert_eq!(
1296 names,
1297 vec![
1298 ("spool_id".to_owned(), super::Located::Path),
1299 ("actor".to_owned(), super::Located::Body),
1300 ("reason".to_owned(), super::Located::Body),
1301 ("tool".to_owned(), super::Located::Body),
1302 ]
1303 );
1304 let register = operation("register_spool").expect("the registration is served");
1305 assert!(
1306 register
1307 .request()
1308 .iter()
1309 .all(|parameter| parameter.name != super::COMMAND_TAG
1310 && parameter.located == super::Located::Body)
1311 );
1312 }
1313
1314 #[test]
1318 fn the_ledgers_kinds_are_the_commands_the_contracts_declare() {
1319 let schema = super::Vocabulary::Commands.schema();
1320 let declared: Vec<String> = schema["oneOf"]
1321 .as_array()
1322 .expect("the spool vocabulary is a union")
1323 .iter()
1324 .filter_map(|variant| variant.pointer("/properties/command/const"))
1325 .filter_map(|tag| tag.as_str().map(str::to_owned))
1326 .collect();
1327 let kinds: Vec<String> = super::SpoolCommandKind::ALL
1328 .iter()
1329 .map(|kind| {
1330 printobserver_types::serde_json::to_value(kind.action_kind())
1331 .ok()
1332 .and_then(|tag| tag.as_str().map(str::to_owned))
1333 .expect("an action kind renders as its tag")
1334 })
1335 .collect();
1336 assert_eq!(kinds, declared);
1337 let served: Vec<super::SpoolCommandKind> = OPERATIONS
1338 .iter()
1339 .filter_map(|operation| match operation.effect {
1340 Effect::Command(kind) => Some(kind),
1341 _ => None,
1342 })
1343 .collect();
1344 assert_eq!(served, super::SpoolCommandKind::ALL.to_vec());
1345 }
1346
1347 #[test]
1349 fn a_repeated_value_is_described_as_a_list_of_its_kind() {
1350 let history = operation("printer_history").expect("the printer history is served");
1351 let kinds = history
1352 .request_shapes()
1353 .into_iter()
1354 .find(|(parameter, _)| parameter.name == "kinds")
1355 .expect("the history takes kinds");
1356 assert!(kinds.0.repeated);
1357 assert_eq!(
1358 kinds.1,
1359 printobserver_types::serde_json::json!({"type": "array", "items": {"type": "string"}})
1360 );
1361 }
1362
1363 #[test]
1366 fn a_recovery_actions_body_is_its_fields_beside_the_actor_and_the_reason() {
1367 let heat = operation("recover_heat").expect("the heat is served");
1368 let names: Vec<(String, bool, super::Located)> = heat
1369 .request()
1370 .into_iter()
1371 .map(|parameter| (parameter.name, parameter.required, parameter.located))
1372 .collect();
1373 assert_eq!(
1374 names,
1375 vec![
1376 ("actor".to_owned(), true, super::Located::Body),
1377 ("clearance_asserted".to_owned(), false, super::Located::Body),
1378 ("reason".to_owned(), true, super::Located::Body),
1379 ("target_c".to_owned(), true, super::Located::Body),
1380 ("tool".to_owned(), true, super::Located::Body),
1381 ]
1382 );
1383 let cool = operation("recover_cool").expect("the cool is served");
1384 let names: Vec<String> = cool
1385 .request()
1386 .into_iter()
1387 .map(|parameter| parameter.name)
1388 .collect();
1389 assert_eq!(names, vec!["actor".to_owned(), "reason".to_owned()]);
1390 let served: Vec<super::RecoveryActionKind> = OPERATIONS
1391 .iter()
1392 .filter_map(super::Operation::recovery_kind)
1393 .collect();
1394 assert_eq!(served, super::RecoveryActionKind::ALL.to_vec());
1395 }
1396
1397 #[test]
1401 fn a_printer_wide_form_takes_its_prints_values_less_the_print() {
1402 let mut forms = 0;
1403 for declared in OPERATIONS {
1404 let Some(wide) = declared.printer_wide else {
1405 continue;
1406 };
1407 forms += 1;
1408 assert_eq!(
1409 operation(wide.name),
1410 Some(wide),
1411 "the printer-wide form is not an operation this server serves"
1412 );
1413 assert_eq!(wide.method, declared.method, "`{}`", declared.name);
1414 assert_eq!(wide.effect, declared.effect, "`{}`", declared.name);
1415 assert_eq!(wide.image_path_field, declared.image_path_field);
1416 assert_eq!(
1417 wide.printer_wide, None,
1418 "a printer-wide form has none of its own"
1419 );
1420 assert!(!wide.path.contains("{print_id}"), "`{}`", wide.name);
1421 let taken: Vec<super::Parameter> = declared
1422 .request()
1423 .into_iter()
1424 .filter(|parameter| parameter.name != "print_id")
1425 .collect();
1426 assert_eq!(wide.request(), taken, "`{}`", wide.name);
1427 assert_eq!(
1428 super::printer_wide_of(wide.name).map(|found| found.name),
1429 Some(declared.name)
1430 );
1431 }
1432 assert_eq!(
1433 forms, 1,
1434 "the look is the one read with a printer-wide form"
1435 );
1436 assert!(super::printer_wide_of("look").is_none());
1437 }
1438
1439 #[test]
1441 fn an_operation_this_server_does_not_serve_is_answered_as_none() {
1442 assert_eq!(operation("pause").map(|found| found.name), Some("pause"));
1443 assert!(operation("reboot").is_none());
1444 }
1445}