1use printobserver_types::serde_json::{Value, json};
52
53pub use printobserver_core::{
58 ActionKind, PrintAction, RecoveryAction, RecoveryActionKind, SpoolCommand,
59};
60
61pub const VERSION_PREFIX: &str = "/v1";
63
64pub const MEDIA_TYPE: &str = "application/json";
66
67pub const INGRESS_PATH: &str = "/obico/webhook";
70
71pub const CONTEXT_IMAGE_PATH_FIELD: &str = "image_path";
73
74pub const IMAGE_PATH_FIELD: &str = "path";
76
77const ACTION_TAG: &str = "action";
80
81pub const COMMAND_TAG: &str = "command";
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
87pub enum Method {
88 Get,
90 Post,
92 Put,
94}
95
96impl Method {
97 #[must_use]
99 pub const fn as_str(self) -> &'static str {
100 match self {
101 Self::Get => "GET",
102 Self::Post => "POST",
103 Self::Put => "PUT",
104 }
105 }
106}
107
108impl core::fmt::Display for Method {
109 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
110 formatter.write_str(self.as_str())
111 }
112}
113
114#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
116pub enum Located {
117 Path,
119 Query,
121 Body,
123}
124
125#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
132pub enum ValueKind {
133 Text,
135 Number,
137 Integer,
139 Boolean,
141 Structured,
143}
144
145impl ValueKind {
146 #[must_use]
148 pub const fn structured(self) -> bool {
149 matches!(self, Self::Structured)
150 }
151}
152
153#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
159pub struct Declared {
160 pub name: &'static str,
162 pub required: bool,
164 pub kind: ValueKind,
166 pub shape: Option<&'static str>,
173 pub repeated: bool,
176}
177
178impl Declared {
179 #[must_use]
181 pub const fn once(name: &'static str, required: bool, kind: ValueKind) -> Self {
182 Self {
183 name,
184 required,
185 kind,
186 shape: None,
187 repeated: false,
188 }
189 }
190}
191
192#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
194pub struct Parameter {
195 pub name: String,
197 pub required: bool,
199 pub located: Located,
201 pub kind: ValueKind,
203 pub repeated: bool,
205}
206
207#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
209pub enum Answer {
210 Success,
212 Rejected,
214}
215
216impl Answer {
217 #[must_use]
219 pub const fn as_str(self) -> &'static str {
220 match self {
221 Self::Success => "success",
222 Self::Rejected => "rejected",
223 }
224 }
225}
226
227impl core::fmt::Display for Answer {
228 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
229 formatter.write_str(self.as_str())
230 }
231}
232
233#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
235pub enum Effect {
236 Read,
238 Mutating(ActionKind),
240 Command(SpoolCommandKind),
244 Recovery(RecoveryActionKind),
248 Write,
250}
251
252#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
259pub enum SpoolCommandKind {
260 RegisterSpool,
262 LoadSpool,
264 UnloadSpool,
266 AdjustSpool,
268 RetireSpool,
270}
271
272impl SpoolCommandKind {
273 pub const ALL: [Self; 5] = [
275 Self::RegisterSpool,
276 Self::LoadSpool,
277 Self::UnloadSpool,
278 Self::AdjustSpool,
279 Self::RetireSpool,
280 ];
281
282 #[must_use]
284 pub const fn action_kind(self) -> ActionKind {
285 match self {
286 Self::RegisterSpool => ActionKind::RegisterSpool,
287 Self::LoadSpool => ActionKind::LoadSpool,
288 Self::UnloadSpool => ActionKind::UnloadSpool,
289 Self::AdjustSpool => ActionKind::AdjustSpool,
290 Self::RetireSpool => ActionKind::RetireSpool,
291 }
292 }
293}
294
295#[derive(Debug, Clone, Copy, PartialEq, Eq)]
297pub struct Operation {
298 pub name: &'static str,
301 pub method: Method,
303 pub path: &'static str,
305 pub effect: Effect,
307 pub accepts: Option<&'static str>,
309 pub answers: &'static str,
311 pub query: &'static [Declared],
313 pub body: &'static [Declared],
318 pub image_path_field: Option<&'static str>,
327}
328
329impl Operation {
330 #[must_use]
332 pub fn full_path(&self) -> String {
333 format!("{VERSION_PREFIX}{}", self.path)
334 }
335
336 #[must_use]
338 pub const fn action_kind(&self) -> Option<ActionKind> {
339 match self.effect {
340 Effect::Mutating(kind) => Some(kind),
341 _ => None,
342 }
343 }
344
345 #[must_use]
347 pub const fn command_kind(&self) -> Option<ActionKind> {
348 match self.effect {
349 Effect::Command(kind) => Some(kind.action_kind()),
350 _ => None,
351 }
352 }
353
354 #[must_use]
357 pub const fn granted_as(&self) -> Option<ActionKind> {
358 match self.effect {
359 Effect::Mutating(kind) => Some(kind),
360 Effect::Command(kind) => Some(kind.action_kind()),
361 Effect::Read | Effect::Write | Effect::Recovery(_) => None,
362 }
363 }
364
365 #[must_use]
368 pub const fn recovery_kind(&self) -> Option<RecoveryActionKind> {
369 match self.effect {
370 Effect::Recovery(kind) => Some(kind),
371 _ => None,
372 }
373 }
374
375 #[must_use]
382 pub const fn is_mutating(&self) -> bool {
383 matches!(
384 self.effect,
385 Effect::Mutating(_) | Effect::Command(_) | Effect::Recovery(_) | Effect::Write
386 )
387 }
388
389 #[must_use]
404 pub fn request(&self) -> Vec<Parameter> {
405 let mut found = path_parameters(self.path);
406 found.extend(declared(self.query, Located::Query));
407 match Vocabulary::of(self.effect) {
408 Some((vocabulary, kind)) => {
409 let routed: Vec<String> = found.iter().map(|path| path.name.clone()).collect();
410 found.extend(
411 action_parameters(vocabulary, &kind)
412 .into_iter()
413 .filter(|field| !routed.contains(&field.name)),
414 );
415 }
416 None => found.extend(declared(self.body, Located::Body)),
417 }
418 found
419 }
420
421 #[must_use]
439 pub fn request_shapes(&self) -> Vec<(Parameter, Value)> {
440 let action = match Vocabulary::of(self.effect) {
441 Some((vocabulary, kind)) => action_shapes(vocabulary, &kind),
442 None => Vec::new(),
443 };
444 self.request()
445 .into_iter()
446 .map(|parameter| {
447 let shape = match parameter.located {
448 Located::Path => json!({ "type": "string" }),
451 Located::Query => declared_shape(self.query, ¶meter.name),
452 Located::Body if action.is_empty() => {
453 declared_shape(self.body, ¶meter.name)
454 }
455 Located::Body => action
456 .iter()
457 .find(|(name, _)| *name == parameter.name)
458 .map_or_else(
459 || {
460 panic!(
461 "`{}` takes `{}` in its body, and the action it names \
462 declares no such field",
463 self.name, parameter.name
464 )
465 },
466 |(_, shape)| shape.clone(),
467 ),
468 };
469 (parameter, shape)
470 })
471 .collect()
472 }
473
474 #[must_use]
481 pub const fn answers_with(&self) -> &'static [Answer] {
482 match self.effect {
483 Effect::Mutating(_) | Effect::Command(_) | Effect::Recovery(_) => {
484 &[Answer::Success, Answer::Rejected]
485 }
486 Effect::Read | Effect::Write => &[Answer::Success],
487 }
488 }
489
490 #[must_use]
501 pub fn response_schema(&self, answer: Answer) -> Value {
502 use printobserver_types::schemars::schema_for;
503 debug_assert!(
504 self.answers_with().contains(&answer),
505 "`{}` produces no {answer} answer",
506 self.name
507 );
508 let schema = match (self.name, self.effect) {
509 (_, Effect::Mutating(_)) => schema_for!(crate::wire::ActionAnswer),
510 (_, Effect::Command(_)) => schema_for!(crate::wire::SpoolCommandAnswer),
511 (_, Effect::Recovery(_)) => schema_for!(crate::wire::RecoveryAnswer),
512 (RECOVERY_STATUS, _) => schema_for!(crate::wire::RecoveryStatusAnswer),
513 ("spools", _) => schema_for!(crate::wire::SpoolsAnswer),
514 ("spool", _) => schema_for!(crate::wire::SpoolAnswer),
515 ("printer_history", _) => schema_for!(crate::wire::TimelineAnswer),
516 ("preflight", _) => schema_for!(crate::wire::PreflightAnswer),
517 ("prints", _) => schema_for!(crate::wire::PrintsAnswer),
518 ("status", _) => schema_for!(crate::wire::StatusAnswer),
519 ("context", _) => schema_for!(crate::wire::ContextAnswer),
520 ("image", _) => schema_for!(crate::wire::ImageAnswer),
521 ("history", _) => schema_for!(crate::wire::HistoryAnswer),
522 ("events", _) => schema_for!(crate::wire::EventsAnswer),
523 ("look", _) => schema_for!(crate::wire::LookAnswer),
524 ("manifest_get" | "manifest_set", _) => schema_for!(crate::wire::ManifestAnswer),
525 (name, _) => panic!("the operation `{name}` has no declared answer shape"),
526 };
527 schema.to_value()
528 }
529}
530
531fn declared(entries: &'static [Declared], located: Located) -> impl Iterator<Item = Parameter> {
533 entries.iter().map(move |entry| Parameter {
534 name: entry.name.to_owned(),
535 required: entry.required,
536 located,
537 kind: entry.kind,
538 repeated: entry.repeated,
539 })
540}
541
542fn declared_shape(entries: &'static [Declared], name: &str) -> Value {
548 let Some(entry) = entries.iter().find(|entry| entry.name == name) else {
549 return json!({ "type": "string" });
550 };
551 let one = if let Some(shape) = entry.shape {
552 json!({ "$ref": format!("#/$defs/{shape}") })
553 } else {
554 match entry.kind {
555 ValueKind::Text => json!({ "type": "string" }),
556 ValueKind::Number => json!({ "type": "number" }),
557 ValueKind::Integer => json!({ "type": "integer" }),
558 ValueKind::Boolean => json!({ "type": "boolean" }),
559 ValueKind::Structured => json!({ "type": "object" }),
560 }
561 };
562 if entry.repeated {
565 json!({ "type": "array", "items": one })
566 } else {
567 one
568 }
569}
570
571#[derive(Debug, Clone, Copy, PartialEq, Eq)]
574enum Vocabulary {
575 Actions,
577 Commands,
579 Recovery,
582}
583
584impl Vocabulary {
585 fn of(effect: Effect) -> Option<(Self, String)> {
587 let tag = |kind: ActionKind| {
588 printobserver_types::serde_json::to_value(kind)
589 .ok()
590 .and_then(|value| value.as_str().map(str::to_owned))
591 .unwrap_or_else(|| panic!("`{kind:?}` renders as the tag it is spelled by"))
592 };
593 match effect {
594 Effect::Mutating(kind) => Some((Self::Actions, tag(kind))),
595 Effect::Command(kind) => Some((Self::Commands, tag(kind.action_kind()))),
596 Effect::Recovery(kind) => Some((Self::Recovery, kind.as_str().to_owned())),
597 Effect::Read | Effect::Write => None,
598 }
599 }
600
601 const fn tag(self) -> &'static str {
603 match self {
604 Self::Actions | Self::Recovery => ACTION_TAG,
605 Self::Commands => COMMAND_TAG,
606 }
607 }
608
609 fn schema(self) -> Value {
615 use printobserver_types::schemars::schema_for;
616 match self {
617 Self::Actions => schema_for!(PrintAction).to_value(),
618 Self::Commands => schema_for!(SpoolCommand).to_value(),
619 Self::Recovery => recovery_request_schema(),
620 }
621 }
622}
623
624fn recovery_request_schema() -> Value {
627 use printobserver_types::schemars::schema_for;
628 let mut schema = schema_for!(RecoveryAction).to_value();
629 let actor = schema_for!(printobserver_core::Actor).to_value();
630 if let Some(variants) = schema.get_mut("oneOf").and_then(Value::as_array_mut) {
631 for variant in variants {
632 if let Some(properties) = variant.get_mut("properties").and_then(Value::as_object_mut) {
633 properties.insert(
634 "actor".to_owned(),
635 json!({ "$ref": "#/$defs/Actor", "description": "Who is asking." }),
636 );
637 properties.insert(
638 "reason".to_owned(),
639 json!({ "type": "string", "description": "Why the actor is asking for this." }),
640 );
641 }
642 if let Some(required) = variant.get_mut("required").and_then(Value::as_array_mut) {
643 required.push(json!("actor"));
644 required.push(json!("reason"));
645 }
646 }
647 }
648 let defs = schema
649 .as_object_mut()
650 .map(|top| top.entry("$defs").or_insert_with(|| json!({})));
651 if let Some(Value::Object(defs)) = defs {
652 if let Some(Value::Object(nested)) = actor.get("$defs") {
653 for (name, shape) in nested {
654 defs.insert(name.clone(), shape.clone());
655 }
656 }
657 let mut own = actor.clone();
658 if let Some(top) = own.as_object_mut() {
659 top.remove("$defs");
660 top.remove("$schema");
661 }
662 defs.insert("Actor".to_owned(), own);
663 }
664 schema
665}
666
667fn action_shapes(vocabulary: Vocabulary, kind: &str) -> Vec<(String, Value)> {
678 let schema = vocabulary.schema();
679 let variant = action_variant(&schema, vocabulary, kind);
680 variant
681 .get("properties")
682 .and_then(Value::as_object)
683 .unwrap_or_else(|| panic!("the action `{kind}` declares no properties"))
684 .iter()
685 .filter(|(name, _)| name.as_str() != vocabulary.tag())
686 .map(|(name, field)| (name.clone(), field.clone()))
687 .collect()
688}
689
690fn action_variant(schema: &Value, vocabulary: Vocabulary, tag: &str) -> Value {
697 schema
698 .get("oneOf")
699 .and_then(Value::as_array)
700 .and_then(|variants| {
701 variants.iter().find(|variant| {
702 variant.pointer(&format!("/properties/{}/const", vocabulary.tag()))
703 == Some(&json!(tag))
704 })
705 })
706 .cloned()
707 .unwrap_or_else(|| panic!("the contracts declare no action tagged `{tag}`"))
708}
709
710fn path_parameters(path: &str) -> Vec<Parameter> {
712 path.split('/')
713 .filter_map(|segment| segment.strip_prefix('{')?.strip_suffix('}'))
714 .map(|name| Parameter {
715 name: name.to_owned(),
716 required: true,
719 located: Located::Path,
720 kind: ValueKind::Text,
723 repeated: false,
724 })
725 .collect()
726}
727
728fn action_parameters(vocabulary: Vocabulary, kind: &str) -> Vec<Parameter> {
735 let schema = vocabulary.schema();
736 let variant = action_variant(&schema, vocabulary, kind);
737 let required: Vec<&str> = variant
738 .get("required")
739 .and_then(Value::as_array)
740 .map(|names| names.iter().filter_map(Value::as_str).collect())
741 .unwrap_or_default();
742 let properties = variant
743 .get("properties")
744 .and_then(Value::as_object)
745 .unwrap_or_else(|| panic!("the action `{kind}` declares no properties"));
746 properties
747 .iter()
748 .filter(|(name, _)| name.as_str() != vocabulary.tag())
749 .map(|(name, field)| Parameter {
750 name: name.clone(),
751 required: required.contains(&name.as_str()),
752 located: Located::Body,
753 kind: kind_of(&resolve(&schema, field)),
754 repeated: false,
755 })
756 .collect()
757}
758
759fn resolve(schema: &Value, field: &Value) -> Value {
761 let Some(reference) = field.get("$ref").and_then(Value::as_str) else {
762 return field.clone();
763 };
764 reference
765 .strip_prefix("#/")
766 .and_then(|rest| schema.pointer(&format!("/{rest}")))
767 .cloned()
768 .unwrap_or_else(|| field.clone())
769}
770
771fn kind_of(shape: &Value) -> ValueKind {
779 if let Some(declared) = shape.get("type") {
780 let named = |name: &str| match declared {
781 Value::String(one) => one == name,
782 Value::Array(many) => many.iter().any(|one| one == name),
783 _ => false,
784 };
785 if named("object") || named("array") {
786 return ValueKind::Structured;
787 }
788 if named("string") {
789 return ValueKind::Text;
790 }
791 if named("integer") {
792 return ValueKind::Integer;
793 }
794 if named("number") {
795 return ValueKind::Number;
796 }
797 if named("boolean") {
798 return ValueKind::Boolean;
799 }
800 }
801 match shape.get("oneOf").or_else(|| shape.get("anyOf")) {
802 Some(Value::Array(branches)) if !branches.is_empty() => {
803 let kinds: Vec<ValueKind> = branches
804 .iter()
805 .map(|branch| match branch.get("const") {
806 Some(Value::String(_)) => ValueKind::Text,
807 _ => kind_of(branch),
808 })
809 .collect();
810 let first = kinds[0];
811 if kinds.iter().all(|kind| *kind == first) {
812 first
813 } else {
814 ValueKind::Structured
815 }
816 }
817 _ => ValueKind::Structured,
818 }
819}
820
821const fn action(name: &'static str, path: &'static str, kind: ActionKind) -> Operation {
823 Operation {
824 name,
825 method: Method::Post,
826 path,
827 effect: Effect::Mutating(kind),
828 accepts: Some(MEDIA_TYPE),
829 answers: MEDIA_TYPE,
830 query: &[],
831 body: &[],
832 image_path_field: None,
833 }
834}
835
836const fn command(name: &'static str, path: &'static str, kind: SpoolCommandKind) -> Operation {
838 Operation {
839 effect: Effect::Command(kind),
840 ..action(name, path, kind.action_kind())
841 }
842}
843
844const fn recovery(name: &'static str, path: &'static str, kind: RecoveryActionKind) -> Operation {
846 Operation {
847 name,
848 method: Method::Post,
849 path,
850 effect: Effect::Recovery(kind),
851 accepts: Some(MEDIA_TYPE),
852 answers: MEDIA_TYPE,
853 query: &[],
854 body: &[],
855 image_path_field: None,
856 }
857}
858
859const fn read(name: &'static str, path: &'static str) -> Operation {
861 Operation {
862 name,
863 method: Method::Get,
864 path,
865 effect: Effect::Read,
866 accepts: None,
867 answers: MEDIA_TYPE,
868 query: &[],
869 body: &[],
870 image_path_field: None,
871 }
872}
873
874#[must_use]
881pub fn command_for(operation: &str) -> String {
882 operation.replace('_', "-")
883}
884
885pub const OPERATIONS: [Operation; 37] = [
887 read("prints", "/prints"),
891 read("status", "/prints/{print_id}/status"),
892 Operation {
893 image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
894 ..read("context", "/prints/{print_id}/context")
895 },
896 Operation {
897 image_path_field: Some(IMAGE_PATH_FIELD),
898 ..read("image", "/images/{image_id}")
899 },
900 Operation {
901 query: &[Declared::once("limit", false, ValueKind::Integer)],
902 ..read("history", "/prints/{print_id}/history")
903 },
904 Operation {
908 query: &[
909 Declared::once("after", false, ValueKind::Text),
910 Declared::once("print_id", false, ValueKind::Text),
911 Declared {
912 repeated: true,
913 ..Declared::once("kinds", false, ValueKind::Text)
914 },
915 Declared {
916 repeated: true,
917 ..Declared::once("exclude_kinds", false, ValueKind::Text)
918 },
919 Declared::once("wait_s", false, ValueKind::Integer),
920 Declared::once("limit", false, ValueKind::Integer),
921 ],
922 ..read("events", "/events")
923 },
924 read("manifest_get", "/prints/{print_id}/manifest"),
925 Operation {
929 query: &[Declared::once("wait_s", false, ValueKind::Integer)],
930 image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
931 ..read("look", "/prints/{print_id}/look")
932 },
933 Operation {
934 name: "manifest_set",
935 method: Method::Put,
936 path: "/prints/{print_id}/manifest",
937 effect: Effect::Write,
938 accepts: Some(MEDIA_TYPE),
939 answers: MEDIA_TYPE,
940 query: &[],
941 body: &[
942 Declared::once("reason", true, ValueKind::Text),
943 Declared {
944 shape: Some("JobManifest"),
945 ..Declared::once("manifest", true, ValueKind::Structured)
946 },
947 ],
948 image_path_field: None,
949 },
950 Operation {
954 query: &[Declared::once("include_retired", false, ValueKind::Boolean)],
955 ..read("spools", "/spools")
956 },
957 read("spool", "/spools/{spool_id}"),
958 Operation {
962 query: &[
963 Declared {
964 repeated: true,
965 ..Declared::once("kinds", false, ValueKind::Text)
966 },
967 Declared::once("since", false, ValueKind::Text),
968 Declared::once("until", false, ValueKind::Text),
969 Declared::once("spool_id", false, ValueKind::Text),
970 Declared::once("before", false, ValueKind::Text),
971 Declared::once("limit", false, ValueKind::Integer),
972 ],
973 ..read("printer_history", "/history")
974 },
975 Operation {
978 query: &[Declared::once("file_name", true, ValueKind::Text)],
979 ..read("preflight", "/preflight")
980 },
981 action(
982 "pause",
983 "/prints/{print_id}/actions/pause",
984 ActionKind::Pause,
985 ),
986 action(
987 "resume",
988 "/prints/{print_id}/actions/resume",
989 ActionKind::Resume,
990 ),
991 action(
992 "cancel",
993 "/prints/{print_id}/actions/cancel",
994 ActionKind::Cancel,
995 ),
996 action(
997 "start_print",
998 "/prints/{print_id}/actions/start_print",
999 ActionKind::StartPrint,
1000 ),
1001 action(
1002 "set_feedrate_factor",
1003 "/prints/{print_id}/actions/set_feedrate_factor",
1004 ActionKind::SetFeedrateFactor,
1005 ),
1006 action(
1007 "set_flowrate_factor",
1008 "/prints/{print_id}/actions/set_flowrate_factor",
1009 ActionKind::SetFlowrateFactor,
1010 ),
1011 action(
1012 "set_tool_target_c",
1013 "/prints/{print_id}/actions/set_tool_target_c",
1014 ActionKind::SetToolTargetC,
1015 ),
1016 action(
1017 "set_bed_target_c",
1018 "/prints/{print_id}/actions/set_bed_target_c",
1019 ActionKind::SetBedTargetC,
1020 ),
1021 action(
1022 "set_fan_percent",
1023 "/prints/{print_id}/actions/set_fan_percent",
1024 ActionKind::SetFanPercent,
1025 ),
1026 action(
1027 "acknowledge_failure",
1028 "/prints/{print_id}/actions/acknowledge_failure",
1029 ActionKind::AcknowledgeFailure,
1030 ),
1031 action(
1033 "close_print",
1034 "/prints/{print_id}/actions/close_print",
1035 ActionKind::ClosePrint,
1036 ),
1037 command(
1038 "register_spool",
1039 "/spools/actions/register_spool",
1040 SpoolCommandKind::RegisterSpool,
1041 ),
1042 command(
1043 "load_spool",
1044 "/spools/{spool_id}/actions/load_spool",
1045 SpoolCommandKind::LoadSpool,
1046 ),
1047 command(
1048 "unload_spool",
1049 "/spools/{spool_id}/actions/unload_spool",
1050 SpoolCommandKind::UnloadSpool,
1051 ),
1052 command(
1053 "adjust_spool",
1054 "/spools/{spool_id}/actions/adjust_spool",
1055 SpoolCommandKind::AdjustSpool,
1056 ),
1057 command(
1058 "retire_spool",
1059 "/spools/{spool_id}/actions/retire_spool",
1060 SpoolCommandKind::RetireSpool,
1061 ),
1062 read(RECOVERY_STATUS, "/printer/recovery"),
1065 recovery(
1066 "recover_lift",
1067 "/printer/recovery/recover_lift",
1068 RecoveryActionKind::RecoverLift,
1069 ),
1070 recovery(
1071 "recover_cool",
1072 "/printer/recovery/recover_cool",
1073 RecoveryActionKind::RecoverCool,
1074 ),
1075 recovery(
1076 "recover_fan",
1077 "/printer/recovery/recover_fan",
1078 RecoveryActionKind::RecoverFan,
1079 ),
1080 recovery(
1081 "recover_heat",
1082 "/printer/recovery/recover_heat",
1083 RecoveryActionKind::RecoverHeat,
1084 ),
1085 recovery(
1086 "recover_park",
1087 "/printer/recovery/recover_park",
1088 RecoveryActionKind::RecoverPark,
1089 ),
1090 recovery(
1091 "recover_home_xy",
1092 "/printer/recovery/recover_home_xy",
1093 RecoveryActionKind::RecoverHomeXy,
1094 ),
1095 recovery(
1096 "recover_home_z",
1097 "/printer/recovery/recover_home_z",
1098 RecoveryActionKind::RecoverHomeZ,
1099 ),
1100];
1101
1102pub const RECOVERY_STATUS: &str = "recover_status";
1105
1106pub const BESIDE_THE_ACTIONS: [&str; 13] = [
1114 "prints",
1115 "status",
1116 "context",
1117 "image",
1118 "history",
1119 "events",
1120 "manifest_get",
1121 "look",
1122 "manifest_set",
1123 "spools",
1124 "spool",
1125 "printer_history",
1126 "preflight",
1127];
1128
1129#[must_use]
1131pub fn operation(name: &str) -> Option<&'static Operation> {
1132 OPERATIONS.iter().find(|declared| declared.name == name)
1133}
1134
1135#[cfg(test)]
1136mod tests {
1137 use printobserver_core::ActionKind;
1138
1139 use super::{Effect, MEDIA_TYPE, Method, OPERATIONS, VERSION_PREFIX, operation};
1140
1141 #[test]
1143 fn every_method_is_spelled_as_the_wire_spells_it() {
1144 for (method, spelling) in [
1145 (Method::Get, "GET"),
1146 (Method::Post, "POST"),
1147 (Method::Put, "PUT"),
1148 ] {
1149 assert_eq!(method.as_str(), spelling);
1150 assert_eq!(method.to_string(), spelling);
1151 }
1152 }
1153
1154 #[test]
1156 fn every_operation_sits_beneath_the_one_versioned_prefix() {
1157 for declared in OPERATIONS {
1158 let whole = declared.full_path();
1159 assert!(
1160 whole.starts_with(VERSION_PREFIX),
1161 "`{}` is served at {whole}",
1162 declared.name
1163 );
1164 assert_eq!(declared.answers, MEDIA_TYPE);
1165 }
1166 }
1167
1168 #[test]
1170 fn a_mutating_operation_names_its_action_and_a_read_names_none() {
1171 for declared in OPERATIONS {
1172 match declared.effect {
1173 Effect::Mutating(kind) => {
1174 assert_eq!(declared.action_kind(), Some(kind));
1175 assert_eq!(declared.command_kind(), None);
1176 assert_eq!(declared.granted_as(), Some(kind));
1177 assert!(declared.is_mutating());
1178 }
1179 Effect::Command(kind) => {
1180 assert_eq!(declared.action_kind(), None);
1181 assert_eq!(declared.command_kind(), Some(kind.action_kind()));
1182 assert_eq!(declared.granted_as(), Some(kind.action_kind()));
1183 assert!(declared.is_mutating());
1184 }
1185 Effect::Recovery(kind) => {
1186 assert_eq!(declared.action_kind(), None);
1187 assert_eq!(declared.granted_as(), None);
1188 assert_eq!(declared.recovery_kind(), Some(kind));
1189 assert!(declared.is_mutating());
1190 }
1191 Effect::Write => {
1192 assert_eq!(declared.action_kind(), None);
1193 assert!(
1194 declared.is_mutating(),
1195 "`{}` writes a record and is not held to the reason every \
1196 change carries",
1197 declared.name
1198 );
1199 }
1200 Effect::Read => {
1201 assert_eq!(declared.action_kind(), None);
1202 assert!(!declared.is_mutating());
1203 }
1204 }
1205 }
1206 }
1207
1208 #[test]
1213 fn a_mutating_operation_takes_a_body_and_a_read_takes_none() {
1214 let mutating = super::action(
1215 "pause",
1216 "/prints/{print_id}/actions/pause",
1217 ActionKind::Pause,
1218 );
1219 assert_eq!(mutating.method, Method::Post);
1220 assert_eq!(mutating.accepts, Some(MEDIA_TYPE));
1221 assert_eq!(mutating.answers, MEDIA_TYPE);
1222 assert_eq!(mutating.action_kind(), Some(ActionKind::Pause));
1223
1224 let reading = super::read("status", "/prints/{print_id}/status");
1225 assert_eq!(reading.method, Method::Get);
1226 assert_eq!(reading.accepts, None);
1227 assert_eq!(reading.answers, MEDIA_TYPE);
1228 assert_eq!(reading.effect, Effect::Read);
1229 }
1230
1231 #[test]
1234 fn a_spool_commands_body_is_its_fields_less_the_tag_and_the_routed_spool() {
1235 let load = operation("load_spool").expect("the load is served");
1236 let names: Vec<(String, super::Located)> = load
1237 .request()
1238 .into_iter()
1239 .map(|parameter| (parameter.name, parameter.located))
1240 .collect();
1241 assert_eq!(
1242 names,
1243 vec![
1244 ("spool_id".to_owned(), super::Located::Path),
1245 ("actor".to_owned(), super::Located::Body),
1246 ("reason".to_owned(), super::Located::Body),
1247 ("tool".to_owned(), super::Located::Body),
1248 ]
1249 );
1250 let register = operation("register_spool").expect("the registration is served");
1251 assert!(
1252 register
1253 .request()
1254 .iter()
1255 .all(|parameter| parameter.name != super::COMMAND_TAG
1256 && parameter.located == super::Located::Body)
1257 );
1258 }
1259
1260 #[test]
1264 fn the_ledgers_kinds_are_the_commands_the_contracts_declare() {
1265 let schema = super::Vocabulary::Commands.schema();
1266 let declared: Vec<String> = schema["oneOf"]
1267 .as_array()
1268 .expect("the spool vocabulary is a union")
1269 .iter()
1270 .filter_map(|variant| variant.pointer("/properties/command/const"))
1271 .filter_map(|tag| tag.as_str().map(str::to_owned))
1272 .collect();
1273 let kinds: Vec<String> = super::SpoolCommandKind::ALL
1274 .iter()
1275 .map(|kind| {
1276 printobserver_types::serde_json::to_value(kind.action_kind())
1277 .ok()
1278 .and_then(|tag| tag.as_str().map(str::to_owned))
1279 .expect("an action kind renders as its tag")
1280 })
1281 .collect();
1282 assert_eq!(kinds, declared);
1283 let served: Vec<super::SpoolCommandKind> = OPERATIONS
1284 .iter()
1285 .filter_map(|operation| match operation.effect {
1286 Effect::Command(kind) => Some(kind),
1287 _ => None,
1288 })
1289 .collect();
1290 assert_eq!(served, super::SpoolCommandKind::ALL.to_vec());
1291 }
1292
1293 #[test]
1295 fn a_repeated_value_is_described_as_a_list_of_its_kind() {
1296 let history = operation("printer_history").expect("the printer history is served");
1297 let kinds = history
1298 .request_shapes()
1299 .into_iter()
1300 .find(|(parameter, _)| parameter.name == "kinds")
1301 .expect("the history takes kinds");
1302 assert!(kinds.0.repeated);
1303 assert_eq!(
1304 kinds.1,
1305 printobserver_types::serde_json::json!({"type": "array", "items": {"type": "string"}})
1306 );
1307 }
1308
1309 #[test]
1312 fn a_recovery_actions_body_is_its_fields_beside_the_actor_and_the_reason() {
1313 let heat = operation("recover_heat").expect("the heat is served");
1314 let names: Vec<(String, bool, super::Located)> = heat
1315 .request()
1316 .into_iter()
1317 .map(|parameter| (parameter.name, parameter.required, parameter.located))
1318 .collect();
1319 assert_eq!(
1320 names,
1321 vec![
1322 ("actor".to_owned(), true, super::Located::Body),
1323 ("clearance_asserted".to_owned(), false, super::Located::Body),
1324 ("reason".to_owned(), true, super::Located::Body),
1325 ("target_c".to_owned(), true, super::Located::Body),
1326 ("tool".to_owned(), true, super::Located::Body),
1327 ]
1328 );
1329 let cool = operation("recover_cool").expect("the cool is served");
1330 let names: Vec<String> = cool
1331 .request()
1332 .into_iter()
1333 .map(|parameter| parameter.name)
1334 .collect();
1335 assert_eq!(names, vec!["actor".to_owned(), "reason".to_owned()]);
1336 let served: Vec<super::RecoveryActionKind> = OPERATIONS
1337 .iter()
1338 .filter_map(super::Operation::recovery_kind)
1339 .collect();
1340 assert_eq!(served, super::RecoveryActionKind::ALL.to_vec());
1341 }
1342
1343 #[test]
1345 fn an_operation_this_server_does_not_serve_is_answered_as_none() {
1346 assert_eq!(operation("pause").map(|found| found.name), Some("pause"));
1347 assert!(operation("reboot").is_none());
1348 }
1349}