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 {
916 image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
917 ..read("context", "/prints/{print_id}/context")
918 },
919 Operation {
920 image_path_field: Some(IMAGE_PATH_FIELD),
921 ..read("image", "/images/{image_id}")
922 },
923 Operation {
924 query: &[Declared::once("limit", false, ValueKind::Integer)],
925 ..read("history", "/prints/{print_id}/history")
926 },
927 Operation {
931 query: &[
932 Declared::once("after", false, ValueKind::Text),
933 Declared::once("print_id", false, ValueKind::Text),
934 Declared {
935 repeated: true,
936 ..Declared::once("kinds", false, ValueKind::Text)
937 },
938 Declared {
939 repeated: true,
940 ..Declared::once("exclude_kinds", false, ValueKind::Text)
941 },
942 Declared::once("wait_s", false, ValueKind::Integer),
943 Declared::once("limit", false, ValueKind::Integer),
944 ],
945 ..read("events", "/events")
946 },
947 read("manifest_get", "/prints/{print_id}/manifest"),
948 Operation {
953 query: &[Declared::once("wait_s", false, ValueKind::Integer)],
954 image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
955 printer_wide: Some(&PRINTER_LOOK_OPERATION),
956 ..read("look", "/prints/{print_id}/look")
957 },
958 PRINTER_LOOK_OPERATION,
959 Operation {
960 name: "manifest_set",
961 method: Method::Put,
962 path: "/prints/{print_id}/manifest",
963 effect: Effect::Write,
964 accepts: Some(MEDIA_TYPE),
965 answers: MEDIA_TYPE,
966 query: &[],
967 body: &[
968 Declared::once("reason", true, ValueKind::Text),
969 Declared {
970 shape: Some("JobManifest"),
971 ..Declared::once("manifest", true, ValueKind::Structured)
972 },
973 ],
974 image_path_field: None,
975 printer_wide: None,
976 },
977 Operation {
981 query: &[Declared::once("include_retired", false, ValueKind::Boolean)],
982 ..read("spools", "/spools")
983 },
984 read("spool", "/spools/{spool_id}"),
985 Operation {
989 query: &[
990 Declared {
991 repeated: true,
992 ..Declared::once("kinds", false, ValueKind::Text)
993 },
994 Declared::once("since", false, ValueKind::Text),
995 Declared::once("until", false, ValueKind::Text),
996 Declared::once("spool_id", false, ValueKind::Text),
997 Declared::once("before", false, ValueKind::Text),
998 Declared::once("limit", false, ValueKind::Integer),
999 ],
1000 ..read("printer_history", "/history")
1001 },
1002 Operation {
1006 query: &[
1007 Declared::once("file_name", true, ValueKind::Text),
1008 Declared {
1010 shape: Some("SheetId"),
1011 ..Declared::once("sheet", false, ValueKind::Text)
1012 },
1013 ],
1014 ..read("preflight", "/preflight")
1015 },
1016 action(
1017 "pause",
1018 "/prints/{print_id}/actions/pause",
1019 ActionKind::Pause,
1020 ),
1021 action(
1022 "resume",
1023 "/prints/{print_id}/actions/resume",
1024 ActionKind::Resume,
1025 ),
1026 action(
1027 "cancel",
1028 "/prints/{print_id}/actions/cancel",
1029 ActionKind::Cancel,
1030 ),
1031 action(
1032 "start_print",
1033 "/prints/{print_id}/actions/start_print",
1034 ActionKind::StartPrint,
1035 ),
1036 action(
1037 "set_feedrate_factor",
1038 "/prints/{print_id}/actions/set_feedrate_factor",
1039 ActionKind::SetFeedrateFactor,
1040 ),
1041 action(
1042 "set_flowrate_factor",
1043 "/prints/{print_id}/actions/set_flowrate_factor",
1044 ActionKind::SetFlowrateFactor,
1045 ),
1046 action(
1047 "set_tool_target_c",
1048 "/prints/{print_id}/actions/set_tool_target_c",
1049 ActionKind::SetToolTargetC,
1050 ),
1051 action(
1052 "set_bed_target_c",
1053 "/prints/{print_id}/actions/set_bed_target_c",
1054 ActionKind::SetBedTargetC,
1055 ),
1056 action(
1057 "set_fan_percent",
1058 "/prints/{print_id}/actions/set_fan_percent",
1059 ActionKind::SetFanPercent,
1060 ),
1061 action(
1062 "acknowledge_failure",
1063 "/prints/{print_id}/actions/acknowledge_failure",
1064 ActionKind::AcknowledgeFailure,
1065 ),
1066 action(
1068 "close_print",
1069 "/prints/{print_id}/actions/close_print",
1070 ActionKind::ClosePrint,
1071 ),
1072 command(
1073 "register_spool",
1074 "/spools/actions/register_spool",
1075 SpoolCommandKind::RegisterSpool,
1076 ),
1077 command(
1078 "load_spool",
1079 "/spools/{spool_id}/actions/load_spool",
1080 SpoolCommandKind::LoadSpool,
1081 ),
1082 command(
1083 "unload_spool",
1084 "/spools/{spool_id}/actions/unload_spool",
1085 SpoolCommandKind::UnloadSpool,
1086 ),
1087 command(
1088 "adjust_spool",
1089 "/spools/{spool_id}/actions/adjust_spool",
1090 SpoolCommandKind::AdjustSpool,
1091 ),
1092 command(
1093 "retire_spool",
1094 "/spools/{spool_id}/actions/retire_spool",
1095 SpoolCommandKind::RetireSpool,
1096 ),
1097 read(RECOVERY_STATUS, "/printer/recovery"),
1100 recovery(
1101 "recover_lift",
1102 "/printer/recovery/recover_lift",
1103 RecoveryActionKind::RecoverLift,
1104 ),
1105 recovery(
1106 "recover_cool",
1107 "/printer/recovery/recover_cool",
1108 RecoveryActionKind::RecoverCool,
1109 ),
1110 recovery(
1111 "recover_fan",
1112 "/printer/recovery/recover_fan",
1113 RecoveryActionKind::RecoverFan,
1114 ),
1115 recovery(
1116 "recover_heat",
1117 "/printer/recovery/recover_heat",
1118 RecoveryActionKind::RecoverHeat,
1119 ),
1120 recovery(
1121 "recover_park",
1122 "/printer/recovery/recover_park",
1123 RecoveryActionKind::RecoverPark,
1124 ),
1125 recovery(
1126 "recover_home_xy",
1127 "/printer/recovery/recover_home_xy",
1128 RecoveryActionKind::RecoverHomeXy,
1129 ),
1130 recovery(
1131 "recover_home_z",
1132 "/printer/recovery/recover_home_z",
1133 RecoveryActionKind::RecoverHomeZ,
1134 ),
1135];
1136
1137pub const RECOVERY_STATUS: &str = "recover_status";
1140
1141pub const BESIDE_THE_ACTIONS: [&str; 14] = [
1150 "prints",
1151 "status",
1152 "context",
1153 "image",
1154 "history",
1155 "events",
1156 "manifest_get",
1157 "look",
1158 PRINTER_LOOK,
1159 "manifest_set",
1160 "spools",
1161 "spool",
1162 "printer_history",
1163 "preflight",
1164];
1165
1166pub const PRINTER_LOOK: &str = "printer_look";
1169
1170const PRINTER_LOOK_OPERATION: Operation = Operation {
1177 query: &[Declared::once("wait_s", false, ValueKind::Integer)],
1178 image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
1179 ..read(PRINTER_LOOK, "/look")
1180};
1181
1182#[must_use]
1185pub fn printer_wide_of(name: &str) -> Option<&'static Operation> {
1186 OPERATIONS
1187 .iter()
1188 .find(|declared| declared.printer_wide.is_some_and(|wide| wide.name == name))
1189}
1190
1191#[must_use]
1193pub fn operation(name: &str) -> Option<&'static Operation> {
1194 OPERATIONS.iter().find(|declared| declared.name == name)
1195}
1196
1197#[cfg(test)]
1198mod tests {
1199 use printobserver_core::ActionKind;
1200
1201 use super::{Effect, MEDIA_TYPE, Method, OPERATIONS, VERSION_PREFIX, operation};
1202
1203 #[test]
1205 fn every_method_is_spelled_as_the_wire_spells_it() {
1206 for (method, spelling) in [
1207 (Method::Get, "GET"),
1208 (Method::Post, "POST"),
1209 (Method::Put, "PUT"),
1210 ] {
1211 assert_eq!(method.as_str(), spelling);
1212 assert_eq!(method.to_string(), spelling);
1213 }
1214 }
1215
1216 #[test]
1218 fn every_operation_sits_beneath_the_one_versioned_prefix() {
1219 for declared in OPERATIONS {
1220 let whole = declared.full_path();
1221 assert!(
1222 whole.starts_with(VERSION_PREFIX),
1223 "`{}` is served at {whole}",
1224 declared.name
1225 );
1226 assert_eq!(declared.answers, MEDIA_TYPE);
1227 }
1228 }
1229
1230 #[test]
1232 fn a_mutating_operation_names_its_action_and_a_read_names_none() {
1233 for declared in OPERATIONS {
1234 match declared.effect {
1235 Effect::Mutating(kind) => {
1236 assert_eq!(declared.action_kind(), Some(kind));
1237 assert_eq!(declared.command_kind(), None);
1238 assert_eq!(declared.granted_as(), Some(kind));
1239 assert!(declared.is_mutating());
1240 }
1241 Effect::Command(kind) => {
1242 assert_eq!(declared.action_kind(), None);
1243 assert_eq!(declared.command_kind(), Some(kind.action_kind()));
1244 assert_eq!(declared.granted_as(), Some(kind.action_kind()));
1245 assert!(declared.is_mutating());
1246 }
1247 Effect::Recovery(kind) => {
1248 assert_eq!(declared.action_kind(), None);
1249 assert_eq!(declared.granted_as(), None);
1250 assert_eq!(declared.recovery_kind(), Some(kind));
1251 assert!(declared.is_mutating());
1252 }
1253 Effect::Write => {
1254 assert_eq!(declared.action_kind(), None);
1255 assert!(
1256 declared.is_mutating(),
1257 "`{}` writes a record and is not held to the reason every \
1258 change carries",
1259 declared.name
1260 );
1261 }
1262 Effect::Read => {
1263 assert_eq!(declared.action_kind(), None);
1264 assert!(!declared.is_mutating());
1265 }
1266 }
1267 }
1268 }
1269
1270 #[test]
1275 fn a_mutating_operation_takes_a_body_and_a_read_takes_none() {
1276 let mutating = super::action(
1277 "pause",
1278 "/prints/{print_id}/actions/pause",
1279 ActionKind::Pause,
1280 );
1281 assert_eq!(mutating.method, Method::Post);
1282 assert_eq!(mutating.accepts, Some(MEDIA_TYPE));
1283 assert_eq!(mutating.answers, MEDIA_TYPE);
1284 assert_eq!(mutating.action_kind(), Some(ActionKind::Pause));
1285
1286 let reading = super::read("status", "/prints/{print_id}/status");
1287 assert_eq!(reading.method, Method::Get);
1288 assert_eq!(reading.accepts, None);
1289 assert_eq!(reading.answers, MEDIA_TYPE);
1290 assert_eq!(reading.effect, Effect::Read);
1291 }
1292
1293 #[test]
1296 fn a_spool_commands_body_is_its_fields_less_the_tag_and_the_routed_spool() {
1297 let load = operation("load_spool").expect("the load is served");
1298 let names: Vec<(String, super::Located)> = load
1299 .request()
1300 .into_iter()
1301 .map(|parameter| (parameter.name, parameter.located))
1302 .collect();
1303 assert_eq!(
1304 names,
1305 vec![
1306 ("spool_id".to_owned(), super::Located::Path),
1307 ("actor".to_owned(), super::Located::Body),
1308 ("reason".to_owned(), super::Located::Body),
1309 ("tool".to_owned(), super::Located::Body),
1310 ]
1311 );
1312 let register = operation("register_spool").expect("the registration is served");
1313 assert!(
1314 register
1315 .request()
1316 .iter()
1317 .all(|parameter| parameter.name != super::COMMAND_TAG
1318 && parameter.located == super::Located::Body)
1319 );
1320 }
1321
1322 #[test]
1326 fn the_ledgers_kinds_are_the_commands_the_contracts_declare() {
1327 let schema = super::Vocabulary::Commands.schema();
1328 let declared: Vec<String> = schema["oneOf"]
1329 .as_array()
1330 .expect("the spool vocabulary is a union")
1331 .iter()
1332 .filter_map(|variant| variant.pointer("/properties/command/const"))
1333 .filter_map(|tag| tag.as_str().map(str::to_owned))
1334 .collect();
1335 let kinds: Vec<String> = super::SpoolCommandKind::ALL
1336 .iter()
1337 .map(|kind| {
1338 printobserver_types::serde_json::to_value(kind.action_kind())
1339 .ok()
1340 .and_then(|tag| tag.as_str().map(str::to_owned))
1341 .expect("an action kind renders as its tag")
1342 })
1343 .collect();
1344 assert_eq!(kinds, declared);
1345 let served: Vec<super::SpoolCommandKind> = OPERATIONS
1346 .iter()
1347 .filter_map(|operation| match operation.effect {
1348 Effect::Command(kind) => Some(kind),
1349 _ => None,
1350 })
1351 .collect();
1352 assert_eq!(served, super::SpoolCommandKind::ALL.to_vec());
1353 }
1354
1355 #[test]
1357 fn a_repeated_value_is_described_as_a_list_of_its_kind() {
1358 let history = operation("printer_history").expect("the printer history is served");
1359 let kinds = history
1360 .request_shapes()
1361 .into_iter()
1362 .find(|(parameter, _)| parameter.name == "kinds")
1363 .expect("the history takes kinds");
1364 assert!(kinds.0.repeated);
1365 assert_eq!(
1366 kinds.1,
1367 printobserver_types::serde_json::json!({"type": "array", "items": {"type": "string"}})
1368 );
1369 }
1370
1371 #[test]
1374 fn a_recovery_actions_body_is_its_fields_beside_the_actor_and_the_reason() {
1375 let heat = operation("recover_heat").expect("the heat is served");
1376 let names: Vec<(String, bool, super::Located)> = heat
1377 .request()
1378 .into_iter()
1379 .map(|parameter| (parameter.name, parameter.required, parameter.located))
1380 .collect();
1381 assert_eq!(
1382 names,
1383 vec![
1384 ("actor".to_owned(), true, super::Located::Body),
1385 ("clearance_asserted".to_owned(), false, super::Located::Body),
1386 ("reason".to_owned(), true, super::Located::Body),
1387 ("target_c".to_owned(), true, super::Located::Body),
1388 ("tool".to_owned(), true, super::Located::Body),
1389 ]
1390 );
1391 let cool = operation("recover_cool").expect("the cool is served");
1392 let names: Vec<String> = cool
1393 .request()
1394 .into_iter()
1395 .map(|parameter| parameter.name)
1396 .collect();
1397 assert_eq!(names, vec!["actor".to_owned(), "reason".to_owned()]);
1398 let served: Vec<super::RecoveryActionKind> = OPERATIONS
1399 .iter()
1400 .filter_map(super::Operation::recovery_kind)
1401 .collect();
1402 assert_eq!(served, super::RecoveryActionKind::ALL.to_vec());
1403 }
1404
1405 #[test]
1409 fn a_printer_wide_form_takes_its_prints_values_less_the_print() {
1410 let mut forms = 0;
1411 for declared in OPERATIONS {
1412 let Some(wide) = declared.printer_wide else {
1413 continue;
1414 };
1415 forms += 1;
1416 assert_eq!(
1417 operation(wide.name),
1418 Some(wide),
1419 "the printer-wide form is not an operation this server serves"
1420 );
1421 assert_eq!(wide.method, declared.method, "`{}`", declared.name);
1422 assert_eq!(wide.effect, declared.effect, "`{}`", declared.name);
1423 assert_eq!(wide.image_path_field, declared.image_path_field);
1424 assert_eq!(
1425 wide.printer_wide, None,
1426 "a printer-wide form has none of its own"
1427 );
1428 assert!(!wide.path.contains("{print_id}"), "`{}`", wide.name);
1429 let taken: Vec<super::Parameter> = declared
1430 .request()
1431 .into_iter()
1432 .filter(|parameter| parameter.name != "print_id")
1433 .collect();
1434 assert_eq!(wide.request(), taken, "`{}`", wide.name);
1435 assert_eq!(
1436 super::printer_wide_of(wide.name).map(|found| found.name),
1437 Some(declared.name)
1438 );
1439 }
1440 assert_eq!(
1441 forms, 1,
1442 "the look is the one read with a printer-wide form"
1443 );
1444 assert!(super::printer_wide_of("look").is_none());
1445 }
1446
1447 #[test]
1449 fn an_operation_this_server_does_not_serve_is_answered_as_none() {
1450 assert_eq!(operation("pause").map(|found| found.name), Some("pause"));
1451 assert!(operation("reboot").is_none());
1452 }
1453}