1use printobserver_types::serde_json::{Value, json};
64
65pub use printobserver_core::{
70 ActionKind, PrintAction, RecoveryAction, RecoveryActionKind, SpoolCommand,
71};
72
73pub const VERSION_PREFIX: &str = "/v1";
75
76pub const MEDIA_TYPE: &str = "application/json";
78
79pub const INGRESS_PATH: &str = "/obico/webhook";
82
83pub const CONTEXT_IMAGE_PATH_FIELD: &str = "image_path";
85
86pub const IMAGE_PATH_FIELD: &str = "path";
88
89const ACTION_TAG: &str = "action";
92
93pub const COMMAND_TAG: &str = "command";
96
97#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
99pub enum Method {
100 Get,
102 Post,
104 Put,
106}
107
108impl Method {
109 #[must_use]
111 pub const fn as_str(self) -> &'static str {
112 match self {
113 Self::Get => "GET",
114 Self::Post => "POST",
115 Self::Put => "PUT",
116 }
117 }
118}
119
120impl core::fmt::Display for Method {
121 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
122 formatter.write_str(self.as_str())
123 }
124}
125
126#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
128pub enum Located {
129 Path,
131 Query,
133 Body,
135}
136
137#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
144pub enum ValueKind {
145 Text,
147 Number,
149 Integer,
151 Boolean,
153 Structured,
155}
156
157impl ValueKind {
158 #[must_use]
160 pub const fn structured(self) -> bool {
161 matches!(self, Self::Structured)
162 }
163}
164
165#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
171pub struct Declared {
172 pub name: &'static str,
174 pub required: bool,
176 pub kind: ValueKind,
178 pub shape: Option<&'static str>,
185 pub repeated: bool,
188}
189
190impl Declared {
191 #[must_use]
193 pub const fn once(name: &'static str, required: bool, kind: ValueKind) -> Self {
194 Self {
195 name,
196 required,
197 kind,
198 shape: None,
199 repeated: false,
200 }
201 }
202}
203
204#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
206pub struct Parameter {
207 pub name: String,
209 pub required: bool,
211 pub located: Located,
213 pub kind: ValueKind,
215 pub repeated: bool,
217}
218
219#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
221pub enum Answer {
222 Success,
224 Rejected,
226}
227
228impl Answer {
229 #[must_use]
231 pub const fn as_str(self) -> &'static str {
232 match self {
233 Self::Success => "success",
234 Self::Rejected => "rejected",
235 }
236 }
237}
238
239impl core::fmt::Display for Answer {
240 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
241 formatter.write_str(self.as_str())
242 }
243}
244
245#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
247pub enum Effect {
248 Read,
250 Mutating(ActionKind),
252 Command(SpoolCommandKind),
256 Recovery(RecoveryActionKind),
260 Write,
262}
263
264#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
271pub enum SpoolCommandKind {
272 RegisterSpool,
274 LoadSpool,
276 UnloadSpool,
278 AdjustSpool,
280 RetireSpool,
282}
283
284impl SpoolCommandKind {
285 pub const ALL: [Self; 5] = [
287 Self::RegisterSpool,
288 Self::LoadSpool,
289 Self::UnloadSpool,
290 Self::AdjustSpool,
291 Self::RetireSpool,
292 ];
293
294 #[must_use]
296 pub const fn action_kind(self) -> ActionKind {
297 match self {
298 Self::RegisterSpool => ActionKind::RegisterSpool,
299 Self::LoadSpool => ActionKind::LoadSpool,
300 Self::UnloadSpool => ActionKind::UnloadSpool,
301 Self::AdjustSpool => ActionKind::AdjustSpool,
302 Self::RetireSpool => ActionKind::RetireSpool,
303 }
304 }
305}
306
307#[derive(Debug, Clone, Copy, PartialEq, Eq)]
309pub struct Operation {
310 pub name: &'static str,
313 pub method: Method,
315 pub path: &'static str,
317 pub effect: Effect,
319 pub accepts: Option<&'static str>,
321 pub answers: &'static str,
323 pub query: &'static [Declared],
325 pub body: &'static [Declared],
330 pub image_path_field: Option<&'static str>,
339 pub printer_wide: Option<&'static Operation>,
348 pub mints_print: bool,
356}
357
358impl Operation {
359 #[must_use]
361 pub fn full_path(&self) -> String {
362 format!("{VERSION_PREFIX}{}", self.path)
363 }
364
365 #[must_use]
367 pub const fn action_kind(&self) -> Option<ActionKind> {
368 match self.effect {
369 Effect::Mutating(kind) => Some(kind),
370 _ => None,
371 }
372 }
373
374 #[must_use]
376 pub const fn command_kind(&self) -> Option<ActionKind> {
377 match self.effect {
378 Effect::Command(kind) => Some(kind.action_kind()),
379 _ => None,
380 }
381 }
382
383 #[must_use]
386 pub const fn granted_as(&self) -> Option<ActionKind> {
387 match self.effect {
388 Effect::Mutating(kind) => Some(kind),
389 Effect::Command(kind) => Some(kind.action_kind()),
390 Effect::Read | Effect::Write | Effect::Recovery(_) => None,
391 }
392 }
393
394 #[must_use]
397 pub const fn recovery_kind(&self) -> Option<RecoveryActionKind> {
398 match self.effect {
399 Effect::Recovery(kind) => Some(kind),
400 _ => None,
401 }
402 }
403
404 #[must_use]
411 pub const fn is_mutating(&self) -> bool {
412 matches!(
413 self.effect,
414 Effect::Mutating(_) | Effect::Command(_) | Effect::Recovery(_) | Effect::Write
415 )
416 }
417
418 #[must_use]
433 pub fn request(&self) -> Vec<Parameter> {
434 let mut found = path_parameters(self.path);
435 found.extend(declared(self.query, Located::Query));
436 match Vocabulary::of(self.effect) {
437 Some((vocabulary, kind)) => {
438 let routed: Vec<String> = found.iter().map(|path| path.name.clone()).collect();
439 found.extend(
440 action_parameters(vocabulary, &kind)
441 .into_iter()
442 .filter(|field| !routed.contains(&field.name)),
443 );
444 }
445 None => found.extend(declared(self.body, Located::Body)),
446 }
447 found
448 }
449
450 #[must_use]
468 pub fn request_shapes(&self) -> Vec<(Parameter, Value)> {
469 let action = match Vocabulary::of(self.effect) {
470 Some((vocabulary, kind)) => action_shapes(vocabulary, &kind),
471 None => Vec::new(),
472 };
473 self.request()
474 .into_iter()
475 .map(|parameter| {
476 let shape = match parameter.located {
477 Located::Path => json!({ "type": "string" }),
480 Located::Query => declared_shape(self.query, ¶meter.name),
481 Located::Body if action.is_empty() => {
482 declared_shape(self.body, ¶meter.name)
483 }
484 Located::Body => action
485 .iter()
486 .find(|(name, _)| *name == parameter.name)
487 .map_or_else(
488 || {
489 panic!(
490 "`{}` takes `{}` in its body, and the action it names \
491 declares no such field",
492 self.name, parameter.name
493 )
494 },
495 |(_, shape)| shape.clone(),
496 ),
497 };
498 (parameter, shape)
499 })
500 .collect()
501 }
502
503 #[must_use]
510 pub const fn answers_with(&self) -> &'static [Answer] {
511 match self.effect {
512 Effect::Mutating(_) | Effect::Command(_) | Effect::Recovery(_) => {
513 &[Answer::Success, Answer::Rejected]
514 }
515 Effect::Read | Effect::Write => &[Answer::Success],
516 }
517 }
518
519 #[must_use]
530 pub fn response_schema(&self, answer: Answer) -> Value {
531 use printobserver_types::schemars::schema_for;
532 debug_assert!(
533 self.answers_with().contains(&answer),
534 "`{}` produces no {answer} answer",
535 self.name
536 );
537 let schema = match (self.name, self.effect) {
538 (_, Effect::Mutating(_)) => schema_for!(crate::wire::ActionAnswer),
539 (_, Effect::Command(_)) => schema_for!(crate::wire::SpoolCommandAnswer),
540 (_, Effect::Recovery(_)) => schema_for!(crate::wire::RecoveryAnswer),
541 (RECOVERY_STATUS, _) => schema_for!(crate::wire::RecoveryStatusAnswer),
542 ("spools", _) => schema_for!(crate::wire::SpoolsAnswer),
543 ("spool", _) => schema_for!(crate::wire::SpoolAnswer),
544 ("printer_history", _) => schema_for!(crate::wire::TimelineAnswer),
545 ("preflight", _) => schema_for!(crate::wire::PreflightAnswer),
546 ("prints", _) => schema_for!(crate::wire::PrintsAnswer),
547 ("status", _) => schema_for!(crate::wire::StatusAnswer),
548 ("context", _) => schema_for!(crate::wire::ContextAnswer),
549 ("image", _) => schema_for!(crate::wire::ImageAnswer),
550 ("history", _) => schema_for!(crate::wire::HistoryAnswer),
551 ("events", _) => schema_for!(crate::wire::EventsAnswer),
552 ("look" | "printer_look", _) => schema_for!(crate::wire::LookAnswer),
553 ("manifest_get" | "manifest_set", _) => schema_for!(crate::wire::ManifestAnswer),
554 (BED_CLEAR, _) => schema_for!(crate::wire::BedClearAnswer),
555 (name, _) => panic!("the operation `{name}` has no declared answer shape"),
556 };
557 schema.to_value()
558 }
559}
560
561fn declared(entries: &'static [Declared], located: Located) -> impl Iterator<Item = Parameter> {
563 entries.iter().map(move |entry| Parameter {
564 name: entry.name.to_owned(),
565 required: entry.required,
566 located,
567 kind: entry.kind,
568 repeated: entry.repeated,
569 })
570}
571
572fn declared_shape(entries: &'static [Declared], name: &str) -> Value {
578 let Some(entry) = entries.iter().find(|entry| entry.name == name) else {
579 return json!({ "type": "string" });
580 };
581 let one = if let Some(shape) = entry.shape {
582 json!({ "$ref": format!("#/$defs/{shape}") })
583 } else {
584 match entry.kind {
585 ValueKind::Text => json!({ "type": "string" }),
586 ValueKind::Number => json!({ "type": "number" }),
587 ValueKind::Integer => json!({ "type": "integer" }),
588 ValueKind::Boolean => json!({ "type": "boolean" }),
589 ValueKind::Structured => json!({ "type": "object" }),
590 }
591 };
592 if entry.repeated {
595 json!({ "type": "array", "items": one })
596 } else {
597 one
598 }
599}
600
601#[derive(Debug, Clone, Copy, PartialEq, Eq)]
604enum Vocabulary {
605 Actions,
607 Commands,
609 Recovery,
612}
613
614impl Vocabulary {
615 fn of(effect: Effect) -> Option<(Self, String)> {
617 let tag = |kind: ActionKind| {
618 printobserver_types::serde_json::to_value(kind)
619 .ok()
620 .and_then(|value| value.as_str().map(str::to_owned))
621 .unwrap_or_else(|| panic!("`{kind:?}` renders as the tag it is spelled by"))
622 };
623 match effect {
624 Effect::Mutating(kind) => Some((Self::Actions, tag(kind))),
625 Effect::Command(kind) => Some((Self::Commands, tag(kind.action_kind()))),
626 Effect::Recovery(kind) => Some((Self::Recovery, kind.as_str().to_owned())),
627 Effect::Read | Effect::Write => None,
628 }
629 }
630
631 const fn tag(self) -> &'static str {
633 match self {
634 Self::Actions | Self::Recovery => ACTION_TAG,
635 Self::Commands => COMMAND_TAG,
636 }
637 }
638
639 fn schema(self) -> Value {
645 use printobserver_types::schemars::schema_for;
646 match self {
647 Self::Actions => schema_for!(PrintAction).to_value(),
648 Self::Commands => schema_for!(SpoolCommand).to_value(),
649 Self::Recovery => recovery_request_schema(),
650 }
651 }
652}
653
654fn recovery_request_schema() -> Value {
657 use printobserver_types::schemars::schema_for;
658 let mut schema = schema_for!(RecoveryAction).to_value();
659 let actor = schema_for!(printobserver_core::Actor).to_value();
660 if let Some(variants) = schema.get_mut("oneOf").and_then(Value::as_array_mut) {
661 for variant in variants {
662 if let Some(properties) = variant.get_mut("properties").and_then(Value::as_object_mut) {
663 properties.insert(
664 "actor".to_owned(),
665 json!({ "$ref": "#/$defs/Actor", "description": "Who is asking." }),
666 );
667 properties.insert(
668 "reason".to_owned(),
669 json!({ "type": "string", "description": "Why the actor is asking for this." }),
670 );
671 }
672 if let Some(required) = variant.get_mut("required").and_then(Value::as_array_mut) {
673 required.push(json!("actor"));
674 required.push(json!("reason"));
675 }
676 }
677 }
678 let defs = schema
679 .as_object_mut()
680 .map(|top| top.entry("$defs").or_insert_with(|| json!({})));
681 if let Some(Value::Object(defs)) = defs {
682 if let Some(Value::Object(nested)) = actor.get("$defs") {
683 for (name, shape) in nested {
684 defs.insert(name.clone(), shape.clone());
685 }
686 }
687 let mut own = actor.clone();
688 if let Some(top) = own.as_object_mut() {
689 top.remove("$defs");
690 top.remove("$schema");
691 }
692 defs.insert("Actor".to_owned(), own);
693 }
694 schema
695}
696
697fn action_shapes(vocabulary: Vocabulary, kind: &str) -> Vec<(String, Value)> {
708 let schema = vocabulary.schema();
709 let variant = action_variant(&schema, vocabulary, kind);
710 variant
711 .get("properties")
712 .and_then(Value::as_object)
713 .unwrap_or_else(|| panic!("the action `{kind}` declares no properties"))
714 .iter()
715 .filter(|(name, _)| name.as_str() != vocabulary.tag())
716 .map(|(name, field)| (name.clone(), field.clone()))
717 .collect()
718}
719
720fn action_variant(schema: &Value, vocabulary: Vocabulary, tag: &str) -> Value {
727 schema
728 .get("oneOf")
729 .and_then(Value::as_array)
730 .and_then(|variants| {
731 variants.iter().find(|variant| {
732 variant.pointer(&format!("/properties/{}/const", vocabulary.tag()))
733 == Some(&json!(tag))
734 })
735 })
736 .cloned()
737 .unwrap_or_else(|| panic!("the contracts declare no action tagged `{tag}`"))
738}
739
740fn path_parameters(path: &str) -> Vec<Parameter> {
742 path.split('/')
743 .filter_map(|segment| segment.strip_prefix('{')?.strip_suffix('}'))
744 .map(|name| Parameter {
745 name: name.to_owned(),
746 required: true,
749 located: Located::Path,
750 kind: ValueKind::Text,
753 repeated: false,
754 })
755 .collect()
756}
757
758fn action_parameters(vocabulary: Vocabulary, kind: &str) -> Vec<Parameter> {
765 let schema = vocabulary.schema();
766 let variant = action_variant(&schema, vocabulary, kind);
767 let required: Vec<&str> = variant
768 .get("required")
769 .and_then(Value::as_array)
770 .map(|names| names.iter().filter_map(Value::as_str).collect())
771 .unwrap_or_default();
772 let properties = variant
773 .get("properties")
774 .and_then(Value::as_object)
775 .unwrap_or_else(|| panic!("the action `{kind}` declares no properties"));
776 properties
777 .iter()
778 .filter(|(name, _)| name.as_str() != vocabulary.tag())
779 .map(|(name, field)| Parameter {
780 name: name.clone(),
781 required: required.contains(&name.as_str()),
782 located: Located::Body,
783 kind: kind_of(&resolve(&schema, field)),
784 repeated: false,
785 })
786 .collect()
787}
788
789fn resolve(schema: &Value, field: &Value) -> Value {
791 let Some(reference) = field.get("$ref").and_then(Value::as_str) else {
792 return field.clone();
793 };
794 reference
795 .strip_prefix("#/")
796 .and_then(|rest| schema.pointer(&format!("/{rest}")))
797 .cloned()
798 .unwrap_or_else(|| field.clone())
799}
800
801fn kind_of(shape: &Value) -> ValueKind {
809 if let Some(declared) = shape.get("type") {
810 let named = |name: &str| match declared {
811 Value::String(one) => one == name,
812 Value::Array(many) => many.iter().any(|one| one == name),
813 _ => false,
814 };
815 if named("object") || named("array") {
816 return ValueKind::Structured;
817 }
818 if named("string") {
819 return ValueKind::Text;
820 }
821 if named("integer") {
822 return ValueKind::Integer;
823 }
824 if named("number") {
825 return ValueKind::Number;
826 }
827 if named("boolean") {
828 return ValueKind::Boolean;
829 }
830 }
831 match shape.get("oneOf").or_else(|| shape.get("anyOf")) {
832 Some(Value::Array(branches)) if !branches.is_empty() => {
833 let kinds: Vec<ValueKind> = branches
834 .iter()
835 .map(|branch| match branch.get("const") {
836 Some(Value::String(_)) => ValueKind::Text,
837 _ => kind_of(branch),
838 })
839 .collect();
840 let first = kinds[0];
841 if kinds.iter().all(|kind| *kind == first) {
842 first
843 } else {
844 ValueKind::Structured
845 }
846 }
847 _ => ValueKind::Structured,
848 }
849}
850
851const fn action(name: &'static str, path: &'static str, kind: ActionKind) -> Operation {
853 Operation {
854 name,
855 method: Method::Post,
856 path,
857 effect: Effect::Mutating(kind),
858 accepts: Some(MEDIA_TYPE),
859 answers: MEDIA_TYPE,
860 query: &[],
861 body: &[],
862 image_path_field: None,
863 printer_wide: None,
864 mints_print: false,
865 }
866}
867
868const fn command(name: &'static str, path: &'static str, kind: SpoolCommandKind) -> Operation {
870 Operation {
871 effect: Effect::Command(kind),
872 ..action(name, path, kind.action_kind())
873 }
874}
875
876const fn recovery(name: &'static str, path: &'static str, kind: RecoveryActionKind) -> Operation {
878 Operation {
879 name,
880 method: Method::Post,
881 path,
882 effect: Effect::Recovery(kind),
883 accepts: Some(MEDIA_TYPE),
884 answers: MEDIA_TYPE,
885 query: &[],
886 body: &[],
887 image_path_field: None,
888 printer_wide: None,
889 mints_print: false,
890 }
891}
892
893const fn read(name: &'static str, path: &'static str) -> Operation {
895 Operation {
896 name,
897 method: Method::Get,
898 path,
899 effect: Effect::Read,
900 accepts: None,
901 answers: MEDIA_TYPE,
902 query: &[],
903 body: &[],
904 image_path_field: None,
905 printer_wide: None,
906 mints_print: false,
907 }
908}
909
910#[must_use]
917pub fn command_for(operation: &str) -> String {
918 operation.replace('_', "-")
919}
920
921pub const OPERATIONS: [Operation; 39] = [
923 read("prints", "/prints"),
927 read("status", "/prints/{print_id}/status"),
928 Operation {
931 query: &[
932 Declared {
934 shape: Some("EventId"),
935 ..Declared::once("since", false, ValueKind::Text)
936 },
937 ],
938 image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
939 ..read("context", "/prints/{print_id}/context")
940 },
941 Operation {
942 image_path_field: Some(IMAGE_PATH_FIELD),
943 ..read("image", "/images/{image_id}")
944 },
945 Operation {
946 query: &[Declared::once("limit", false, ValueKind::Integer)],
947 ..read("history", "/prints/{print_id}/history")
948 },
949 Operation {
953 query: &[
954 Declared::once("after", false, ValueKind::Text),
955 Declared::once("print_id", false, ValueKind::Text),
956 Declared {
957 repeated: true,
958 ..Declared::once("kinds", false, ValueKind::Text)
959 },
960 Declared {
961 repeated: true,
962 ..Declared::once("exclude_kinds", false, ValueKind::Text)
963 },
964 Declared::once("wait_s", false, ValueKind::Integer),
965 Declared::once("limit", false, ValueKind::Integer),
966 ],
967 ..read("events", "/events")
968 },
969 read("manifest_get", "/prints/{print_id}/manifest"),
970 Operation {
975 query: &[Declared::once("wait_s", false, ValueKind::Integer)],
976 image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
977 printer_wide: Some(&PRINTER_LOOK_OPERATION),
978 mints_print: false,
979 ..read("look", "/prints/{print_id}/look")
980 },
981 PRINTER_LOOK_OPERATION,
982 Operation {
983 name: "manifest_set",
984 method: Method::Put,
985 path: "/prints/{print_id}/manifest",
986 effect: Effect::Write,
987 accepts: Some(MEDIA_TYPE),
988 answers: MEDIA_TYPE,
989 query: &[],
990 body: &[
991 Declared::once("reason", true, ValueKind::Text),
992 Declared {
993 shape: Some("JobManifest"),
994 ..Declared::once("manifest", true, ValueKind::Structured)
995 },
996 ],
997 image_path_field: None,
998 printer_wide: None,
999 mints_print: false,
1000 },
1001 Operation {
1005 query: &[Declared::once("include_retired", false, ValueKind::Boolean)],
1006 ..read("spools", "/spools")
1007 },
1008 read("spool", "/spools/{spool_id}"),
1009 Operation {
1013 query: &[
1014 Declared {
1015 repeated: true,
1016 ..Declared::once("kinds", false, ValueKind::Text)
1017 },
1018 Declared::once("since", false, ValueKind::Text),
1019 Declared::once("until", false, ValueKind::Text),
1020 Declared::once("spool_id", false, ValueKind::Text),
1021 Declared::once("before", false, ValueKind::Text),
1022 Declared::once("limit", false, ValueKind::Integer),
1023 ],
1024 ..read("printer_history", "/history")
1025 },
1026 Operation {
1030 query: &[
1031 Declared::once("file_name", true, ValueKind::Text),
1032 Declared {
1034 shape: Some("SheetId"),
1035 ..Declared::once("sheet", false, ValueKind::Text)
1036 },
1037 ],
1038 ..read("preflight", "/preflight")
1039 },
1040 action(
1041 "pause",
1042 "/prints/{print_id}/actions/pause",
1043 ActionKind::Pause,
1044 ),
1045 action(
1046 "resume",
1047 "/prints/{print_id}/actions/resume",
1048 ActionKind::Resume,
1049 ),
1050 action(
1051 "cancel",
1052 "/prints/{print_id}/actions/cancel",
1053 ActionKind::Cancel,
1054 ),
1055 Operation {
1057 mints_print: true,
1058 ..action(
1059 "start_print",
1060 "/prints/{print_id}/actions/start_print",
1061 ActionKind::StartPrint,
1062 )
1063 },
1064 action(
1065 "set_feedrate_factor",
1066 "/prints/{print_id}/actions/set_feedrate_factor",
1067 ActionKind::SetFeedrateFactor,
1068 ),
1069 action(
1070 "set_flowrate_factor",
1071 "/prints/{print_id}/actions/set_flowrate_factor",
1072 ActionKind::SetFlowrateFactor,
1073 ),
1074 action(
1075 "set_tool_target_c",
1076 "/prints/{print_id}/actions/set_tool_target_c",
1077 ActionKind::SetToolTargetC,
1078 ),
1079 action(
1080 "set_bed_target_c",
1081 "/prints/{print_id}/actions/set_bed_target_c",
1082 ActionKind::SetBedTargetC,
1083 ),
1084 action(
1085 "set_fan_percent",
1086 "/prints/{print_id}/actions/set_fan_percent",
1087 ActionKind::SetFanPercent,
1088 ),
1089 action(
1090 "acknowledge_failure",
1091 "/prints/{print_id}/actions/acknowledge_failure",
1092 ActionKind::AcknowledgeFailure,
1093 ),
1094 action(
1096 "close_print",
1097 "/prints/{print_id}/actions/close_print",
1098 ActionKind::ClosePrint,
1099 ),
1100 command(
1101 "register_spool",
1102 "/spools/actions/register_spool",
1103 SpoolCommandKind::RegisterSpool,
1104 ),
1105 command(
1106 "load_spool",
1107 "/spools/{spool_id}/actions/load_spool",
1108 SpoolCommandKind::LoadSpool,
1109 ),
1110 command(
1111 "unload_spool",
1112 "/spools/{spool_id}/actions/unload_spool",
1113 SpoolCommandKind::UnloadSpool,
1114 ),
1115 command(
1116 "adjust_spool",
1117 "/spools/{spool_id}/actions/adjust_spool",
1118 SpoolCommandKind::AdjustSpool,
1119 ),
1120 command(
1121 "retire_spool",
1122 "/spools/{spool_id}/actions/retire_spool",
1123 SpoolCommandKind::RetireSpool,
1124 ),
1125 read(RECOVERY_STATUS, "/printer/recovery"),
1128 recovery(
1129 "recover_lift",
1130 "/printer/recovery/recover_lift",
1131 RecoveryActionKind::RecoverLift,
1132 ),
1133 recovery(
1134 "recover_cool",
1135 "/printer/recovery/recover_cool",
1136 RecoveryActionKind::RecoverCool,
1137 ),
1138 recovery(
1139 "recover_fan",
1140 "/printer/recovery/recover_fan",
1141 RecoveryActionKind::RecoverFan,
1142 ),
1143 recovery(
1144 "recover_heat",
1145 "/printer/recovery/recover_heat",
1146 RecoveryActionKind::RecoverHeat,
1147 ),
1148 recovery(
1149 "recover_park",
1150 "/printer/recovery/recover_park",
1151 RecoveryActionKind::RecoverPark,
1152 ),
1153 recovery(
1154 "recover_home_xy",
1155 "/printer/recovery/recover_home_xy",
1156 RecoveryActionKind::RecoverHomeXy,
1157 ),
1158 recovery(
1159 "recover_home_z",
1160 "/printer/recovery/recover_home_z",
1161 RecoveryActionKind::RecoverHomeZ,
1162 ),
1163 Operation {
1167 name: BED_CLEAR,
1168 method: Method::Post,
1169 path: "/printer/bed_clear",
1170 effect: Effect::Write,
1171 accepts: Some(MEDIA_TYPE),
1172 answers: MEDIA_TYPE,
1173 query: &[],
1174 body: &[
1175 Declared {
1176 shape: Some("Actor"),
1177 ..Declared::once("actor", true, ValueKind::Structured)
1178 },
1179 Declared::once("reason", true, ValueKind::Text),
1180 ],
1181 image_path_field: None,
1182 printer_wide: None,
1183 mints_print: false,
1184 },
1185];
1186
1187pub const BED_CLEAR: &str = "bed_clear";
1190
1191pub const RECOVERY_STATUS: &str = "recover_status";
1194
1195pub const BESIDE_THE_ACTIONS: [&str; 15] = [
1205 "prints",
1206 "status",
1207 "context",
1208 "image",
1209 "history",
1210 "events",
1211 "manifest_get",
1212 "look",
1213 PRINTER_LOOK,
1214 "manifest_set",
1215 "spools",
1216 "spool",
1217 "printer_history",
1218 "preflight",
1219 BED_CLEAR,
1220];
1221
1222pub const PRINTER_LOOK: &str = "printer_look";
1225
1226const PRINTER_LOOK_OPERATION: Operation = Operation {
1233 query: &[Declared::once("wait_s", false, ValueKind::Integer)],
1234 image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
1235 ..read(PRINTER_LOOK, "/look")
1236};
1237
1238#[must_use]
1241pub fn printer_wide_of(name: &str) -> Option<&'static Operation> {
1242 OPERATIONS
1243 .iter()
1244 .find(|declared| declared.printer_wide.is_some_and(|wide| wide.name == name))
1245}
1246
1247#[must_use]
1249pub fn operation(name: &str) -> Option<&'static Operation> {
1250 OPERATIONS.iter().find(|declared| declared.name == name)
1251}
1252
1253#[cfg(test)]
1254mod tests {
1255 use printobserver_core::ActionKind;
1256
1257 use super::{Effect, MEDIA_TYPE, Method, OPERATIONS, VERSION_PREFIX, operation};
1258
1259 #[test]
1261 fn every_method_is_spelled_as_the_wire_spells_it() {
1262 for (method, spelling) in [
1263 (Method::Get, "GET"),
1264 (Method::Post, "POST"),
1265 (Method::Put, "PUT"),
1266 ] {
1267 assert_eq!(method.as_str(), spelling);
1268 assert_eq!(method.to_string(), spelling);
1269 }
1270 }
1271
1272 #[test]
1274 fn every_operation_sits_beneath_the_one_versioned_prefix() {
1275 for declared in OPERATIONS {
1276 let whole = declared.full_path();
1277 assert!(
1278 whole.starts_with(VERSION_PREFIX),
1279 "`{}` is served at {whole}",
1280 declared.name
1281 );
1282 assert_eq!(declared.answers, MEDIA_TYPE);
1283 }
1284 }
1285
1286 #[test]
1288 fn a_mutating_operation_names_its_action_and_a_read_names_none() {
1289 for declared in OPERATIONS {
1290 match declared.effect {
1291 Effect::Mutating(kind) => {
1292 assert_eq!(declared.action_kind(), Some(kind));
1293 assert_eq!(declared.command_kind(), None);
1294 assert_eq!(declared.granted_as(), Some(kind));
1295 assert!(declared.is_mutating());
1296 }
1297 Effect::Command(kind) => {
1298 assert_eq!(declared.action_kind(), None);
1299 assert_eq!(declared.command_kind(), Some(kind.action_kind()));
1300 assert_eq!(declared.granted_as(), Some(kind.action_kind()));
1301 assert!(declared.is_mutating());
1302 }
1303 Effect::Recovery(kind) => {
1304 assert_eq!(declared.action_kind(), None);
1305 assert_eq!(declared.granted_as(), None);
1306 assert_eq!(declared.recovery_kind(), Some(kind));
1307 assert!(declared.is_mutating());
1308 }
1309 Effect::Write => {
1310 assert_eq!(declared.action_kind(), None);
1311 assert!(
1312 declared.is_mutating(),
1313 "`{}` writes a record and is not held to the reason every \
1314 change carries",
1315 declared.name
1316 );
1317 }
1318 Effect::Read => {
1319 assert_eq!(declared.action_kind(), None);
1320 assert!(!declared.is_mutating());
1321 }
1322 }
1323 }
1324 }
1325
1326 #[test]
1331 fn a_mutating_operation_takes_a_body_and_a_read_takes_none() {
1332 let mutating = super::action(
1333 "pause",
1334 "/prints/{print_id}/actions/pause",
1335 ActionKind::Pause,
1336 );
1337 assert_eq!(mutating.method, Method::Post);
1338 assert_eq!(mutating.accepts, Some(MEDIA_TYPE));
1339 assert_eq!(mutating.answers, MEDIA_TYPE);
1340 assert_eq!(mutating.action_kind(), Some(ActionKind::Pause));
1341
1342 let reading = super::read("status", "/prints/{print_id}/status");
1343 assert_eq!(reading.method, Method::Get);
1344 assert_eq!(reading.accepts, None);
1345 assert_eq!(reading.answers, MEDIA_TYPE);
1346 assert_eq!(reading.effect, Effect::Read);
1347 }
1348
1349 #[test]
1352 fn a_spool_commands_body_is_its_fields_less_the_tag_and_the_routed_spool() {
1353 let load = operation("load_spool").expect("the load is served");
1354 let names: Vec<(String, super::Located)> = load
1355 .request()
1356 .into_iter()
1357 .map(|parameter| (parameter.name, parameter.located))
1358 .collect();
1359 assert_eq!(
1360 names,
1361 vec![
1362 ("spool_id".to_owned(), super::Located::Path),
1363 ("actor".to_owned(), super::Located::Body),
1364 ("reason".to_owned(), super::Located::Body),
1365 ("tool".to_owned(), super::Located::Body),
1366 ]
1367 );
1368 let register = operation("register_spool").expect("the registration is served");
1369 assert!(
1370 register
1371 .request()
1372 .iter()
1373 .all(|parameter| parameter.name != super::COMMAND_TAG
1374 && parameter.located == super::Located::Body)
1375 );
1376 }
1377
1378 #[test]
1382 fn the_ledgers_kinds_are_the_commands_the_contracts_declare() {
1383 let schema = super::Vocabulary::Commands.schema();
1384 let declared: Vec<String> = schema["oneOf"]
1385 .as_array()
1386 .expect("the spool vocabulary is a union")
1387 .iter()
1388 .filter_map(|variant| variant.pointer("/properties/command/const"))
1389 .filter_map(|tag| tag.as_str().map(str::to_owned))
1390 .collect();
1391 let kinds: Vec<String> = super::SpoolCommandKind::ALL
1392 .iter()
1393 .map(|kind| {
1394 printobserver_types::serde_json::to_value(kind.action_kind())
1395 .ok()
1396 .and_then(|tag| tag.as_str().map(str::to_owned))
1397 .expect("an action kind renders as its tag")
1398 })
1399 .collect();
1400 assert_eq!(kinds, declared);
1401 let served: Vec<super::SpoolCommandKind> = OPERATIONS
1402 .iter()
1403 .filter_map(|operation| match operation.effect {
1404 Effect::Command(kind) => Some(kind),
1405 _ => None,
1406 })
1407 .collect();
1408 assert_eq!(served, super::SpoolCommandKind::ALL.to_vec());
1409 }
1410
1411 #[test]
1413 fn a_repeated_value_is_described_as_a_list_of_its_kind() {
1414 let history = operation("printer_history").expect("the printer history is served");
1415 let kinds = history
1416 .request_shapes()
1417 .into_iter()
1418 .find(|(parameter, _)| parameter.name == "kinds")
1419 .expect("the history takes kinds");
1420 assert!(kinds.0.repeated);
1421 assert_eq!(
1422 kinds.1,
1423 printobserver_types::serde_json::json!({"type": "array", "items": {"type": "string"}})
1424 );
1425 }
1426
1427 #[test]
1430 fn a_recovery_actions_body_is_its_fields_beside_the_actor_and_the_reason() {
1431 let heat = operation("recover_heat").expect("the heat is served");
1432 let names: Vec<(String, bool, super::Located)> = heat
1433 .request()
1434 .into_iter()
1435 .map(|parameter| (parameter.name, parameter.required, parameter.located))
1436 .collect();
1437 assert_eq!(
1438 names,
1439 vec![
1440 ("actor".to_owned(), true, super::Located::Body),
1441 ("clearance_asserted".to_owned(), false, super::Located::Body),
1442 ("reason".to_owned(), true, super::Located::Body),
1443 ("target_c".to_owned(), true, super::Located::Body),
1444 ("tool".to_owned(), true, super::Located::Body),
1445 ]
1446 );
1447 let cool = operation("recover_cool").expect("the cool is served");
1448 let names: Vec<String> = cool
1449 .request()
1450 .into_iter()
1451 .map(|parameter| parameter.name)
1452 .collect();
1453 assert_eq!(names, vec!["actor".to_owned(), "reason".to_owned()]);
1454 let served: Vec<super::RecoveryActionKind> = OPERATIONS
1455 .iter()
1456 .filter_map(super::Operation::recovery_kind)
1457 .collect();
1458 assert_eq!(served, super::RecoveryActionKind::ALL.to_vec());
1459 }
1460
1461 #[test]
1465 fn a_printer_wide_form_takes_its_prints_values_less_the_print() {
1466 let mut forms = 0;
1467 for declared in OPERATIONS {
1468 let Some(wide) = declared.printer_wide else {
1469 continue;
1470 };
1471 forms += 1;
1472 assert_eq!(
1473 operation(wide.name),
1474 Some(wide),
1475 "the printer-wide form is not an operation this server serves"
1476 );
1477 assert_eq!(wide.method, declared.method, "`{}`", declared.name);
1478 assert_eq!(wide.effect, declared.effect, "`{}`", declared.name);
1479 assert_eq!(wide.image_path_field, declared.image_path_field);
1480 assert_eq!(
1481 wide.printer_wide, None,
1482 "a printer-wide form has none of its own"
1483 );
1484 assert!(!wide.path.contains("{print_id}"), "`{}`", wide.name);
1485 let taken: Vec<super::Parameter> = declared
1486 .request()
1487 .into_iter()
1488 .filter(|parameter| parameter.name != "print_id")
1489 .collect();
1490 assert_eq!(wide.request(), taken, "`{}`", wide.name);
1491 assert_eq!(
1492 super::printer_wide_of(wide.name).map(|found| found.name),
1493 Some(declared.name)
1494 );
1495 }
1496 assert_eq!(
1497 forms, 1,
1498 "the look is the one read with a printer-wide form"
1499 );
1500 assert!(super::printer_wide_of("look").is_none());
1501 }
1502
1503 #[test]
1505 fn an_operation_this_server_does_not_serve_is_answered_as_none() {
1506 assert_eq!(operation("pause").map(|found| found.name), Some("pause"));
1507 assert!(operation("reboot").is_none());
1508 }
1509}