1use printobserver_types::serde_json::{Value, json};
66
67pub use printobserver_core::{
72 ActionKind, PrintAction, RecoveryAction, RecoveryActionKind, SpoolCommand,
73};
74
75pub const VERSION_PREFIX: &str = "/v1";
77
78pub const MEDIA_TYPE: &str = "application/json";
80
81pub const INGRESS_PATH: &str = "/obico/webhook";
84
85pub const CONTEXT_IMAGE_PATH_FIELD: &str = "image_path";
87
88pub const IMAGE_PATH_FIELD: &str = "path";
90
91const ACTION_TAG: &str = "action";
94
95pub const COMMAND_TAG: &str = "command";
98
99#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
101pub enum Method {
102 Get,
104 Post,
106 Put,
108}
109
110impl Method {
111 #[must_use]
113 pub const fn as_str(self) -> &'static str {
114 match self {
115 Self::Get => "GET",
116 Self::Post => "POST",
117 Self::Put => "PUT",
118 }
119 }
120}
121
122impl core::fmt::Display for Method {
123 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
124 formatter.write_str(self.as_str())
125 }
126}
127
128#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
130pub enum Located {
131 Path,
133 Query,
135 Body,
137}
138
139#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
146pub enum ValueKind {
147 Text,
149 Number,
151 Integer,
153 Boolean,
155 Structured,
157}
158
159impl ValueKind {
160 #[must_use]
162 pub const fn structured(self) -> bool {
163 matches!(self, Self::Structured)
164 }
165}
166
167#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
173pub struct Declared {
174 pub name: &'static str,
176 pub required: bool,
178 pub kind: ValueKind,
180 pub shape: Option<&'static str>,
187 pub repeated: bool,
190}
191
192impl Declared {
193 #[must_use]
195 pub const fn once(name: &'static str, required: bool, kind: ValueKind) -> Self {
196 Self {
197 name,
198 required,
199 kind,
200 shape: None,
201 repeated: false,
202 }
203 }
204}
205
206#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
208pub struct Parameter {
209 pub name: String,
211 pub required: bool,
213 pub located: Located,
215 pub kind: ValueKind,
217 pub repeated: bool,
219}
220
221#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
223pub enum Answer {
224 Success,
226 Rejected,
228}
229
230impl Answer {
231 #[must_use]
233 pub const fn as_str(self) -> &'static str {
234 match self {
235 Self::Success => "success",
236 Self::Rejected => "rejected",
237 }
238 }
239}
240
241impl core::fmt::Display for Answer {
242 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
243 formatter.write_str(self.as_str())
244 }
245}
246
247#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
249pub enum Effect {
250 Read,
252 Mutating(ActionKind),
254 Command(SpoolCommandKind),
258 Recovery(RecoveryActionKind),
262 Write,
264}
265
266#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
273pub enum SpoolCommandKind {
274 RegisterSpool,
276 LoadSpool,
278 UnloadSpool,
280 AdjustSpool,
282 RetireSpool,
284}
285
286impl SpoolCommandKind {
287 pub const ALL: [Self; 5] = [
289 Self::RegisterSpool,
290 Self::LoadSpool,
291 Self::UnloadSpool,
292 Self::AdjustSpool,
293 Self::RetireSpool,
294 ];
295
296 #[must_use]
298 pub const fn action_kind(self) -> ActionKind {
299 match self {
300 Self::RegisterSpool => ActionKind::RegisterSpool,
301 Self::LoadSpool => ActionKind::LoadSpool,
302 Self::UnloadSpool => ActionKind::UnloadSpool,
303 Self::AdjustSpool => ActionKind::AdjustSpool,
304 Self::RetireSpool => ActionKind::RetireSpool,
305 }
306 }
307}
308
309#[derive(Debug, Clone, Copy, PartialEq, Eq)]
311pub struct Operation {
312 pub name: &'static str,
315 pub method: Method,
317 pub path: &'static str,
319 pub effect: Effect,
321 pub accepts: Option<&'static str>,
323 pub answers: &'static str,
325 pub query: &'static [Declared],
327 pub body: &'static [Declared],
332 pub image_path_field: Option<&'static str>,
341 pub printer_wide: Option<&'static Operation>,
350 pub mints_print: bool,
358}
359
360impl Operation {
361 #[must_use]
363 pub fn full_path(&self) -> String {
364 format!("{VERSION_PREFIX}{}", self.path)
365 }
366
367 #[must_use]
369 pub const fn action_kind(&self) -> Option<ActionKind> {
370 match self.effect {
371 Effect::Mutating(kind) => Some(kind),
372 _ => None,
373 }
374 }
375
376 #[must_use]
378 pub const fn command_kind(&self) -> Option<ActionKind> {
379 match self.effect {
380 Effect::Command(kind) => Some(kind.action_kind()),
381 _ => None,
382 }
383 }
384
385 #[must_use]
388 pub const fn granted_as(&self) -> Option<ActionKind> {
389 match self.effect {
390 Effect::Mutating(kind) => Some(kind),
391 Effect::Command(kind) => Some(kind.action_kind()),
392 Effect::Read | Effect::Write | Effect::Recovery(_) => None,
393 }
394 }
395
396 #[must_use]
399 pub const fn recovery_kind(&self) -> Option<RecoveryActionKind> {
400 match self.effect {
401 Effect::Recovery(kind) => Some(kind),
402 _ => None,
403 }
404 }
405
406 #[must_use]
413 pub const fn is_mutating(&self) -> bool {
414 matches!(
415 self.effect,
416 Effect::Mutating(_) | Effect::Command(_) | Effect::Recovery(_) | Effect::Write
417 )
418 }
419
420 #[must_use]
435 pub fn request(&self) -> Vec<Parameter> {
436 let mut found = path_parameters(self.path);
437 found.extend(declared(self.query, Located::Query));
438 match Vocabulary::of(self.effect) {
439 Some((vocabulary, kind)) => {
440 let routed: Vec<String> = found.iter().map(|path| path.name.clone()).collect();
441 found.extend(
442 action_parameters(vocabulary, &kind)
443 .into_iter()
444 .filter(|field| !routed.contains(&field.name)),
445 );
446 }
447 None => found.extend(declared(self.body, Located::Body)),
448 }
449 found
450 }
451
452 #[must_use]
470 pub fn request_shapes(&self) -> Vec<(Parameter, Value)> {
471 let action = match Vocabulary::of(self.effect) {
472 Some((vocabulary, kind)) => action_shapes(vocabulary, &kind),
473 None => Vec::new(),
474 };
475 self.request()
476 .into_iter()
477 .map(|parameter| {
478 let shape = match parameter.located {
479 Located::Path => json!({ "type": "string" }),
482 Located::Query => declared_shape(self.query, ¶meter.name),
483 Located::Body if action.is_empty() => {
484 declared_shape(self.body, ¶meter.name)
485 }
486 Located::Body => action
487 .iter()
488 .find(|(name, _)| *name == parameter.name)
489 .map_or_else(
490 || {
491 panic!(
492 "`{}` takes `{}` in its body, and the action it names \
493 declares no such field",
494 self.name, parameter.name
495 )
496 },
497 |(_, shape)| shape.clone(),
498 ),
499 };
500 (parameter, shape)
501 })
502 .collect()
503 }
504
505 #[must_use]
512 pub const fn answers_with(&self) -> &'static [Answer] {
513 match self.effect {
514 Effect::Mutating(_) | Effect::Command(_) | Effect::Recovery(_) => {
515 &[Answer::Success, Answer::Rejected]
516 }
517 Effect::Read | Effect::Write => &[Answer::Success],
518 }
519 }
520
521 #[must_use]
532 pub fn response_schema(&self, answer: Answer) -> Value {
533 use printobserver_types::schemars::schema_for;
534 debug_assert!(
535 self.answers_with().contains(&answer),
536 "`{}` produces no {answer} answer",
537 self.name
538 );
539 let schema = match (self.name, self.effect) {
540 (_, Effect::Mutating(_)) => schema_for!(crate::wire::ActionAnswer),
541 (_, Effect::Command(_)) => schema_for!(crate::wire::SpoolCommandAnswer),
542 (_, Effect::Recovery(_)) => schema_for!(crate::wire::RecoveryAnswer),
543 (RECOVERY_STATUS, _) => schema_for!(crate::wire::RecoveryStatusAnswer),
544 ("spools", _) => schema_for!(crate::wire::SpoolsAnswer),
545 ("spool", _) => schema_for!(crate::wire::SpoolAnswer),
546 ("printer_history", _) => schema_for!(crate::wire::TimelineAnswer),
547 ("preflight", _) => schema_for!(crate::wire::PreflightAnswer),
548 ("prints", _) => schema_for!(crate::wire::PrintsAnswer),
549 ("status", _) => schema_for!(crate::wire::StatusAnswer),
550 ("context", _) => schema_for!(crate::wire::ContextAnswer),
551 ("image", _) => schema_for!(crate::wire::ImageAnswer),
552 ("history", _) => schema_for!(crate::wire::HistoryAnswer),
553 ("events", _) => schema_for!(crate::wire::EventsAnswer),
554 ("look" | "printer_look", _) => schema_for!(crate::wire::LookAnswer),
555 ("manifest_get" | "manifest_set", _) => schema_for!(crate::wire::ManifestAnswer),
556 (BED_CLEAR, _) => schema_for!(crate::wire::BedClearAnswer),
557 (RECHECK_CAMERA, _) => schema_for!(crate::wire::RecheckCameraAnswer),
558 (CHECK_CAMERA, _) => schema_for!(crate::camera_check::CameraCheck),
559 (CHECK_HARNESS, _) => schema_for!(crate::readiness::HarnessReadiness),
560 (name, _) => panic!("the operation `{name}` has no declared answer shape"),
561 };
562 schema.to_value()
563 }
564}
565
566fn declared(entries: &'static [Declared], located: Located) -> impl Iterator<Item = Parameter> {
568 entries.iter().map(move |entry| Parameter {
569 name: entry.name.to_owned(),
570 required: entry.required,
571 located,
572 kind: entry.kind,
573 repeated: entry.repeated,
574 })
575}
576
577fn declared_shape(entries: &'static [Declared], name: &str) -> Value {
583 let Some(entry) = entries.iter().find(|entry| entry.name == name) else {
584 return json!({ "type": "string" });
585 };
586 let one = if let Some(shape) = entry.shape {
587 json!({ "$ref": format!("#/$defs/{shape}") })
588 } else {
589 match entry.kind {
590 ValueKind::Text => json!({ "type": "string" }),
591 ValueKind::Number => json!({ "type": "number" }),
592 ValueKind::Integer => json!({ "type": "integer" }),
593 ValueKind::Boolean => json!({ "type": "boolean" }),
594 ValueKind::Structured => json!({ "type": "object" }),
595 }
596 };
597 if entry.repeated {
600 json!({ "type": "array", "items": one })
601 } else {
602 one
603 }
604}
605
606#[derive(Debug, Clone, Copy, PartialEq, Eq)]
609enum Vocabulary {
610 Actions,
612 Commands,
614 Recovery,
617}
618
619impl Vocabulary {
620 fn of(effect: Effect) -> Option<(Self, String)> {
622 let tag = |kind: ActionKind| {
623 printobserver_types::serde_json::to_value(kind)
624 .ok()
625 .and_then(|value| value.as_str().map(str::to_owned))
626 .unwrap_or_else(|| panic!("`{kind:?}` renders as the tag it is spelled by"))
627 };
628 match effect {
629 Effect::Mutating(kind) => Some((Self::Actions, tag(kind))),
630 Effect::Command(kind) => Some((Self::Commands, tag(kind.action_kind()))),
631 Effect::Recovery(kind) => Some((Self::Recovery, kind.as_str().to_owned())),
632 Effect::Read | Effect::Write => None,
633 }
634 }
635
636 const fn tag(self) -> &'static str {
638 match self {
639 Self::Actions | Self::Recovery => ACTION_TAG,
640 Self::Commands => COMMAND_TAG,
641 }
642 }
643
644 fn schema(self) -> Value {
650 use printobserver_types::schemars::schema_for;
651 match self {
652 Self::Actions => schema_for!(PrintAction).to_value(),
653 Self::Commands => schema_for!(SpoolCommand).to_value(),
654 Self::Recovery => recovery_request_schema(),
655 }
656 }
657}
658
659fn recovery_request_schema() -> Value {
662 use printobserver_types::schemars::schema_for;
663 let mut schema = schema_for!(RecoveryAction).to_value();
664 let actor = schema_for!(printobserver_core::Actor).to_value();
665 if let Some(variants) = schema.get_mut("oneOf").and_then(Value::as_array_mut) {
666 for variant in variants {
667 if let Some(properties) = variant.get_mut("properties").and_then(Value::as_object_mut) {
668 properties.insert(
669 "actor".to_owned(),
670 json!({ "$ref": "#/$defs/Actor", "description": "Who is asking." }),
671 );
672 properties.insert(
673 "reason".to_owned(),
674 json!({ "type": "string", "description": "Why the actor is asking for this." }),
675 );
676 }
677 if let Some(required) = variant.get_mut("required").and_then(Value::as_array_mut) {
678 required.push(json!("actor"));
679 required.push(json!("reason"));
680 }
681 }
682 }
683 let defs = schema
684 .as_object_mut()
685 .map(|top| top.entry("$defs").or_insert_with(|| json!({})));
686 if let Some(Value::Object(defs)) = defs {
687 if let Some(Value::Object(nested)) = actor.get("$defs") {
688 for (name, shape) in nested {
689 defs.insert(name.clone(), shape.clone());
690 }
691 }
692 let mut own = actor.clone();
693 if let Some(top) = own.as_object_mut() {
694 top.remove("$defs");
695 top.remove("$schema");
696 }
697 defs.insert("Actor".to_owned(), own);
698 }
699 schema
700}
701
702fn action_shapes(vocabulary: Vocabulary, kind: &str) -> Vec<(String, Value)> {
713 let schema = vocabulary.schema();
714 let variant = action_variant(&schema, vocabulary, kind);
715 variant
716 .get("properties")
717 .and_then(Value::as_object)
718 .unwrap_or_else(|| panic!("the action `{kind}` declares no properties"))
719 .iter()
720 .filter(|(name, _)| name.as_str() != vocabulary.tag())
721 .map(|(name, field)| (name.clone(), field.clone()))
722 .collect()
723}
724
725fn action_variant(schema: &Value, vocabulary: Vocabulary, tag: &str) -> Value {
732 schema
733 .get("oneOf")
734 .and_then(Value::as_array)
735 .and_then(|variants| {
736 variants.iter().find(|variant| {
737 variant.pointer(&format!("/properties/{}/const", vocabulary.tag()))
738 == Some(&json!(tag))
739 })
740 })
741 .cloned()
742 .unwrap_or_else(|| panic!("the contracts declare no action tagged `{tag}`"))
743}
744
745fn path_parameters(path: &str) -> Vec<Parameter> {
747 path.split('/')
748 .filter_map(|segment| segment.strip_prefix('{')?.strip_suffix('}'))
749 .map(|name| Parameter {
750 name: name.to_owned(),
751 required: true,
754 located: Located::Path,
755 kind: ValueKind::Text,
758 repeated: false,
759 })
760 .collect()
761}
762
763fn action_parameters(vocabulary: Vocabulary, kind: &str) -> Vec<Parameter> {
770 let schema = vocabulary.schema();
771 let variant = action_variant(&schema, vocabulary, kind);
772 let required: Vec<&str> = variant
773 .get("required")
774 .and_then(Value::as_array)
775 .map(|names| names.iter().filter_map(Value::as_str).collect())
776 .unwrap_or_default();
777 let properties = variant
778 .get("properties")
779 .and_then(Value::as_object)
780 .unwrap_or_else(|| panic!("the action `{kind}` declares no properties"));
781 properties
782 .iter()
783 .filter(|(name, _)| name.as_str() != vocabulary.tag())
784 .map(|(name, field)| Parameter {
785 name: name.clone(),
786 required: required.contains(&name.as_str()),
787 located: Located::Body,
788 kind: kind_of(&resolve(&schema, field)),
789 repeated: false,
790 })
791 .collect()
792}
793
794fn resolve(schema: &Value, field: &Value) -> Value {
796 let Some(reference) = field.get("$ref").and_then(Value::as_str) else {
797 return field.clone();
798 };
799 reference
800 .strip_prefix("#/")
801 .and_then(|rest| schema.pointer(&format!("/{rest}")))
802 .cloned()
803 .unwrap_or_else(|| field.clone())
804}
805
806fn kind_of(shape: &Value) -> ValueKind {
814 if let Some(declared) = shape.get("type") {
815 let named = |name: &str| match declared {
816 Value::String(one) => one == name,
817 Value::Array(many) => many.iter().any(|one| one == name),
818 _ => false,
819 };
820 if named("object") || named("array") {
821 return ValueKind::Structured;
822 }
823 if named("string") {
824 return ValueKind::Text;
825 }
826 if named("integer") {
827 return ValueKind::Integer;
828 }
829 if named("number") {
830 return ValueKind::Number;
831 }
832 if named("boolean") {
833 return ValueKind::Boolean;
834 }
835 }
836 match shape.get("oneOf").or_else(|| shape.get("anyOf")) {
837 Some(Value::Array(branches)) if !branches.is_empty() => {
838 let kinds: Vec<ValueKind> = branches
839 .iter()
840 .map(|branch| match branch.get("const") {
841 Some(Value::String(_)) => ValueKind::Text,
842 _ => kind_of(branch),
843 })
844 .collect();
845 let first = kinds[0];
846 if kinds.iter().all(|kind| *kind == first) {
847 first
848 } else {
849 ValueKind::Structured
850 }
851 }
852 _ => ValueKind::Structured,
853 }
854}
855
856const fn action(name: &'static str, path: &'static str, kind: ActionKind) -> Operation {
858 Operation {
859 name,
860 method: Method::Post,
861 path,
862 effect: Effect::Mutating(kind),
863 accepts: Some(MEDIA_TYPE),
864 answers: MEDIA_TYPE,
865 query: &[],
866 body: &[],
867 image_path_field: None,
868 printer_wide: None,
869 mints_print: false,
870 }
871}
872
873const fn command(name: &'static str, path: &'static str, kind: SpoolCommandKind) -> Operation {
875 Operation {
876 effect: Effect::Command(kind),
877 ..action(name, path, kind.action_kind())
878 }
879}
880
881const fn recovery(name: &'static str, path: &'static str, kind: RecoveryActionKind) -> Operation {
883 Operation {
884 name,
885 method: Method::Post,
886 path,
887 effect: Effect::Recovery(kind),
888 accepts: Some(MEDIA_TYPE),
889 answers: MEDIA_TYPE,
890 query: &[],
891 body: &[],
892 image_path_field: None,
893 printer_wide: None,
894 mints_print: false,
895 }
896}
897
898const fn read(name: &'static str, path: &'static str) -> Operation {
900 Operation {
901 name,
902 method: Method::Get,
903 path,
904 effect: Effect::Read,
905 accepts: None,
906 answers: MEDIA_TYPE,
907 query: &[],
908 body: &[],
909 image_path_field: None,
910 printer_wide: None,
911 mints_print: false,
912 }
913}
914
915#[must_use]
922pub fn command_for(operation: &str) -> String {
923 operation.replace('_', "-")
924}
925
926pub const OPERATIONS: [Operation; 42] = [
928 read("prints", "/prints"),
932 read("status", "/prints/{print_id}/status"),
933 Operation {
936 query: &[
937 Declared {
939 shape: Some("EventId"),
940 ..Declared::once("since", false, ValueKind::Text)
941 },
942 ],
943 image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
944 ..read("context", "/prints/{print_id}/context")
945 },
946 Operation {
947 image_path_field: Some(IMAGE_PATH_FIELD),
948 ..read("image", "/images/{image_id}")
949 },
950 Operation {
951 query: &[Declared::once("limit", false, ValueKind::Integer)],
952 ..read("history", "/prints/{print_id}/history")
953 },
954 Operation {
958 query: &[
959 Declared::once("after", false, ValueKind::Text),
960 Declared::once("print_id", false, ValueKind::Text),
961 Declared {
962 repeated: true,
963 ..Declared::once("kinds", false, ValueKind::Text)
964 },
965 Declared {
966 repeated: true,
967 ..Declared::once("exclude_kinds", false, ValueKind::Text)
968 },
969 Declared::once("wait_s", false, ValueKind::Integer),
970 Declared::once("limit", false, ValueKind::Integer),
971 ],
972 ..read("events", "/events")
973 },
974 read("manifest_get", "/prints/{print_id}/manifest"),
975 Operation {
980 query: &[Declared::once("wait_s", false, ValueKind::Integer)],
981 image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
982 printer_wide: Some(&PRINTER_LOOK_OPERATION),
983 mints_print: false,
984 ..read("look", "/prints/{print_id}/look")
985 },
986 PRINTER_LOOK_OPERATION,
987 Operation {
988 name: "manifest_set",
989 method: Method::Put,
990 path: "/prints/{print_id}/manifest",
991 effect: Effect::Write,
992 accepts: Some(MEDIA_TYPE),
993 answers: MEDIA_TYPE,
994 query: &[],
995 body: &[
996 Declared::once("reason", true, ValueKind::Text),
997 Declared {
998 shape: Some("JobManifest"),
999 ..Declared::once("manifest", true, ValueKind::Structured)
1000 },
1001 ],
1002 image_path_field: None,
1003 printer_wide: None,
1004 mints_print: false,
1005 },
1006 Operation {
1010 query: &[Declared::once("include_retired", false, ValueKind::Boolean)],
1011 ..read("spools", "/spools")
1012 },
1013 read("spool", "/spools/{spool_id}"),
1014 Operation {
1018 query: &[
1019 Declared {
1020 repeated: true,
1021 ..Declared::once("kinds", false, ValueKind::Text)
1022 },
1023 Declared::once("since", false, ValueKind::Text),
1024 Declared::once("until", false, ValueKind::Text),
1025 Declared::once("spool_id", false, ValueKind::Text),
1026 Declared::once("before", false, ValueKind::Text),
1027 Declared::once("limit", false, ValueKind::Integer),
1028 ],
1029 ..read("printer_history", "/history")
1030 },
1031 Operation {
1035 query: &[
1036 Declared::once("file_name", true, ValueKind::Text),
1037 Declared {
1039 shape: Some("SheetId"),
1040 ..Declared::once("sheet", false, ValueKind::Text)
1041 },
1042 ],
1043 ..read("preflight", "/preflight")
1044 },
1045 action(
1046 "pause",
1047 "/prints/{print_id}/actions/pause",
1048 ActionKind::Pause,
1049 ),
1050 action(
1051 "resume",
1052 "/prints/{print_id}/actions/resume",
1053 ActionKind::Resume,
1054 ),
1055 action(
1056 "cancel",
1057 "/prints/{print_id}/actions/cancel",
1058 ActionKind::Cancel,
1059 ),
1060 Operation {
1062 mints_print: true,
1063 ..action(
1064 "start_print",
1065 "/prints/{print_id}/actions/start_print",
1066 ActionKind::StartPrint,
1067 )
1068 },
1069 action(
1070 "set_feedrate_factor",
1071 "/prints/{print_id}/actions/set_feedrate_factor",
1072 ActionKind::SetFeedrateFactor,
1073 ),
1074 action(
1075 "set_flowrate_factor",
1076 "/prints/{print_id}/actions/set_flowrate_factor",
1077 ActionKind::SetFlowrateFactor,
1078 ),
1079 action(
1080 "set_tool_target_c",
1081 "/prints/{print_id}/actions/set_tool_target_c",
1082 ActionKind::SetToolTargetC,
1083 ),
1084 action(
1085 "set_bed_target_c",
1086 "/prints/{print_id}/actions/set_bed_target_c",
1087 ActionKind::SetBedTargetC,
1088 ),
1089 action(
1090 "set_fan_percent",
1091 "/prints/{print_id}/actions/set_fan_percent",
1092 ActionKind::SetFanPercent,
1093 ),
1094 action(
1095 "acknowledge_failure",
1096 "/prints/{print_id}/actions/acknowledge_failure",
1097 ActionKind::AcknowledgeFailure,
1098 ),
1099 action(
1101 "close_print",
1102 "/prints/{print_id}/actions/close_print",
1103 ActionKind::ClosePrint,
1104 ),
1105 command(
1106 "register_spool",
1107 "/spools/actions/register_spool",
1108 SpoolCommandKind::RegisterSpool,
1109 ),
1110 command(
1111 "load_spool",
1112 "/spools/{spool_id}/actions/load_spool",
1113 SpoolCommandKind::LoadSpool,
1114 ),
1115 command(
1116 "unload_spool",
1117 "/spools/{spool_id}/actions/unload_spool",
1118 SpoolCommandKind::UnloadSpool,
1119 ),
1120 command(
1121 "adjust_spool",
1122 "/spools/{spool_id}/actions/adjust_spool",
1123 SpoolCommandKind::AdjustSpool,
1124 ),
1125 command(
1126 "retire_spool",
1127 "/spools/{spool_id}/actions/retire_spool",
1128 SpoolCommandKind::RetireSpool,
1129 ),
1130 read(RECOVERY_STATUS, "/printer/recovery"),
1133 recovery(
1134 "recover_lift",
1135 "/printer/recovery/recover_lift",
1136 RecoveryActionKind::RecoverLift,
1137 ),
1138 recovery(
1139 "recover_cool",
1140 "/printer/recovery/recover_cool",
1141 RecoveryActionKind::RecoverCool,
1142 ),
1143 recovery(
1144 "recover_fan",
1145 "/printer/recovery/recover_fan",
1146 RecoveryActionKind::RecoverFan,
1147 ),
1148 recovery(
1149 "recover_heat",
1150 "/printer/recovery/recover_heat",
1151 RecoveryActionKind::RecoverHeat,
1152 ),
1153 recovery(
1154 "recover_park",
1155 "/printer/recovery/recover_park",
1156 RecoveryActionKind::RecoverPark,
1157 ),
1158 recovery(
1159 "recover_home_xy",
1160 "/printer/recovery/recover_home_xy",
1161 RecoveryActionKind::RecoverHomeXy,
1162 ),
1163 recovery(
1164 "recover_home_z",
1165 "/printer/recovery/recover_home_z",
1166 RecoveryActionKind::RecoverHomeZ,
1167 ),
1168 Operation {
1172 name: BED_CLEAR,
1173 method: Method::Post,
1174 path: "/printer/bed_clear",
1175 effect: Effect::Write,
1176 accepts: Some(MEDIA_TYPE),
1177 answers: MEDIA_TYPE,
1178 query: &[],
1179 body: &[
1180 Declared {
1181 shape: Some("Actor"),
1182 ..Declared::once("actor", true, ValueKind::Structured)
1183 },
1184 Declared::once("reason", true, ValueKind::Text),
1185 ],
1186 image_path_field: None,
1187 printer_wide: None,
1188 mints_print: false,
1189 },
1190 Operation {
1194 name: RECHECK_CAMERA,
1195 method: Method::Post,
1196 path: "/prints/{print_id}/camera/recheck",
1197 effect: Effect::Write,
1198 accepts: Some(MEDIA_TYPE),
1199 answers: MEDIA_TYPE,
1200 query: &[],
1201 body: &[
1202 Declared {
1203 shape: Some("Actor"),
1204 ..Declared::once("actor", true, ValueKind::Structured)
1205 },
1206 Declared::once("reason", true, ValueKind::Text),
1207 ],
1208 image_path_field: Some(RECHECK_FRAME_PATH_FIELD),
1209 printer_wide: None,
1210 mints_print: false,
1211 },
1212 Operation {
1216 name: CHECK_CAMERA,
1217 method: Method::Get,
1218 path: "/camera/check",
1219 effect: Effect::Read,
1220 accepts: None,
1221 answers: MEDIA_TYPE,
1222 query: &[
1223 Declared {
1224 shape: Some("SheetId"),
1225 ..Declared::once("sheet", true, ValueKind::Text)
1226 },
1227 Declared::once("bed_z_mm", true, ValueKind::Number),
1228 ],
1229 body: &[],
1230 image_path_field: Some(CAMERA_CHECK_IMAGE_FIELD),
1231 printer_wide: None,
1232 mints_print: false,
1233 },
1234 read(CHECK_HARNESS, "/harness/check"),
1239];
1240
1241pub const BED_CLEAR: &str = "bed_clear";
1244
1245pub const RECHECK_CAMERA: &str = "recheck_camera";
1247
1248pub const CHECK_HARNESS: &str = "check_harness";
1250
1251pub const RECHECK_FRAME_PATH_FIELD: &str = "frame_path";
1253
1254pub const CHECK_CAMERA: &str = "check_camera";
1256
1257pub const CAMERA_CHECK_IMAGE_FIELD: &str = "image_path";
1259
1260pub const RECOVERY_STATUS: &str = "recover_status";
1263
1264pub const BESIDE_THE_ACTIONS: [&str; 18] = [
1278 "prints",
1279 "status",
1280 "context",
1281 "image",
1282 "history",
1283 "events",
1284 "manifest_get",
1285 "look",
1286 PRINTER_LOOK,
1287 "manifest_set",
1288 "spools",
1289 "spool",
1290 "printer_history",
1291 "preflight",
1292 BED_CLEAR,
1293 RECHECK_CAMERA,
1294 CHECK_CAMERA,
1295 CHECK_HARNESS,
1296];
1297
1298pub const PRINTER_LOOK: &str = "printer_look";
1301
1302const PRINTER_LOOK_OPERATION: Operation = Operation {
1309 query: &[Declared::once("wait_s", false, ValueKind::Integer)],
1310 image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
1311 ..read(PRINTER_LOOK, "/look")
1312};
1313
1314#[must_use]
1317pub fn printer_wide_of(name: &str) -> Option<&'static Operation> {
1318 OPERATIONS
1319 .iter()
1320 .find(|declared| declared.printer_wide.is_some_and(|wide| wide.name == name))
1321}
1322
1323#[must_use]
1325pub fn operation(name: &str) -> Option<&'static Operation> {
1326 OPERATIONS.iter().find(|declared| declared.name == name)
1327}
1328
1329#[cfg(test)]
1330mod tests {
1331 use printobserver_core::ActionKind;
1332
1333 use super::{Effect, MEDIA_TYPE, Method, OPERATIONS, VERSION_PREFIX, operation};
1334
1335 #[test]
1337 fn every_method_is_spelled_as_the_wire_spells_it() {
1338 for (method, spelling) in [
1339 (Method::Get, "GET"),
1340 (Method::Post, "POST"),
1341 (Method::Put, "PUT"),
1342 ] {
1343 assert_eq!(method.as_str(), spelling);
1344 assert_eq!(method.to_string(), spelling);
1345 }
1346 }
1347
1348 #[test]
1350 fn every_operation_sits_beneath_the_one_versioned_prefix() {
1351 for declared in OPERATIONS {
1352 let whole = declared.full_path();
1353 assert!(
1354 whole.starts_with(VERSION_PREFIX),
1355 "`{}` is served at {whole}",
1356 declared.name
1357 );
1358 assert_eq!(declared.answers, MEDIA_TYPE);
1359 }
1360 }
1361
1362 #[test]
1364 fn a_mutating_operation_names_its_action_and_a_read_names_none() {
1365 for declared in OPERATIONS {
1366 match declared.effect {
1367 Effect::Mutating(kind) => {
1368 assert_eq!(declared.action_kind(), Some(kind));
1369 assert_eq!(declared.command_kind(), None);
1370 assert_eq!(declared.granted_as(), Some(kind));
1371 assert!(declared.is_mutating());
1372 }
1373 Effect::Command(kind) => {
1374 assert_eq!(declared.action_kind(), None);
1375 assert_eq!(declared.command_kind(), Some(kind.action_kind()));
1376 assert_eq!(declared.granted_as(), Some(kind.action_kind()));
1377 assert!(declared.is_mutating());
1378 }
1379 Effect::Recovery(kind) => {
1380 assert_eq!(declared.action_kind(), None);
1381 assert_eq!(declared.granted_as(), None);
1382 assert_eq!(declared.recovery_kind(), Some(kind));
1383 assert!(declared.is_mutating());
1384 }
1385 Effect::Write => {
1386 assert_eq!(declared.action_kind(), None);
1387 assert!(
1388 declared.is_mutating(),
1389 "`{}` writes a record and is not held to the reason every \
1390 change carries",
1391 declared.name
1392 );
1393 }
1394 Effect::Read => {
1395 assert_eq!(declared.action_kind(), None);
1396 assert!(!declared.is_mutating());
1397 }
1398 }
1399 }
1400 }
1401
1402 #[test]
1407 fn a_mutating_operation_takes_a_body_and_a_read_takes_none() {
1408 let mutating = super::action(
1409 "pause",
1410 "/prints/{print_id}/actions/pause",
1411 ActionKind::Pause,
1412 );
1413 assert_eq!(mutating.method, Method::Post);
1414 assert_eq!(mutating.accepts, Some(MEDIA_TYPE));
1415 assert_eq!(mutating.answers, MEDIA_TYPE);
1416 assert_eq!(mutating.action_kind(), Some(ActionKind::Pause));
1417
1418 let reading = super::read("status", "/prints/{print_id}/status");
1419 assert_eq!(reading.method, Method::Get);
1420 assert_eq!(reading.accepts, None);
1421 assert_eq!(reading.answers, MEDIA_TYPE);
1422 assert_eq!(reading.effect, Effect::Read);
1423 }
1424
1425 #[test]
1428 fn a_spool_commands_body_is_its_fields_less_the_tag_and_the_routed_spool() {
1429 let load = operation("load_spool").expect("the load is served");
1430 let names: Vec<(String, super::Located)> = load
1431 .request()
1432 .into_iter()
1433 .map(|parameter| (parameter.name, parameter.located))
1434 .collect();
1435 assert_eq!(
1436 names,
1437 vec![
1438 ("spool_id".to_owned(), super::Located::Path),
1439 ("actor".to_owned(), super::Located::Body),
1440 ("reason".to_owned(), super::Located::Body),
1441 ("tool".to_owned(), super::Located::Body),
1442 ]
1443 );
1444 let register = operation("register_spool").expect("the registration is served");
1445 assert!(
1446 register
1447 .request()
1448 .iter()
1449 .all(|parameter| parameter.name != super::COMMAND_TAG
1450 && parameter.located == super::Located::Body)
1451 );
1452 }
1453
1454 #[test]
1458 fn the_ledgers_kinds_are_the_commands_the_contracts_declare() {
1459 let schema = super::Vocabulary::Commands.schema();
1460 let declared: Vec<String> = schema["oneOf"]
1461 .as_array()
1462 .expect("the spool vocabulary is a union")
1463 .iter()
1464 .filter_map(|variant| variant.pointer("/properties/command/const"))
1465 .filter_map(|tag| tag.as_str().map(str::to_owned))
1466 .collect();
1467 let kinds: Vec<String> = super::SpoolCommandKind::ALL
1468 .iter()
1469 .map(|kind| {
1470 printobserver_types::serde_json::to_value(kind.action_kind())
1471 .ok()
1472 .and_then(|tag| tag.as_str().map(str::to_owned))
1473 .expect("an action kind renders as its tag")
1474 })
1475 .collect();
1476 assert_eq!(kinds, declared);
1477 let served: Vec<super::SpoolCommandKind> = OPERATIONS
1478 .iter()
1479 .filter_map(|operation| match operation.effect {
1480 Effect::Command(kind) => Some(kind),
1481 _ => None,
1482 })
1483 .collect();
1484 assert_eq!(served, super::SpoolCommandKind::ALL.to_vec());
1485 }
1486
1487 #[test]
1489 fn a_repeated_value_is_described_as_a_list_of_its_kind() {
1490 let history = operation("printer_history").expect("the printer history is served");
1491 let kinds = history
1492 .request_shapes()
1493 .into_iter()
1494 .find(|(parameter, _)| parameter.name == "kinds")
1495 .expect("the history takes kinds");
1496 assert!(kinds.0.repeated);
1497 assert_eq!(
1498 kinds.1,
1499 printobserver_types::serde_json::json!({"type": "array", "items": {"type": "string"}})
1500 );
1501 }
1502
1503 #[test]
1506 fn a_recovery_actions_body_is_its_fields_beside_the_actor_and_the_reason() {
1507 let heat = operation("recover_heat").expect("the heat is served");
1508 let names: Vec<(String, bool, super::Located)> = heat
1509 .request()
1510 .into_iter()
1511 .map(|parameter| (parameter.name, parameter.required, parameter.located))
1512 .collect();
1513 assert_eq!(
1514 names,
1515 vec![
1516 ("actor".to_owned(), true, super::Located::Body),
1517 ("clearance_asserted".to_owned(), false, super::Located::Body),
1518 ("reason".to_owned(), true, super::Located::Body),
1519 ("target_c".to_owned(), true, super::Located::Body),
1520 ("tool".to_owned(), true, super::Located::Body),
1521 ]
1522 );
1523 let cool = operation("recover_cool").expect("the cool is served");
1524 let names: Vec<String> = cool
1525 .request()
1526 .into_iter()
1527 .map(|parameter| parameter.name)
1528 .collect();
1529 assert_eq!(names, vec!["actor".to_owned(), "reason".to_owned()]);
1530 let served: Vec<super::RecoveryActionKind> = OPERATIONS
1531 .iter()
1532 .filter_map(super::Operation::recovery_kind)
1533 .collect();
1534 assert_eq!(served, super::RecoveryActionKind::ALL.to_vec());
1535 }
1536
1537 #[test]
1541 fn a_printer_wide_form_takes_its_prints_values_less_the_print() {
1542 let mut forms = 0;
1543 for declared in OPERATIONS {
1544 let Some(wide) = declared.printer_wide else {
1545 continue;
1546 };
1547 forms += 1;
1548 assert_eq!(
1549 operation(wide.name),
1550 Some(wide),
1551 "the printer-wide form is not an operation this server serves"
1552 );
1553 assert_eq!(wide.method, declared.method, "`{}`", declared.name);
1554 assert_eq!(wide.effect, declared.effect, "`{}`", declared.name);
1555 assert_eq!(wide.image_path_field, declared.image_path_field);
1556 assert_eq!(
1557 wide.printer_wide, None,
1558 "a printer-wide form has none of its own"
1559 );
1560 assert!(!wide.path.contains("{print_id}"), "`{}`", wide.name);
1561 let taken: Vec<super::Parameter> = declared
1562 .request()
1563 .into_iter()
1564 .filter(|parameter| parameter.name != "print_id")
1565 .collect();
1566 assert_eq!(wide.request(), taken, "`{}`", wide.name);
1567 assert_eq!(
1568 super::printer_wide_of(wide.name).map(|found| found.name),
1569 Some(declared.name)
1570 );
1571 }
1572 assert_eq!(
1573 forms, 1,
1574 "the look is the one read with a printer-wide form"
1575 );
1576 assert!(super::printer_wide_of("look").is_none());
1577 }
1578
1579 #[test]
1581 fn an_operation_this_server_does_not_serve_is_answered_as_none() {
1582 assert_eq!(operation("pause").map(|found| found.name), Some("pause"));
1583 assert!(operation("reboot").is_none());
1584 }
1585}