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 (RECHECK_CAMERA, _) => schema_for!(crate::wire::RecheckCameraAnswer),
556 (name, _) => panic!("the operation `{name}` has no declared answer shape"),
557 };
558 schema.to_value()
559 }
560}
561
562fn declared(entries: &'static [Declared], located: Located) -> impl Iterator<Item = Parameter> {
564 entries.iter().map(move |entry| Parameter {
565 name: entry.name.to_owned(),
566 required: entry.required,
567 located,
568 kind: entry.kind,
569 repeated: entry.repeated,
570 })
571}
572
573fn declared_shape(entries: &'static [Declared], name: &str) -> Value {
579 let Some(entry) = entries.iter().find(|entry| entry.name == name) else {
580 return json!({ "type": "string" });
581 };
582 let one = if let Some(shape) = entry.shape {
583 json!({ "$ref": format!("#/$defs/{shape}") })
584 } else {
585 match entry.kind {
586 ValueKind::Text => json!({ "type": "string" }),
587 ValueKind::Number => json!({ "type": "number" }),
588 ValueKind::Integer => json!({ "type": "integer" }),
589 ValueKind::Boolean => json!({ "type": "boolean" }),
590 ValueKind::Structured => json!({ "type": "object" }),
591 }
592 };
593 if entry.repeated {
596 json!({ "type": "array", "items": one })
597 } else {
598 one
599 }
600}
601
602#[derive(Debug, Clone, Copy, PartialEq, Eq)]
605enum Vocabulary {
606 Actions,
608 Commands,
610 Recovery,
613}
614
615impl Vocabulary {
616 fn of(effect: Effect) -> Option<(Self, String)> {
618 let tag = |kind: ActionKind| {
619 printobserver_types::serde_json::to_value(kind)
620 .ok()
621 .and_then(|value| value.as_str().map(str::to_owned))
622 .unwrap_or_else(|| panic!("`{kind:?}` renders as the tag it is spelled by"))
623 };
624 match effect {
625 Effect::Mutating(kind) => Some((Self::Actions, tag(kind))),
626 Effect::Command(kind) => Some((Self::Commands, tag(kind.action_kind()))),
627 Effect::Recovery(kind) => Some((Self::Recovery, kind.as_str().to_owned())),
628 Effect::Read | Effect::Write => None,
629 }
630 }
631
632 const fn tag(self) -> &'static str {
634 match self {
635 Self::Actions | Self::Recovery => ACTION_TAG,
636 Self::Commands => COMMAND_TAG,
637 }
638 }
639
640 fn schema(self) -> Value {
646 use printobserver_types::schemars::schema_for;
647 match self {
648 Self::Actions => schema_for!(PrintAction).to_value(),
649 Self::Commands => schema_for!(SpoolCommand).to_value(),
650 Self::Recovery => recovery_request_schema(),
651 }
652 }
653}
654
655fn recovery_request_schema() -> Value {
658 use printobserver_types::schemars::schema_for;
659 let mut schema = schema_for!(RecoveryAction).to_value();
660 let actor = schema_for!(printobserver_core::Actor).to_value();
661 if let Some(variants) = schema.get_mut("oneOf").and_then(Value::as_array_mut) {
662 for variant in variants {
663 if let Some(properties) = variant.get_mut("properties").and_then(Value::as_object_mut) {
664 properties.insert(
665 "actor".to_owned(),
666 json!({ "$ref": "#/$defs/Actor", "description": "Who is asking." }),
667 );
668 properties.insert(
669 "reason".to_owned(),
670 json!({ "type": "string", "description": "Why the actor is asking for this." }),
671 );
672 }
673 if let Some(required) = variant.get_mut("required").and_then(Value::as_array_mut) {
674 required.push(json!("actor"));
675 required.push(json!("reason"));
676 }
677 }
678 }
679 let defs = schema
680 .as_object_mut()
681 .map(|top| top.entry("$defs").or_insert_with(|| json!({})));
682 if let Some(Value::Object(defs)) = defs {
683 if let Some(Value::Object(nested)) = actor.get("$defs") {
684 for (name, shape) in nested {
685 defs.insert(name.clone(), shape.clone());
686 }
687 }
688 let mut own = actor.clone();
689 if let Some(top) = own.as_object_mut() {
690 top.remove("$defs");
691 top.remove("$schema");
692 }
693 defs.insert("Actor".to_owned(), own);
694 }
695 schema
696}
697
698fn action_shapes(vocabulary: Vocabulary, kind: &str) -> Vec<(String, Value)> {
709 let schema = vocabulary.schema();
710 let variant = action_variant(&schema, vocabulary, kind);
711 variant
712 .get("properties")
713 .and_then(Value::as_object)
714 .unwrap_or_else(|| panic!("the action `{kind}` declares no properties"))
715 .iter()
716 .filter(|(name, _)| name.as_str() != vocabulary.tag())
717 .map(|(name, field)| (name.clone(), field.clone()))
718 .collect()
719}
720
721fn action_variant(schema: &Value, vocabulary: Vocabulary, tag: &str) -> Value {
728 schema
729 .get("oneOf")
730 .and_then(Value::as_array)
731 .and_then(|variants| {
732 variants.iter().find(|variant| {
733 variant.pointer(&format!("/properties/{}/const", vocabulary.tag()))
734 == Some(&json!(tag))
735 })
736 })
737 .cloned()
738 .unwrap_or_else(|| panic!("the contracts declare no action tagged `{tag}`"))
739}
740
741fn path_parameters(path: &str) -> Vec<Parameter> {
743 path.split('/')
744 .filter_map(|segment| segment.strip_prefix('{')?.strip_suffix('}'))
745 .map(|name| Parameter {
746 name: name.to_owned(),
747 required: true,
750 located: Located::Path,
751 kind: ValueKind::Text,
754 repeated: false,
755 })
756 .collect()
757}
758
759fn action_parameters(vocabulary: Vocabulary, kind: &str) -> Vec<Parameter> {
766 let schema = vocabulary.schema();
767 let variant = action_variant(&schema, vocabulary, kind);
768 let required: Vec<&str> = variant
769 .get("required")
770 .and_then(Value::as_array)
771 .map(|names| names.iter().filter_map(Value::as_str).collect())
772 .unwrap_or_default();
773 let properties = variant
774 .get("properties")
775 .and_then(Value::as_object)
776 .unwrap_or_else(|| panic!("the action `{kind}` declares no properties"));
777 properties
778 .iter()
779 .filter(|(name, _)| name.as_str() != vocabulary.tag())
780 .map(|(name, field)| Parameter {
781 name: name.clone(),
782 required: required.contains(&name.as_str()),
783 located: Located::Body,
784 kind: kind_of(&resolve(&schema, field)),
785 repeated: false,
786 })
787 .collect()
788}
789
790fn resolve(schema: &Value, field: &Value) -> Value {
792 let Some(reference) = field.get("$ref").and_then(Value::as_str) else {
793 return field.clone();
794 };
795 reference
796 .strip_prefix("#/")
797 .and_then(|rest| schema.pointer(&format!("/{rest}")))
798 .cloned()
799 .unwrap_or_else(|| field.clone())
800}
801
802fn kind_of(shape: &Value) -> ValueKind {
810 if let Some(declared) = shape.get("type") {
811 let named = |name: &str| match declared {
812 Value::String(one) => one == name,
813 Value::Array(many) => many.iter().any(|one| one == name),
814 _ => false,
815 };
816 if named("object") || named("array") {
817 return ValueKind::Structured;
818 }
819 if named("string") {
820 return ValueKind::Text;
821 }
822 if named("integer") {
823 return ValueKind::Integer;
824 }
825 if named("number") {
826 return ValueKind::Number;
827 }
828 if named("boolean") {
829 return ValueKind::Boolean;
830 }
831 }
832 match shape.get("oneOf").or_else(|| shape.get("anyOf")) {
833 Some(Value::Array(branches)) if !branches.is_empty() => {
834 let kinds: Vec<ValueKind> = branches
835 .iter()
836 .map(|branch| match branch.get("const") {
837 Some(Value::String(_)) => ValueKind::Text,
838 _ => kind_of(branch),
839 })
840 .collect();
841 let first = kinds[0];
842 if kinds.iter().all(|kind| *kind == first) {
843 first
844 } else {
845 ValueKind::Structured
846 }
847 }
848 _ => ValueKind::Structured,
849 }
850}
851
852const fn action(name: &'static str, path: &'static str, kind: ActionKind) -> Operation {
854 Operation {
855 name,
856 method: Method::Post,
857 path,
858 effect: Effect::Mutating(kind),
859 accepts: Some(MEDIA_TYPE),
860 answers: MEDIA_TYPE,
861 query: &[],
862 body: &[],
863 image_path_field: None,
864 printer_wide: None,
865 mints_print: false,
866 }
867}
868
869const fn command(name: &'static str, path: &'static str, kind: SpoolCommandKind) -> Operation {
871 Operation {
872 effect: Effect::Command(kind),
873 ..action(name, path, kind.action_kind())
874 }
875}
876
877const fn recovery(name: &'static str, path: &'static str, kind: RecoveryActionKind) -> Operation {
879 Operation {
880 name,
881 method: Method::Post,
882 path,
883 effect: Effect::Recovery(kind),
884 accepts: Some(MEDIA_TYPE),
885 answers: MEDIA_TYPE,
886 query: &[],
887 body: &[],
888 image_path_field: None,
889 printer_wide: None,
890 mints_print: false,
891 }
892}
893
894const fn read(name: &'static str, path: &'static str) -> Operation {
896 Operation {
897 name,
898 method: Method::Get,
899 path,
900 effect: Effect::Read,
901 accepts: None,
902 answers: MEDIA_TYPE,
903 query: &[],
904 body: &[],
905 image_path_field: None,
906 printer_wide: None,
907 mints_print: false,
908 }
909}
910
911#[must_use]
918pub fn command_for(operation: &str) -> String {
919 operation.replace('_', "-")
920}
921
922pub const OPERATIONS: [Operation; 40] = [
924 read("prints", "/prints"),
928 read("status", "/prints/{print_id}/status"),
929 Operation {
932 query: &[
933 Declared {
935 shape: Some("EventId"),
936 ..Declared::once("since", false, ValueKind::Text)
937 },
938 ],
939 image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
940 ..read("context", "/prints/{print_id}/context")
941 },
942 Operation {
943 image_path_field: Some(IMAGE_PATH_FIELD),
944 ..read("image", "/images/{image_id}")
945 },
946 Operation {
947 query: &[Declared::once("limit", false, ValueKind::Integer)],
948 ..read("history", "/prints/{print_id}/history")
949 },
950 Operation {
954 query: &[
955 Declared::once("after", false, ValueKind::Text),
956 Declared::once("print_id", false, ValueKind::Text),
957 Declared {
958 repeated: true,
959 ..Declared::once("kinds", false, ValueKind::Text)
960 },
961 Declared {
962 repeated: true,
963 ..Declared::once("exclude_kinds", false, ValueKind::Text)
964 },
965 Declared::once("wait_s", false, ValueKind::Integer),
966 Declared::once("limit", false, ValueKind::Integer),
967 ],
968 ..read("events", "/events")
969 },
970 read("manifest_get", "/prints/{print_id}/manifest"),
971 Operation {
976 query: &[Declared::once("wait_s", false, ValueKind::Integer)],
977 image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
978 printer_wide: Some(&PRINTER_LOOK_OPERATION),
979 mints_print: false,
980 ..read("look", "/prints/{print_id}/look")
981 },
982 PRINTER_LOOK_OPERATION,
983 Operation {
984 name: "manifest_set",
985 method: Method::Put,
986 path: "/prints/{print_id}/manifest",
987 effect: Effect::Write,
988 accepts: Some(MEDIA_TYPE),
989 answers: MEDIA_TYPE,
990 query: &[],
991 body: &[
992 Declared::once("reason", true, ValueKind::Text),
993 Declared {
994 shape: Some("JobManifest"),
995 ..Declared::once("manifest", true, ValueKind::Structured)
996 },
997 ],
998 image_path_field: None,
999 printer_wide: None,
1000 mints_print: false,
1001 },
1002 Operation {
1006 query: &[Declared::once("include_retired", false, ValueKind::Boolean)],
1007 ..read("spools", "/spools")
1008 },
1009 read("spool", "/spools/{spool_id}"),
1010 Operation {
1014 query: &[
1015 Declared {
1016 repeated: true,
1017 ..Declared::once("kinds", false, ValueKind::Text)
1018 },
1019 Declared::once("since", false, ValueKind::Text),
1020 Declared::once("until", false, ValueKind::Text),
1021 Declared::once("spool_id", false, ValueKind::Text),
1022 Declared::once("before", false, ValueKind::Text),
1023 Declared::once("limit", false, ValueKind::Integer),
1024 ],
1025 ..read("printer_history", "/history")
1026 },
1027 Operation {
1031 query: &[
1032 Declared::once("file_name", true, ValueKind::Text),
1033 Declared {
1035 shape: Some("SheetId"),
1036 ..Declared::once("sheet", false, ValueKind::Text)
1037 },
1038 ],
1039 ..read("preflight", "/preflight")
1040 },
1041 action(
1042 "pause",
1043 "/prints/{print_id}/actions/pause",
1044 ActionKind::Pause,
1045 ),
1046 action(
1047 "resume",
1048 "/prints/{print_id}/actions/resume",
1049 ActionKind::Resume,
1050 ),
1051 action(
1052 "cancel",
1053 "/prints/{print_id}/actions/cancel",
1054 ActionKind::Cancel,
1055 ),
1056 Operation {
1058 mints_print: true,
1059 ..action(
1060 "start_print",
1061 "/prints/{print_id}/actions/start_print",
1062 ActionKind::StartPrint,
1063 )
1064 },
1065 action(
1066 "set_feedrate_factor",
1067 "/prints/{print_id}/actions/set_feedrate_factor",
1068 ActionKind::SetFeedrateFactor,
1069 ),
1070 action(
1071 "set_flowrate_factor",
1072 "/prints/{print_id}/actions/set_flowrate_factor",
1073 ActionKind::SetFlowrateFactor,
1074 ),
1075 action(
1076 "set_tool_target_c",
1077 "/prints/{print_id}/actions/set_tool_target_c",
1078 ActionKind::SetToolTargetC,
1079 ),
1080 action(
1081 "set_bed_target_c",
1082 "/prints/{print_id}/actions/set_bed_target_c",
1083 ActionKind::SetBedTargetC,
1084 ),
1085 action(
1086 "set_fan_percent",
1087 "/prints/{print_id}/actions/set_fan_percent",
1088 ActionKind::SetFanPercent,
1089 ),
1090 action(
1091 "acknowledge_failure",
1092 "/prints/{print_id}/actions/acknowledge_failure",
1093 ActionKind::AcknowledgeFailure,
1094 ),
1095 action(
1097 "close_print",
1098 "/prints/{print_id}/actions/close_print",
1099 ActionKind::ClosePrint,
1100 ),
1101 command(
1102 "register_spool",
1103 "/spools/actions/register_spool",
1104 SpoolCommandKind::RegisterSpool,
1105 ),
1106 command(
1107 "load_spool",
1108 "/spools/{spool_id}/actions/load_spool",
1109 SpoolCommandKind::LoadSpool,
1110 ),
1111 command(
1112 "unload_spool",
1113 "/spools/{spool_id}/actions/unload_spool",
1114 SpoolCommandKind::UnloadSpool,
1115 ),
1116 command(
1117 "adjust_spool",
1118 "/spools/{spool_id}/actions/adjust_spool",
1119 SpoolCommandKind::AdjustSpool,
1120 ),
1121 command(
1122 "retire_spool",
1123 "/spools/{spool_id}/actions/retire_spool",
1124 SpoolCommandKind::RetireSpool,
1125 ),
1126 read(RECOVERY_STATUS, "/printer/recovery"),
1129 recovery(
1130 "recover_lift",
1131 "/printer/recovery/recover_lift",
1132 RecoveryActionKind::RecoverLift,
1133 ),
1134 recovery(
1135 "recover_cool",
1136 "/printer/recovery/recover_cool",
1137 RecoveryActionKind::RecoverCool,
1138 ),
1139 recovery(
1140 "recover_fan",
1141 "/printer/recovery/recover_fan",
1142 RecoveryActionKind::RecoverFan,
1143 ),
1144 recovery(
1145 "recover_heat",
1146 "/printer/recovery/recover_heat",
1147 RecoveryActionKind::RecoverHeat,
1148 ),
1149 recovery(
1150 "recover_park",
1151 "/printer/recovery/recover_park",
1152 RecoveryActionKind::RecoverPark,
1153 ),
1154 recovery(
1155 "recover_home_xy",
1156 "/printer/recovery/recover_home_xy",
1157 RecoveryActionKind::RecoverHomeXy,
1158 ),
1159 recovery(
1160 "recover_home_z",
1161 "/printer/recovery/recover_home_z",
1162 RecoveryActionKind::RecoverHomeZ,
1163 ),
1164 Operation {
1168 name: BED_CLEAR,
1169 method: Method::Post,
1170 path: "/printer/bed_clear",
1171 effect: Effect::Write,
1172 accepts: Some(MEDIA_TYPE),
1173 answers: MEDIA_TYPE,
1174 query: &[],
1175 body: &[
1176 Declared {
1177 shape: Some("Actor"),
1178 ..Declared::once("actor", true, ValueKind::Structured)
1179 },
1180 Declared::once("reason", true, ValueKind::Text),
1181 ],
1182 image_path_field: None,
1183 printer_wide: None,
1184 mints_print: false,
1185 },
1186 Operation {
1190 name: RECHECK_CAMERA,
1191 method: Method::Post,
1192 path: "/prints/{print_id}/camera/recheck",
1193 effect: Effect::Write,
1194 accepts: Some(MEDIA_TYPE),
1195 answers: MEDIA_TYPE,
1196 query: &[],
1197 body: &[
1198 Declared {
1199 shape: Some("Actor"),
1200 ..Declared::once("actor", true, ValueKind::Structured)
1201 },
1202 Declared::once("reason", true, ValueKind::Text),
1203 ],
1204 image_path_field: Some(RECHECK_FRAME_PATH_FIELD),
1205 printer_wide: None,
1206 mints_print: false,
1207 },
1208];
1209
1210pub const BED_CLEAR: &str = "bed_clear";
1213
1214pub const RECHECK_CAMERA: &str = "recheck_camera";
1216
1217pub const RECHECK_FRAME_PATH_FIELD: &str = "frame_path";
1219
1220pub const RECOVERY_STATUS: &str = "recover_status";
1223
1224pub const BESIDE_THE_ACTIONS: [&str; 16] = [
1235 "prints",
1236 "status",
1237 "context",
1238 "image",
1239 "history",
1240 "events",
1241 "manifest_get",
1242 "look",
1243 PRINTER_LOOK,
1244 "manifest_set",
1245 "spools",
1246 "spool",
1247 "printer_history",
1248 "preflight",
1249 BED_CLEAR,
1250 RECHECK_CAMERA,
1251];
1252
1253pub const PRINTER_LOOK: &str = "printer_look";
1256
1257const PRINTER_LOOK_OPERATION: Operation = Operation {
1264 query: &[Declared::once("wait_s", false, ValueKind::Integer)],
1265 image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
1266 ..read(PRINTER_LOOK, "/look")
1267};
1268
1269#[must_use]
1272pub fn printer_wide_of(name: &str) -> Option<&'static Operation> {
1273 OPERATIONS
1274 .iter()
1275 .find(|declared| declared.printer_wide.is_some_and(|wide| wide.name == name))
1276}
1277
1278#[must_use]
1280pub fn operation(name: &str) -> Option<&'static Operation> {
1281 OPERATIONS.iter().find(|declared| declared.name == name)
1282}
1283
1284#[cfg(test)]
1285mod tests {
1286 use printobserver_core::ActionKind;
1287
1288 use super::{Effect, MEDIA_TYPE, Method, OPERATIONS, VERSION_PREFIX, operation};
1289
1290 #[test]
1292 fn every_method_is_spelled_as_the_wire_spells_it() {
1293 for (method, spelling) in [
1294 (Method::Get, "GET"),
1295 (Method::Post, "POST"),
1296 (Method::Put, "PUT"),
1297 ] {
1298 assert_eq!(method.as_str(), spelling);
1299 assert_eq!(method.to_string(), spelling);
1300 }
1301 }
1302
1303 #[test]
1305 fn every_operation_sits_beneath_the_one_versioned_prefix() {
1306 for declared in OPERATIONS {
1307 let whole = declared.full_path();
1308 assert!(
1309 whole.starts_with(VERSION_PREFIX),
1310 "`{}` is served at {whole}",
1311 declared.name
1312 );
1313 assert_eq!(declared.answers, MEDIA_TYPE);
1314 }
1315 }
1316
1317 #[test]
1319 fn a_mutating_operation_names_its_action_and_a_read_names_none() {
1320 for declared in OPERATIONS {
1321 match declared.effect {
1322 Effect::Mutating(kind) => {
1323 assert_eq!(declared.action_kind(), Some(kind));
1324 assert_eq!(declared.command_kind(), None);
1325 assert_eq!(declared.granted_as(), Some(kind));
1326 assert!(declared.is_mutating());
1327 }
1328 Effect::Command(kind) => {
1329 assert_eq!(declared.action_kind(), None);
1330 assert_eq!(declared.command_kind(), Some(kind.action_kind()));
1331 assert_eq!(declared.granted_as(), Some(kind.action_kind()));
1332 assert!(declared.is_mutating());
1333 }
1334 Effect::Recovery(kind) => {
1335 assert_eq!(declared.action_kind(), None);
1336 assert_eq!(declared.granted_as(), None);
1337 assert_eq!(declared.recovery_kind(), Some(kind));
1338 assert!(declared.is_mutating());
1339 }
1340 Effect::Write => {
1341 assert_eq!(declared.action_kind(), None);
1342 assert!(
1343 declared.is_mutating(),
1344 "`{}` writes a record and is not held to the reason every \
1345 change carries",
1346 declared.name
1347 );
1348 }
1349 Effect::Read => {
1350 assert_eq!(declared.action_kind(), None);
1351 assert!(!declared.is_mutating());
1352 }
1353 }
1354 }
1355 }
1356
1357 #[test]
1362 fn a_mutating_operation_takes_a_body_and_a_read_takes_none() {
1363 let mutating = super::action(
1364 "pause",
1365 "/prints/{print_id}/actions/pause",
1366 ActionKind::Pause,
1367 );
1368 assert_eq!(mutating.method, Method::Post);
1369 assert_eq!(mutating.accepts, Some(MEDIA_TYPE));
1370 assert_eq!(mutating.answers, MEDIA_TYPE);
1371 assert_eq!(mutating.action_kind(), Some(ActionKind::Pause));
1372
1373 let reading = super::read("status", "/prints/{print_id}/status");
1374 assert_eq!(reading.method, Method::Get);
1375 assert_eq!(reading.accepts, None);
1376 assert_eq!(reading.answers, MEDIA_TYPE);
1377 assert_eq!(reading.effect, Effect::Read);
1378 }
1379
1380 #[test]
1383 fn a_spool_commands_body_is_its_fields_less_the_tag_and_the_routed_spool() {
1384 let load = operation("load_spool").expect("the load is served");
1385 let names: Vec<(String, super::Located)> = load
1386 .request()
1387 .into_iter()
1388 .map(|parameter| (parameter.name, parameter.located))
1389 .collect();
1390 assert_eq!(
1391 names,
1392 vec![
1393 ("spool_id".to_owned(), super::Located::Path),
1394 ("actor".to_owned(), super::Located::Body),
1395 ("reason".to_owned(), super::Located::Body),
1396 ("tool".to_owned(), super::Located::Body),
1397 ]
1398 );
1399 let register = operation("register_spool").expect("the registration is served");
1400 assert!(
1401 register
1402 .request()
1403 .iter()
1404 .all(|parameter| parameter.name != super::COMMAND_TAG
1405 && parameter.located == super::Located::Body)
1406 );
1407 }
1408
1409 #[test]
1413 fn the_ledgers_kinds_are_the_commands_the_contracts_declare() {
1414 let schema = super::Vocabulary::Commands.schema();
1415 let declared: Vec<String> = schema["oneOf"]
1416 .as_array()
1417 .expect("the spool vocabulary is a union")
1418 .iter()
1419 .filter_map(|variant| variant.pointer("/properties/command/const"))
1420 .filter_map(|tag| tag.as_str().map(str::to_owned))
1421 .collect();
1422 let kinds: Vec<String> = super::SpoolCommandKind::ALL
1423 .iter()
1424 .map(|kind| {
1425 printobserver_types::serde_json::to_value(kind.action_kind())
1426 .ok()
1427 .and_then(|tag| tag.as_str().map(str::to_owned))
1428 .expect("an action kind renders as its tag")
1429 })
1430 .collect();
1431 assert_eq!(kinds, declared);
1432 let served: Vec<super::SpoolCommandKind> = OPERATIONS
1433 .iter()
1434 .filter_map(|operation| match operation.effect {
1435 Effect::Command(kind) => Some(kind),
1436 _ => None,
1437 })
1438 .collect();
1439 assert_eq!(served, super::SpoolCommandKind::ALL.to_vec());
1440 }
1441
1442 #[test]
1444 fn a_repeated_value_is_described_as_a_list_of_its_kind() {
1445 let history = operation("printer_history").expect("the printer history is served");
1446 let kinds = history
1447 .request_shapes()
1448 .into_iter()
1449 .find(|(parameter, _)| parameter.name == "kinds")
1450 .expect("the history takes kinds");
1451 assert!(kinds.0.repeated);
1452 assert_eq!(
1453 kinds.1,
1454 printobserver_types::serde_json::json!({"type": "array", "items": {"type": "string"}})
1455 );
1456 }
1457
1458 #[test]
1461 fn a_recovery_actions_body_is_its_fields_beside_the_actor_and_the_reason() {
1462 let heat = operation("recover_heat").expect("the heat is served");
1463 let names: Vec<(String, bool, super::Located)> = heat
1464 .request()
1465 .into_iter()
1466 .map(|parameter| (parameter.name, parameter.required, parameter.located))
1467 .collect();
1468 assert_eq!(
1469 names,
1470 vec![
1471 ("actor".to_owned(), true, super::Located::Body),
1472 ("clearance_asserted".to_owned(), false, super::Located::Body),
1473 ("reason".to_owned(), true, super::Located::Body),
1474 ("target_c".to_owned(), true, super::Located::Body),
1475 ("tool".to_owned(), true, super::Located::Body),
1476 ]
1477 );
1478 let cool = operation("recover_cool").expect("the cool is served");
1479 let names: Vec<String> = cool
1480 .request()
1481 .into_iter()
1482 .map(|parameter| parameter.name)
1483 .collect();
1484 assert_eq!(names, vec!["actor".to_owned(), "reason".to_owned()]);
1485 let served: Vec<super::RecoveryActionKind> = OPERATIONS
1486 .iter()
1487 .filter_map(super::Operation::recovery_kind)
1488 .collect();
1489 assert_eq!(served, super::RecoveryActionKind::ALL.to_vec());
1490 }
1491
1492 #[test]
1496 fn a_printer_wide_form_takes_its_prints_values_less_the_print() {
1497 let mut forms = 0;
1498 for declared in OPERATIONS {
1499 let Some(wide) = declared.printer_wide else {
1500 continue;
1501 };
1502 forms += 1;
1503 assert_eq!(
1504 operation(wide.name),
1505 Some(wide),
1506 "the printer-wide form is not an operation this server serves"
1507 );
1508 assert_eq!(wide.method, declared.method, "`{}`", declared.name);
1509 assert_eq!(wide.effect, declared.effect, "`{}`", declared.name);
1510 assert_eq!(wide.image_path_field, declared.image_path_field);
1511 assert_eq!(
1512 wide.printer_wide, None,
1513 "a printer-wide form has none of its own"
1514 );
1515 assert!(!wide.path.contains("{print_id}"), "`{}`", wide.name);
1516 let taken: Vec<super::Parameter> = declared
1517 .request()
1518 .into_iter()
1519 .filter(|parameter| parameter.name != "print_id")
1520 .collect();
1521 assert_eq!(wide.request(), taken, "`{}`", wide.name);
1522 assert_eq!(
1523 super::printer_wide_of(wide.name).map(|found| found.name),
1524 Some(declared.name)
1525 );
1526 }
1527 assert_eq!(
1528 forms, 1,
1529 "the look is the one read with a printer-wide form"
1530 );
1531 assert!(super::printer_wide_of("look").is_none());
1532 }
1533
1534 #[test]
1536 fn an_operation_this_server_does_not_serve_is_answered_as_none() {
1537 assert_eq!(operation("pause").map(|found| found.name), Some("pause"));
1538 assert!(operation("reboot").is_none());
1539 }
1540}