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