use printobserver_types::serde_json::{Value, json};
use printobserver_types::{ActionKind, PrintAction};
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";
#[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>,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Parameter {
pub name: String,
pub required: bool,
pub located: Located,
pub kind: ValueKind,
}
#[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),
Write,
}
#[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>,
}
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 is_mutating(&self) -> bool {
matches!(self.effect, Effect::Mutating(_) | 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 self.effect {
Effect::Mutating(kind) => found.extend(action_parameters(kind)),
Effect::Read | Effect::Write => found.extend(declared(self.body, Located::Body)),
}
found
}
#[must_use]
pub fn request_shapes(&self) -> Vec<(Parameter, Value)> {
let action = match self.effect {
Effect::Mutating(kind) => action_shapes(kind),
Effect::Read | Effect::Write => 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(_) => &[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),
("status", _) => schema_for!(crate::wire::StatusAnswer),
("context", _) => schema_for!(crate::wire::ContextAnswer),
("image", _) => schema_for!(crate::wire::ImageAnswer),
("history", _) => schema_for!(crate::wire::HistoryAnswer),
("manifest_get" | "manifest_set", _) => schema_for!(crate::wire::ManifestAnswer),
(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,
})
}
fn declared_shape(entries: &'static [Declared], name: &str) -> Value {
let Some(entry) = entries.iter().find(|entry| entry.name == name) else {
return json!({ "type": "string" });
};
if let Some(shape) = entry.shape {
return json!({ "$ref": format!("#/$defs/{shape}") });
}
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" }),
}
}
fn action_shapes(kind: ActionKind) -> Vec<(String, Value)> {
let schema = printobserver_types::schemars::schema_for!(PrintAction).to_value();
let variant = action_variant(&schema, 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() != ACTION_TAG)
.map(|(name, field)| (name.clone(), field.clone()))
.collect()
}
fn action_variant(schema: &Value, kind: ActionKind) -> Value {
let tag = 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"));
schema
.get("oneOf")
.and_then(Value::as_array)
.and_then(|variants| {
variants.iter().find(|variant| {
variant.pointer(&format!("/properties/{ACTION_TAG}/const"))
== Some(&json!(tag.clone()))
})
})
.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,
})
.collect()
}
fn action_parameters(kind: ActionKind) -> Vec<Parameter> {
let schema = printobserver_types::schemars::schema_for!(PrintAction).to_value();
let variant = action_variant(&schema, 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() != ACTION_TAG)
.map(|(name, field)| Parameter {
name: name.clone(),
required: required.contains(&name.as_str()),
located: Located::Body,
kind: kind_of(&resolve(&schema, field)),
})
.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,
}
}
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,
}
}
pub const OPERATIONS: [Operation; 16] = [
read("status", "/prints/{print_id}/status"),
Operation {
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 {
name: "limit",
required: false,
kind: ValueKind::Integer,
shape: None,
}],
..read("history", "/prints/{print_id}/history")
},
read("manifest_get", "/prints/{print_id}/manifest"),
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 {
name: "reason",
required: true,
kind: ValueKind::Text,
shape: None,
},
Declared {
name: "manifest",
required: true,
kind: ValueKind::Structured,
shape: Some("JobManifest"),
},
],
image_path_field: None,
},
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,
),
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,
),
];
pub const BESIDE_THE_ACTIONS: [&str; 6] = [
"status",
"context",
"image",
"history",
"manifest_get",
"manifest_set",
];
#[must_use]
pub fn operation(name: &str) -> Option<&'static Operation> {
OPERATIONS.iter().find(|declared| declared.name == name)
}
#[cfg(test)]
mod tests {
use printobserver_types::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!(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 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());
}
}