use printobserver_types::serde_json::{Value, json};
pub use printobserver_core::{
ActionKind, PrintAction, RecoveryAction, RecoveryActionKind, SpoolCommand,
};
pub const VERSION_PREFIX: &str = "/v1";
pub const MEDIA_TYPE: &str = "application/json";
pub const INGRESS_PATH: &str = "/obico/webhook";
pub const CONTEXT_IMAGE_PATH_FIELD: &str = "image_path";
pub const IMAGE_PATH_FIELD: &str = "path";
const ACTION_TAG: &str = "action";
pub const COMMAND_TAG: &str = "command";
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Method {
Get,
Post,
Put,
}
impl Method {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Get => "GET",
Self::Post => "POST",
Self::Put => "PUT",
}
}
}
impl core::fmt::Display for Method {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Located {
Path,
Query,
Body,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ValueKind {
Text,
Number,
Integer,
Boolean,
Structured,
}
impl ValueKind {
#[must_use]
pub const fn structured(self) -> bool {
matches!(self, Self::Structured)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Declared {
pub name: &'static str,
pub required: bool,
pub kind: ValueKind,
pub shape: Option<&'static str>,
pub repeated: bool,
}
impl Declared {
#[must_use]
pub const fn once(name: &'static str, required: bool, kind: ValueKind) -> Self {
Self {
name,
required,
kind,
shape: None,
repeated: false,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Parameter {
pub name: String,
pub required: bool,
pub located: Located,
pub kind: ValueKind,
pub repeated: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Answer {
Success,
Rejected,
}
impl Answer {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Success => "success",
Self::Rejected => "rejected",
}
}
}
impl core::fmt::Display for Answer {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Effect {
Read,
Mutating(ActionKind),
Command(SpoolCommandKind),
Recovery(RecoveryActionKind),
Write,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum SpoolCommandKind {
RegisterSpool,
LoadSpool,
UnloadSpool,
AdjustSpool,
RetireSpool,
}
impl SpoolCommandKind {
pub const ALL: [Self; 5] = [
Self::RegisterSpool,
Self::LoadSpool,
Self::UnloadSpool,
Self::AdjustSpool,
Self::RetireSpool,
];
#[must_use]
pub const fn action_kind(self) -> ActionKind {
match self {
Self::RegisterSpool => ActionKind::RegisterSpool,
Self::LoadSpool => ActionKind::LoadSpool,
Self::UnloadSpool => ActionKind::UnloadSpool,
Self::AdjustSpool => ActionKind::AdjustSpool,
Self::RetireSpool => ActionKind::RetireSpool,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Operation {
pub name: &'static str,
pub method: Method,
pub path: &'static str,
pub effect: Effect,
pub accepts: Option<&'static str>,
pub answers: &'static str,
pub query: &'static [Declared],
pub body: &'static [Declared],
pub image_path_field: Option<&'static str>,
pub printer_wide: Option<&'static Operation>,
pub mints_print: bool,
}
impl Operation {
#[must_use]
pub fn full_path(&self) -> String {
format!("{VERSION_PREFIX}{}", self.path)
}
#[must_use]
pub const fn action_kind(&self) -> Option<ActionKind> {
match self.effect {
Effect::Mutating(kind) => Some(kind),
_ => None,
}
}
#[must_use]
pub const fn command_kind(&self) -> Option<ActionKind> {
match self.effect {
Effect::Command(kind) => Some(kind.action_kind()),
_ => None,
}
}
#[must_use]
pub const fn granted_as(&self) -> Option<ActionKind> {
match self.effect {
Effect::Mutating(kind) => Some(kind),
Effect::Command(kind) => Some(kind.action_kind()),
Effect::Read | Effect::Write | Effect::Recovery(_) => None,
}
}
#[must_use]
pub const fn recovery_kind(&self) -> Option<RecoveryActionKind> {
match self.effect {
Effect::Recovery(kind) => Some(kind),
_ => None,
}
}
#[must_use]
pub const fn is_mutating(&self) -> bool {
matches!(
self.effect,
Effect::Mutating(_) | Effect::Command(_) | Effect::Recovery(_) | Effect::Write
)
}
#[must_use]
pub fn request(&self) -> Vec<Parameter> {
let mut found = path_parameters(self.path);
found.extend(declared(self.query, Located::Query));
match Vocabulary::of(self.effect) {
Some((vocabulary, kind)) => {
let routed: Vec<String> = found.iter().map(|path| path.name.clone()).collect();
found.extend(
action_parameters(vocabulary, &kind)
.into_iter()
.filter(|field| !routed.contains(&field.name)),
);
}
None => found.extend(declared(self.body, Located::Body)),
}
found
}
#[must_use]
pub fn request_shapes(&self) -> Vec<(Parameter, Value)> {
let action = match Vocabulary::of(self.effect) {
Some((vocabulary, kind)) => action_shapes(vocabulary, &kind),
None => Vec::new(),
};
self.request()
.into_iter()
.map(|parameter| {
let shape = match parameter.located {
Located::Path => json!({ "type": "string" }),
Located::Query => declared_shape(self.query, ¶meter.name),
Located::Body if action.is_empty() => {
declared_shape(self.body, ¶meter.name)
}
Located::Body => action
.iter()
.find(|(name, _)| *name == parameter.name)
.map_or_else(
|| {
panic!(
"`{}` takes `{}` in its body, and the action it names \
declares no such field",
self.name, parameter.name
)
},
|(_, shape)| shape.clone(),
),
};
(parameter, shape)
})
.collect()
}
#[must_use]
pub const fn answers_with(&self) -> &'static [Answer] {
match self.effect {
Effect::Mutating(_) | Effect::Command(_) | Effect::Recovery(_) => {
&[Answer::Success, Answer::Rejected]
}
Effect::Read | Effect::Write => &[Answer::Success],
}
}
#[must_use]
pub fn response_schema(&self, answer: Answer) -> Value {
use printobserver_types::schemars::schema_for;
debug_assert!(
self.answers_with().contains(&answer),
"`{}` produces no {answer} answer",
self.name
);
let schema = match (self.name, self.effect) {
(_, Effect::Mutating(_)) => schema_for!(crate::wire::ActionAnswer),
(_, Effect::Command(_)) => schema_for!(crate::wire::SpoolCommandAnswer),
(_, Effect::Recovery(_)) => schema_for!(crate::wire::RecoveryAnswer),
(RECOVERY_STATUS, _) => schema_for!(crate::wire::RecoveryStatusAnswer),
("spools", _) => schema_for!(crate::wire::SpoolsAnswer),
("spool", _) => schema_for!(crate::wire::SpoolAnswer),
("printer_history", _) => schema_for!(crate::wire::TimelineAnswer),
("preflight", _) => schema_for!(crate::wire::PreflightAnswer),
("prints", _) => schema_for!(crate::wire::PrintsAnswer),
("status", _) => schema_for!(crate::wire::StatusAnswer),
("context", _) => schema_for!(crate::wire::ContextAnswer),
("image", _) => schema_for!(crate::wire::ImageAnswer),
("history", _) => schema_for!(crate::wire::HistoryAnswer),
("events", _) => schema_for!(crate::wire::EventsAnswer),
("look" | "printer_look", _) => schema_for!(crate::wire::LookAnswer),
("manifest_get" | "manifest_set", _) => schema_for!(crate::wire::ManifestAnswer),
(BED_CLEAR, _) => schema_for!(crate::wire::BedClearAnswer),
(RECHECK_CAMERA, _) => schema_for!(crate::wire::RecheckCameraAnswer),
(CHECK_CAMERA, _) => schema_for!(crate::camera_check::CameraCheck),
(CHECK_HARNESS, _) => schema_for!(crate::readiness::HarnessReadiness),
(name, _) => panic!("the operation `{name}` has no declared answer shape"),
};
schema.to_value()
}
}
fn declared(entries: &'static [Declared], located: Located) -> impl Iterator<Item = Parameter> {
entries.iter().map(move |entry| Parameter {
name: entry.name.to_owned(),
required: entry.required,
located,
kind: entry.kind,
repeated: entry.repeated,
})
}
fn declared_shape(entries: &'static [Declared], name: &str) -> Value {
let Some(entry) = entries.iter().find(|entry| entry.name == name) else {
return json!({ "type": "string" });
};
let one = if let Some(shape) = entry.shape {
json!({ "$ref": format!("#/$defs/{shape}") })
} else {
match entry.kind {
ValueKind::Text => json!({ "type": "string" }),
ValueKind::Number => json!({ "type": "number" }),
ValueKind::Integer => json!({ "type": "integer" }),
ValueKind::Boolean => json!({ "type": "boolean" }),
ValueKind::Structured => json!({ "type": "object" }),
}
};
if entry.repeated {
json!({ "type": "array", "items": one })
} else {
one
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Vocabulary {
Actions,
Commands,
Recovery,
}
impl Vocabulary {
fn of(effect: Effect) -> Option<(Self, String)> {
let tag = |kind: ActionKind| {
printobserver_types::serde_json::to_value(kind)
.ok()
.and_then(|value| value.as_str().map(str::to_owned))
.unwrap_or_else(|| panic!("`{kind:?}` renders as the tag it is spelled by"))
};
match effect {
Effect::Mutating(kind) => Some((Self::Actions, tag(kind))),
Effect::Command(kind) => Some((Self::Commands, tag(kind.action_kind()))),
Effect::Recovery(kind) => Some((Self::Recovery, kind.as_str().to_owned())),
Effect::Read | Effect::Write => None,
}
}
const fn tag(self) -> &'static str {
match self {
Self::Actions | Self::Recovery => ACTION_TAG,
Self::Commands => COMMAND_TAG,
}
}
fn schema(self) -> Value {
use printobserver_types::schemars::schema_for;
match self {
Self::Actions => schema_for!(PrintAction).to_value(),
Self::Commands => schema_for!(SpoolCommand).to_value(),
Self::Recovery => recovery_request_schema(),
}
}
}
fn recovery_request_schema() -> Value {
use printobserver_types::schemars::schema_for;
let mut schema = schema_for!(RecoveryAction).to_value();
let actor = schema_for!(printobserver_core::Actor).to_value();
if let Some(variants) = schema.get_mut("oneOf").and_then(Value::as_array_mut) {
for variant in variants {
if let Some(properties) = variant.get_mut("properties").and_then(Value::as_object_mut) {
properties.insert(
"actor".to_owned(),
json!({ "$ref": "#/$defs/Actor", "description": "Who is asking." }),
);
properties.insert(
"reason".to_owned(),
json!({ "type": "string", "description": "Why the actor is asking for this." }),
);
}
if let Some(required) = variant.get_mut("required").and_then(Value::as_array_mut) {
required.push(json!("actor"));
required.push(json!("reason"));
}
}
}
let defs = schema
.as_object_mut()
.map(|top| top.entry("$defs").or_insert_with(|| json!({})));
if let Some(Value::Object(defs)) = defs {
if let Some(Value::Object(nested)) = actor.get("$defs") {
for (name, shape) in nested {
defs.insert(name.clone(), shape.clone());
}
}
let mut own = actor.clone();
if let Some(top) = own.as_object_mut() {
top.remove("$defs");
top.remove("$schema");
}
defs.insert("Actor".to_owned(), own);
}
schema
}
fn action_shapes(vocabulary: Vocabulary, kind: &str) -> Vec<(String, Value)> {
let schema = vocabulary.schema();
let variant = action_variant(&schema, vocabulary, kind);
variant
.get("properties")
.and_then(Value::as_object)
.unwrap_or_else(|| panic!("the action `{kind}` declares no properties"))
.iter()
.filter(|(name, _)| name.as_str() != vocabulary.tag())
.map(|(name, field)| (name.clone(), field.clone()))
.collect()
}
fn action_variant(schema: &Value, vocabulary: Vocabulary, tag: &str) -> Value {
schema
.get("oneOf")
.and_then(Value::as_array)
.and_then(|variants| {
variants.iter().find(|variant| {
variant.pointer(&format!("/properties/{}/const", vocabulary.tag()))
== Some(&json!(tag))
})
})
.cloned()
.unwrap_or_else(|| panic!("the contracts declare no action tagged `{tag}`"))
}
fn path_parameters(path: &str) -> Vec<Parameter> {
path.split('/')
.filter_map(|segment| segment.strip_prefix('{')?.strip_suffix('}'))
.map(|name| Parameter {
name: name.to_owned(),
required: true,
located: Located::Path,
kind: ValueKind::Text,
repeated: false,
})
.collect()
}
fn action_parameters(vocabulary: Vocabulary, kind: &str) -> Vec<Parameter> {
let schema = vocabulary.schema();
let variant = action_variant(&schema, vocabulary, kind);
let required: Vec<&str> = variant
.get("required")
.and_then(Value::as_array)
.map(|names| names.iter().filter_map(Value::as_str).collect())
.unwrap_or_default();
let properties = variant
.get("properties")
.and_then(Value::as_object)
.unwrap_or_else(|| panic!("the action `{kind}` declares no properties"));
properties
.iter()
.filter(|(name, _)| name.as_str() != vocabulary.tag())
.map(|(name, field)| Parameter {
name: name.clone(),
required: required.contains(&name.as_str()),
located: Located::Body,
kind: kind_of(&resolve(&schema, field)),
repeated: false,
})
.collect()
}
fn resolve(schema: &Value, field: &Value) -> Value {
let Some(reference) = field.get("$ref").and_then(Value::as_str) else {
return field.clone();
};
reference
.strip_prefix("#/")
.and_then(|rest| schema.pointer(&format!("/{rest}")))
.cloned()
.unwrap_or_else(|| field.clone())
}
fn kind_of(shape: &Value) -> ValueKind {
if let Some(declared) = shape.get("type") {
let named = |name: &str| match declared {
Value::String(one) => one == name,
Value::Array(many) => many.iter().any(|one| one == name),
_ => false,
};
if named("object") || named("array") {
return ValueKind::Structured;
}
if named("string") {
return ValueKind::Text;
}
if named("integer") {
return ValueKind::Integer;
}
if named("number") {
return ValueKind::Number;
}
if named("boolean") {
return ValueKind::Boolean;
}
}
match shape.get("oneOf").or_else(|| shape.get("anyOf")) {
Some(Value::Array(branches)) if !branches.is_empty() => {
let kinds: Vec<ValueKind> = branches
.iter()
.map(|branch| match branch.get("const") {
Some(Value::String(_)) => ValueKind::Text,
_ => kind_of(branch),
})
.collect();
let first = kinds[0];
if kinds.iter().all(|kind| *kind == first) {
first
} else {
ValueKind::Structured
}
}
_ => ValueKind::Structured,
}
}
const fn action(name: &'static str, path: &'static str, kind: ActionKind) -> Operation {
Operation {
name,
method: Method::Post,
path,
effect: Effect::Mutating(kind),
accepts: Some(MEDIA_TYPE),
answers: MEDIA_TYPE,
query: &[],
body: &[],
image_path_field: None,
printer_wide: None,
mints_print: false,
}
}
const fn command(name: &'static str, path: &'static str, kind: SpoolCommandKind) -> Operation {
Operation {
effect: Effect::Command(kind),
..action(name, path, kind.action_kind())
}
}
const fn recovery(name: &'static str, path: &'static str, kind: RecoveryActionKind) -> Operation {
Operation {
name,
method: Method::Post,
path,
effect: Effect::Recovery(kind),
accepts: Some(MEDIA_TYPE),
answers: MEDIA_TYPE,
query: &[],
body: &[],
image_path_field: None,
printer_wide: None,
mints_print: false,
}
}
const fn read(name: &'static str, path: &'static str) -> Operation {
Operation {
name,
method: Method::Get,
path,
effect: Effect::Read,
accepts: None,
answers: MEDIA_TYPE,
query: &[],
body: &[],
image_path_field: None,
printer_wide: None,
mints_print: false,
}
}
#[must_use]
pub fn command_for(operation: &str) -> String {
operation.replace('_', "-")
}
pub const OPERATIONS: [Operation; 42] = [
read("prints", "/prints"),
read("status", "/prints/{print_id}/status"),
Operation {
query: &[
Declared {
shape: Some("EventId"),
..Declared::once("since", false, ValueKind::Text)
},
],
image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
..read("context", "/prints/{print_id}/context")
},
Operation {
image_path_field: Some(IMAGE_PATH_FIELD),
..read("image", "/images/{image_id}")
},
Operation {
query: &[Declared::once("limit", false, ValueKind::Integer)],
..read("history", "/prints/{print_id}/history")
},
Operation {
query: &[
Declared::once("after", false, ValueKind::Text),
Declared::once("print_id", false, ValueKind::Text),
Declared {
repeated: true,
..Declared::once("kinds", false, ValueKind::Text)
},
Declared {
repeated: true,
..Declared::once("exclude_kinds", false, ValueKind::Text)
},
Declared::once("wait_s", false, ValueKind::Integer),
Declared::once("limit", false, ValueKind::Integer),
],
..read("events", "/events")
},
read("manifest_get", "/prints/{print_id}/manifest"),
Operation {
query: &[Declared::once("wait_s", false, ValueKind::Integer)],
image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
printer_wide: Some(&PRINTER_LOOK_OPERATION),
mints_print: false,
..read("look", "/prints/{print_id}/look")
},
PRINTER_LOOK_OPERATION,
Operation {
name: "manifest_set",
method: Method::Put,
path: "/prints/{print_id}/manifest",
effect: Effect::Write,
accepts: Some(MEDIA_TYPE),
answers: MEDIA_TYPE,
query: &[],
body: &[
Declared::once("reason", true, ValueKind::Text),
Declared {
shape: Some("JobManifest"),
..Declared::once("manifest", true, ValueKind::Structured)
},
],
image_path_field: None,
printer_wide: None,
mints_print: false,
},
Operation {
query: &[Declared::once("include_retired", false, ValueKind::Boolean)],
..read("spools", "/spools")
},
read("spool", "/spools/{spool_id}"),
Operation {
query: &[
Declared {
repeated: true,
..Declared::once("kinds", false, ValueKind::Text)
},
Declared::once("since", false, ValueKind::Text),
Declared::once("until", false, ValueKind::Text),
Declared::once("spool_id", false, ValueKind::Text),
Declared::once("before", false, ValueKind::Text),
Declared::once("limit", false, ValueKind::Integer),
],
..read("printer_history", "/history")
},
Operation {
query: &[
Declared::once("file_name", true, ValueKind::Text),
Declared {
shape: Some("SheetId"),
..Declared::once("sheet", false, ValueKind::Text)
},
],
..read("preflight", "/preflight")
},
action(
"pause",
"/prints/{print_id}/actions/pause",
ActionKind::Pause,
),
action(
"resume",
"/prints/{print_id}/actions/resume",
ActionKind::Resume,
),
action(
"cancel",
"/prints/{print_id}/actions/cancel",
ActionKind::Cancel,
),
Operation {
mints_print: true,
..action(
"start_print",
"/prints/{print_id}/actions/start_print",
ActionKind::StartPrint,
)
},
action(
"set_feedrate_factor",
"/prints/{print_id}/actions/set_feedrate_factor",
ActionKind::SetFeedrateFactor,
),
action(
"set_flowrate_factor",
"/prints/{print_id}/actions/set_flowrate_factor",
ActionKind::SetFlowrateFactor,
),
action(
"set_tool_target_c",
"/prints/{print_id}/actions/set_tool_target_c",
ActionKind::SetToolTargetC,
),
action(
"set_bed_target_c",
"/prints/{print_id}/actions/set_bed_target_c",
ActionKind::SetBedTargetC,
),
action(
"set_fan_percent",
"/prints/{print_id}/actions/set_fan_percent",
ActionKind::SetFanPercent,
),
action(
"acknowledge_failure",
"/prints/{print_id}/actions/acknowledge_failure",
ActionKind::AcknowledgeFailure,
),
action(
"close_print",
"/prints/{print_id}/actions/close_print",
ActionKind::ClosePrint,
),
command(
"register_spool",
"/spools/actions/register_spool",
SpoolCommandKind::RegisterSpool,
),
command(
"load_spool",
"/spools/{spool_id}/actions/load_spool",
SpoolCommandKind::LoadSpool,
),
command(
"unload_spool",
"/spools/{spool_id}/actions/unload_spool",
SpoolCommandKind::UnloadSpool,
),
command(
"adjust_spool",
"/spools/{spool_id}/actions/adjust_spool",
SpoolCommandKind::AdjustSpool,
),
command(
"retire_spool",
"/spools/{spool_id}/actions/retire_spool",
SpoolCommandKind::RetireSpool,
),
read(RECOVERY_STATUS, "/printer/recovery"),
recovery(
"recover_lift",
"/printer/recovery/recover_lift",
RecoveryActionKind::RecoverLift,
),
recovery(
"recover_cool",
"/printer/recovery/recover_cool",
RecoveryActionKind::RecoverCool,
),
recovery(
"recover_fan",
"/printer/recovery/recover_fan",
RecoveryActionKind::RecoverFan,
),
recovery(
"recover_heat",
"/printer/recovery/recover_heat",
RecoveryActionKind::RecoverHeat,
),
recovery(
"recover_park",
"/printer/recovery/recover_park",
RecoveryActionKind::RecoverPark,
),
recovery(
"recover_home_xy",
"/printer/recovery/recover_home_xy",
RecoveryActionKind::RecoverHomeXy,
),
recovery(
"recover_home_z",
"/printer/recovery/recover_home_z",
RecoveryActionKind::RecoverHomeZ,
),
Operation {
name: BED_CLEAR,
method: Method::Post,
path: "/printer/bed_clear",
effect: Effect::Write,
accepts: Some(MEDIA_TYPE),
answers: MEDIA_TYPE,
query: &[],
body: &[
Declared {
shape: Some("Actor"),
..Declared::once("actor", true, ValueKind::Structured)
},
Declared::once("reason", true, ValueKind::Text),
],
image_path_field: None,
printer_wide: None,
mints_print: false,
},
Operation {
name: RECHECK_CAMERA,
method: Method::Post,
path: "/prints/{print_id}/camera/recheck",
effect: Effect::Write,
accepts: Some(MEDIA_TYPE),
answers: MEDIA_TYPE,
query: &[],
body: &[
Declared {
shape: Some("Actor"),
..Declared::once("actor", true, ValueKind::Structured)
},
Declared::once("reason", true, ValueKind::Text),
],
image_path_field: Some(RECHECK_FRAME_PATH_FIELD),
printer_wide: None,
mints_print: false,
},
Operation {
name: CHECK_CAMERA,
method: Method::Get,
path: "/camera/check",
effect: Effect::Read,
accepts: None,
answers: MEDIA_TYPE,
query: &[
Declared {
shape: Some("SheetId"),
..Declared::once("sheet", true, ValueKind::Text)
},
Declared::once("bed_z_mm", true, ValueKind::Number),
],
body: &[],
image_path_field: Some(CAMERA_CHECK_IMAGE_FIELD),
printer_wide: None,
mints_print: false,
},
read(CHECK_HARNESS, "/harness/check"),
];
pub const BED_CLEAR: &str = "bed_clear";
pub const RECHECK_CAMERA: &str = "recheck_camera";
pub const CHECK_HARNESS: &str = "check_harness";
pub const RECHECK_FRAME_PATH_FIELD: &str = "frame_path";
pub const CHECK_CAMERA: &str = "check_camera";
pub const CAMERA_CHECK_IMAGE_FIELD: &str = "image_path";
pub const RECOVERY_STATUS: &str = "recover_status";
pub const BESIDE_THE_ACTIONS: [&str; 18] = [
"prints",
"status",
"context",
"image",
"history",
"events",
"manifest_get",
"look",
PRINTER_LOOK,
"manifest_set",
"spools",
"spool",
"printer_history",
"preflight",
BED_CLEAR,
RECHECK_CAMERA,
CHECK_CAMERA,
CHECK_HARNESS,
];
pub const PRINTER_LOOK: &str = "printer_look";
const PRINTER_LOOK_OPERATION: Operation = Operation {
query: &[Declared::once("wait_s", false, ValueKind::Integer)],
image_path_field: Some(CONTEXT_IMAGE_PATH_FIELD),
..read(PRINTER_LOOK, "/look")
};
#[must_use]
pub fn printer_wide_of(name: &str) -> Option<&'static Operation> {
OPERATIONS
.iter()
.find(|declared| declared.printer_wide.is_some_and(|wide| wide.name == name))
}
#[must_use]
pub fn operation(name: &str) -> Option<&'static Operation> {
OPERATIONS.iter().find(|declared| declared.name == name)
}
#[cfg(test)]
mod tests {
use printobserver_core::ActionKind;
use super::{Effect, MEDIA_TYPE, Method, OPERATIONS, VERSION_PREFIX, operation};
#[test]
fn every_method_is_spelled_as_the_wire_spells_it() {
for (method, spelling) in [
(Method::Get, "GET"),
(Method::Post, "POST"),
(Method::Put, "PUT"),
] {
assert_eq!(method.as_str(), spelling);
assert_eq!(method.to_string(), spelling);
}
}
#[test]
fn every_operation_sits_beneath_the_one_versioned_prefix() {
for declared in OPERATIONS {
let whole = declared.full_path();
assert!(
whole.starts_with(VERSION_PREFIX),
"`{}` is served at {whole}",
declared.name
);
assert_eq!(declared.answers, MEDIA_TYPE);
}
}
#[test]
fn a_mutating_operation_names_its_action_and_a_read_names_none() {
for declared in OPERATIONS {
match declared.effect {
Effect::Mutating(kind) => {
assert_eq!(declared.action_kind(), Some(kind));
assert_eq!(declared.command_kind(), None);
assert_eq!(declared.granted_as(), Some(kind));
assert!(declared.is_mutating());
}
Effect::Command(kind) => {
assert_eq!(declared.action_kind(), None);
assert_eq!(declared.command_kind(), Some(kind.action_kind()));
assert_eq!(declared.granted_as(), Some(kind.action_kind()));
assert!(declared.is_mutating());
}
Effect::Recovery(kind) => {
assert_eq!(declared.action_kind(), None);
assert_eq!(declared.granted_as(), None);
assert_eq!(declared.recovery_kind(), Some(kind));
assert!(declared.is_mutating());
}
Effect::Write => {
assert_eq!(declared.action_kind(), None);
assert!(
declared.is_mutating(),
"`{}` writes a record and is not held to the reason every \
change carries",
declared.name
);
}
Effect::Read => {
assert_eq!(declared.action_kind(), None);
assert!(!declared.is_mutating());
}
}
}
}
#[test]
fn a_mutating_operation_takes_a_body_and_a_read_takes_none() {
let mutating = super::action(
"pause",
"/prints/{print_id}/actions/pause",
ActionKind::Pause,
);
assert_eq!(mutating.method, Method::Post);
assert_eq!(mutating.accepts, Some(MEDIA_TYPE));
assert_eq!(mutating.answers, MEDIA_TYPE);
assert_eq!(mutating.action_kind(), Some(ActionKind::Pause));
let reading = super::read("status", "/prints/{print_id}/status");
assert_eq!(reading.method, Method::Get);
assert_eq!(reading.accepts, None);
assert_eq!(reading.answers, MEDIA_TYPE);
assert_eq!(reading.effect, Effect::Read);
}
#[test]
fn a_spool_commands_body_is_its_fields_less_the_tag_and_the_routed_spool() {
let load = operation("load_spool").expect("the load is served");
let names: Vec<(String, super::Located)> = load
.request()
.into_iter()
.map(|parameter| (parameter.name, parameter.located))
.collect();
assert_eq!(
names,
vec![
("spool_id".to_owned(), super::Located::Path),
("actor".to_owned(), super::Located::Body),
("reason".to_owned(), super::Located::Body),
("tool".to_owned(), super::Located::Body),
]
);
let register = operation("register_spool").expect("the registration is served");
assert!(
register
.request()
.iter()
.all(|parameter| parameter.name != super::COMMAND_TAG
&& parameter.located == super::Located::Body)
);
}
#[test]
fn the_ledgers_kinds_are_the_commands_the_contracts_declare() {
let schema = super::Vocabulary::Commands.schema();
let declared: Vec<String> = schema["oneOf"]
.as_array()
.expect("the spool vocabulary is a union")
.iter()
.filter_map(|variant| variant.pointer("/properties/command/const"))
.filter_map(|tag| tag.as_str().map(str::to_owned))
.collect();
let kinds: Vec<String> = super::SpoolCommandKind::ALL
.iter()
.map(|kind| {
printobserver_types::serde_json::to_value(kind.action_kind())
.ok()
.and_then(|tag| tag.as_str().map(str::to_owned))
.expect("an action kind renders as its tag")
})
.collect();
assert_eq!(kinds, declared);
let served: Vec<super::SpoolCommandKind> = OPERATIONS
.iter()
.filter_map(|operation| match operation.effect {
Effect::Command(kind) => Some(kind),
_ => None,
})
.collect();
assert_eq!(served, super::SpoolCommandKind::ALL.to_vec());
}
#[test]
fn a_repeated_value_is_described_as_a_list_of_its_kind() {
let history = operation("printer_history").expect("the printer history is served");
let kinds = history
.request_shapes()
.into_iter()
.find(|(parameter, _)| parameter.name == "kinds")
.expect("the history takes kinds");
assert!(kinds.0.repeated);
assert_eq!(
kinds.1,
printobserver_types::serde_json::json!({"type": "array", "items": {"type": "string"}})
);
}
#[test]
fn a_recovery_actions_body_is_its_fields_beside_the_actor_and_the_reason() {
let heat = operation("recover_heat").expect("the heat is served");
let names: Vec<(String, bool, super::Located)> = heat
.request()
.into_iter()
.map(|parameter| (parameter.name, parameter.required, parameter.located))
.collect();
assert_eq!(
names,
vec![
("actor".to_owned(), true, super::Located::Body),
("clearance_asserted".to_owned(), false, super::Located::Body),
("reason".to_owned(), true, super::Located::Body),
("target_c".to_owned(), true, super::Located::Body),
("tool".to_owned(), true, super::Located::Body),
]
);
let cool = operation("recover_cool").expect("the cool is served");
let names: Vec<String> = cool
.request()
.into_iter()
.map(|parameter| parameter.name)
.collect();
assert_eq!(names, vec!["actor".to_owned(), "reason".to_owned()]);
let served: Vec<super::RecoveryActionKind> = OPERATIONS
.iter()
.filter_map(super::Operation::recovery_kind)
.collect();
assert_eq!(served, super::RecoveryActionKind::ALL.to_vec());
}
#[test]
fn a_printer_wide_form_takes_its_prints_values_less_the_print() {
let mut forms = 0;
for declared in OPERATIONS {
let Some(wide) = declared.printer_wide else {
continue;
};
forms += 1;
assert_eq!(
operation(wide.name),
Some(wide),
"the printer-wide form is not an operation this server serves"
);
assert_eq!(wide.method, declared.method, "`{}`", declared.name);
assert_eq!(wide.effect, declared.effect, "`{}`", declared.name);
assert_eq!(wide.image_path_field, declared.image_path_field);
assert_eq!(
wide.printer_wide, None,
"a printer-wide form has none of its own"
);
assert!(!wide.path.contains("{print_id}"), "`{}`", wide.name);
let taken: Vec<super::Parameter> = declared
.request()
.into_iter()
.filter(|parameter| parameter.name != "print_id")
.collect();
assert_eq!(wide.request(), taken, "`{}`", wide.name);
assert_eq!(
super::printer_wide_of(wide.name).map(|found| found.name),
Some(declared.name)
);
}
assert_eq!(
forms, 1,
"the look is the one read with a printer-wide form"
);
assert!(super::printer_wide_of("look").is_none());
}
#[test]
fn an_operation_this_server_does_not_serve_is_answered_as_none() {
assert_eq!(operation("pause").map(|found| found.name), Some("pause"));
assert!(operation("reboot").is_none());
}
}