use std::path::PathBuf;
use printobserver_core::PrintContext;
use printobserver_core::store::ImageLookup;
use printobserver_core::{
AcknowledgementDisposition, ActionKind, ActionRecord, Actor, ImageRecord, Intervention,
JobManifest, ManifestNarrowing, PendingCharge, PolicyDecision, Preflight, PrintRecord,
SpoolCommand, SpoolId, SpoolRecord, SpoolTrust,
};
use printobserver_printer_api::{JobSnapshot, PrinterSnapshot};
use printobserver_supervisor_api::SupervisionSession;
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};
use printobserver_types::serde_json::{Map, Value};
use printobserver_types::{EventId, EventRecord, FileName, PrintId};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BodyRefusal {
pub detail: String,
}
impl core::fmt::Display for BodyRefusal {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter.write_str(&self.detail)
}
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
pub struct ActionBody {
#[serde(default)]
pub reason: Option<String>,
pub actor: Actor,
#[serde(default)]
pub duration_s: Option<i64>,
#[serde(default)]
pub factor: Option<f64>,
#[serde(default)]
pub target_c: Option<f64>,
#[serde(default)]
pub percent: Option<f64>,
#[serde(default)]
pub tool: Option<i64>,
#[serde(default)]
pub file_name: Option<FileName>,
#[serde(default)]
pub manifest: Option<JobManifest>,
#[serde(default)]
pub override_filament_check: bool,
#[serde(default)]
pub event_id: Option<EventId>,
#[serde(default)]
pub disposition: Option<AcknowledgementDisposition>,
}
fn missing<T>(named: &str) -> Result<T, BodyRefusal> {
Err(BodyRefusal {
detail: format!("this operation needs `{named}`, and the request carries none"),
})
}
pub fn reason_of(reason: Option<&str>) -> Result<String, BodyRefusal> {
match reason.map(str::trim) {
Some(reason) if !reason.is_empty() => Ok(reason.to_owned()),
_ => Err(BodyRefusal {
detail: "every mutating request carries a `reason`, and this one carries none"
.to_owned(),
}),
}
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
pub struct ManifestBody {
#[serde(default)]
pub reason: Option<String>,
pub manifest: JobManifest,
}
impl ManifestBody {
pub fn reason(&self) -> Result<String, BodyRefusal> {
reason_of(self.reason.as_deref())
}
}
impl ActionBody {
pub fn reason(&self) -> Result<String, BodyRefusal> {
reason_of(self.reason.as_deref())
}
pub fn into_action(
self,
kind: ActionKind,
) -> Result<printobserver_core::PrintAction, BodyRefusal> {
use printobserver_core::PrintAction as Action;
let reason = self.reason()?;
let actor = self.actor.clone();
let duration_s = self.duration_s;
Ok(match kind {
ActionKind::Pause => Action::Pause { reason, actor },
ActionKind::Resume => Action::Resume { reason, actor },
ActionKind::Cancel => Action::Cancel { reason, actor },
ActionKind::StartPrint => Action::StartPrint {
file_name: match self.file_name {
Some(name) => name,
None => return missing("file_name"),
},
manifest: match self.manifest {
Some(manifest) => manifest,
None => return missing("manifest"),
},
override_filament_check: self.override_filament_check,
reason,
actor,
},
ActionKind::SetFeedrateFactor => Action::SetFeedrateFactor {
factor: match self.factor {
Some(factor) => factor,
None => return missing("factor"),
},
duration_s,
reason,
actor,
},
ActionKind::SetFlowrateFactor => Action::SetFlowrateFactor {
factor: match self.factor {
Some(factor) => factor,
None => return missing("factor"),
},
duration_s,
reason,
actor,
},
ActionKind::SetToolTargetC => Action::SetToolTargetC {
tool: match self.tool {
Some(tool) => tool,
None => return missing("tool"),
},
target_c: match self.target_c {
Some(target) => target,
None => return missing("target_c"),
},
duration_s,
reason,
actor,
},
ActionKind::SetBedTargetC => Action::SetBedTargetC {
target_c: match self.target_c {
Some(target) => target,
None => return missing("target_c"),
},
duration_s,
reason,
actor,
},
ActionKind::SetFanPercent => Action::SetFanPercent {
percent: match self.percent {
Some(percent) => percent,
None => return missing("percent"),
},
duration_s,
reason,
actor,
},
ActionKind::AcknowledgeFailure => Action::AcknowledgeFailure {
event_id: match self.event_id {
Some(event_id) => event_id,
None => return missing("event_id"),
},
disposition: match self.disposition {
Some(disposition) => disposition,
None => return missing("disposition"),
},
reason,
actor,
},
ActionKind::RegisterSpool
| ActionKind::LoadSpool
| ActionKind::UnloadSpool
| ActionKind::AdjustSpool
| ActionKind::RetireSpool => {
return Err(BodyRefusal {
detail: format!(
"{kind:?} is a spool command, and no print-action operation carries one"
),
});
}
})
}
}
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct ActionAnswer {
pub record: ActionRecord,
#[serde(skip_serializing_if = "Option::is_none")]
pub intervention: Option<Intervention>,
#[serde(skip_serializing_if = "Option::is_none")]
pub printer_refusal: Option<String>,
}
pub fn spool_command_of(
kind: ActionKind,
spool_id: Option<SpoolId>,
body: Value,
) -> Result<SpoolCommand, BodyRefusal> {
let Value::Object(mut fields) = body else {
return Err(BodyRefusal {
detail: "a spool command's body is a document of its fields".to_owned(),
});
};
let reason = reason_of(fields.get("reason").and_then(Value::as_str))?;
fields.insert("reason".to_owned(), Value::String(reason));
let tag = crate::operations::COMMAND_TAG;
for routed in [tag, "spool_id"] {
if fields.contains_key(routed) {
return Err(BodyRefusal {
detail: format!(
"a spool command's body does not carry `{routed}`: the operation it is \
sent to names it"
),
});
}
}
let named = printobserver_types::serde_json::to_value(kind).map_err(|error| BodyRefusal {
detail: error.to_string(),
})?;
fields.insert(tag.to_owned(), named);
if let Some(spool_id) = spool_id {
fields.insert("spool_id".to_owned(), Value::String(spool_id.to_string()));
}
let command: SpoolCommand = printobserver_types::serde_json::from_value(Value::Object(fields))
.map_err(|error| BodyRefusal {
detail: format!("this is not a `{}` body: {error}", spool_command_name(kind)),
})?;
if command.kind() == kind {
Ok(command)
} else {
Err(BodyRefusal {
detail: format!("this body is not a `{}`", spool_command_name(kind)),
})
}
}
fn spool_command_name(kind: ActionKind) -> String {
printobserver_types::serde_json::to_value(kind)
.ok()
.and_then(|value| value.as_str().map(str::to_owned))
.unwrap_or_else(|| format!("{kind:?}"))
}
pub fn claimed_actor(body: &Map<String, Value>) -> Result<Actor, BodyRefusal> {
let Some(actor) = body.get("actor") else {
return missing("actor");
};
printobserver_types::serde_json::from_value(actor.clone()).map_err(|error| BodyRefusal {
detail: format!("`actor` is not an actor this system has: {error}"),
})
}
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct SpoolCommandAnswer {
pub decision: PolicyDecision,
#[serde(skip_serializing_if = "Option::is_none")]
pub spool: Option<SpoolRecord>,
pub events: Vec<EventRecord>,
}
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct SpoolsAnswer {
pub at_a_glance: Vec<String>,
pub spools: Vec<SpoolRecord>,
pub pending: Vec<PendingCharge>,
}
impl SpoolsAnswer {
#[must_use]
pub fn of(spools: Vec<SpoolRecord>, pending: Vec<PendingCharge>) -> Self {
Self {
at_a_glance: spools.iter().map(at_a_glance).collect(),
spools,
pending,
}
}
}
#[must_use]
pub fn at_a_glance(spool: &SpoolRecord) -> String {
let place = spool
.loaded_on_tool
.map_or_else(|| "not loaded".to_owned(), |tool| format!("on tool {tool}"));
let trust = match &spool.trust {
SpoolTrust::Verified => "verified".to_owned(),
SpoolTrust::Unverified { marks } => {
let oldest = marks.first().map_or_else(String::new, |mark| {
printobserver_types::serde_json::to_value(mark.reason.kind())
.ok()
.and_then(|named| named.as_str().map(str::to_owned))
.unwrap_or_default()
});
let more = marks.len().saturating_sub(1);
if more == 0 {
format!("unverified: {oldest}")
} else {
format!("unverified: {oldest} (+{more} more)")
}
}
};
let retired = if spool.retired_at.is_some() {
" | retired"
} else {
""
};
format!(
"{} | {} | {:.1} g of {:.1} g left | {place} | {trust}{retired}",
spool.name, spool.material, spool.remaining_g, spool.initial_g
)
}
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct SpoolAnswer {
pub spool: SpoolRecord,
pub recent: Vec<EventRecord>,
}
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct TimelineAnswer {
pub events: Vec<EventRecord>,
#[serde(skip_serializing_if = "Option::is_none")]
pub next: Option<EventId>,
}
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct PreflightAnswer {
pub preflight: Preflight,
}
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct StatusAnswer {
pub print: PrintRecord,
#[serde(skip_serializing_if = "Option::is_none")]
pub printer: Option<PrinterSnapshot>,
#[serde(skip_serializing_if = "Option::is_none")]
pub job: Option<JobSnapshot>,
#[serde(skip_serializing_if = "Option::is_none")]
pub session: Option<SupervisionSession>,
pub interventions: Vec<Intervention>,
}
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct ContextAnswer {
pub context: PrintContext,
#[serde(skip_serializing_if = "Option::is_none")]
pub image_path: Option<PathBuf>,
}
pub type LookAnswer = printobserver_core::Look;
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct ImageAnswer {
pub record: ImageRecord,
#[serde(skip_serializing_if = "Option::is_none")]
pub path: Option<PathBuf>,
}
impl From<ImageLookup> for ImageAnswer {
fn from(lookup: ImageLookup) -> Self {
match lookup {
ImageLookup::Found { record, path } => Self {
record,
path: Some(path),
},
ImageLookup::FileMissing { record } => Self { record, path: None },
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct PrintsAnswer {
pub prints: Vec<PrintRecord>,
#[serde(skip_serializing_if = "Option::is_none")]
pub active: Option<PrintId>,
}
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct HistoryAnswer {
pub events: Vec<EventRecord>,
}
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct ManifestAnswer {
#[serde(skip_serializing_if = "Option::is_none")]
pub manifest: Option<JobManifest>,
pub narrowings: Vec<ManifestNarrowing>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct ErrorAnswer {
pub error: String,
}
impl ErrorAnswer {
pub fn saying(detail: impl core::fmt::Display) -> Self {
Self {
error: detail.to_string(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IngressAnswer;
impl Serialize for IngressAnswer {
fn serialize<S: printobserver_types::serde::Serializer>(
&self,
serializer: S,
) -> Result<S::Ok, S::Error> {
use printobserver_types::serde::ser::SerializeStruct as _;
let mut state = serializer.serialize_struct("IngressAnswer", 1)?;
state.serialize_field("accepted", &true)?;
state.end()
}
}
#[cfg(test)]
mod tests {
use printobserver_core::{ActionKind, Actor, ImageRecord};
use printobserver_types::contract::Sample as _;
use super::{ActionBody, ErrorAnswer, ImageAnswer, ImageLookup};
fn bare() -> ActionBody {
ActionBody {
reason: Some("a test is asking".to_owned()),
actor: Actor::Operator,
duration_s: None,
factor: None,
target_c: None,
percent: None,
tool: None,
file_name: None,
manifest: None,
override_filament_check: false,
event_id: None,
disposition: None,
}
}
#[test]
fn every_action_that_needs_a_value_it_was_not_given_is_refused_naming_it() {
let needed = [
(ActionKind::StartPrint, "file_name"),
(ActionKind::SetFeedrateFactor, "factor"),
(ActionKind::SetFlowrateFactor, "factor"),
(ActionKind::SetToolTargetC, "tool"),
(ActionKind::SetBedTargetC, "target_c"),
(ActionKind::SetFanPercent, "percent"),
(ActionKind::AcknowledgeFailure, "event_id"),
];
for (kind, named) in needed {
let refusal = bare()
.into_action(kind)
.expect_err("this action needs a value the body does not carry");
assert!(
refusal.to_string().contains(named),
"{kind:?} was refused without naming `{named}`: {refusal}"
);
}
}
#[test]
fn a_spool_command_kind_is_refused_as_a_print_action() {
for kind in [
ActionKind::RegisterSpool,
ActionKind::LoadSpool,
ActionKind::UnloadSpool,
ActionKind::AdjustSpool,
ActionKind::RetireSpool,
] {
let refusal = bare()
.into_action(kind)
.expect_err("a spool command is not a print action");
assert!(
refusal.to_string().contains("spool command"),
"{kind:?} was refused without saying why: {refusal}"
);
}
}
#[test]
fn the_second_value_a_two_valued_action_needs_is_named_in_its_turn() {
let mut starting = bare();
starting.file_name = Some(printobserver_types::FileName::new("a.gcode").expect("a name"));
assert!(
starting
.into_action(ActionKind::StartPrint)
.expect_err("a start needs a manifest")
.to_string()
.contains("manifest")
);
let mut tool = bare();
tool.tool = Some(0);
assert!(
tool.into_action(ActionKind::SetToolTargetC)
.expect_err("a tool target needs a temperature")
.to_string()
.contains("target_c")
);
let mut acknowledgement = bare();
acknowledgement.event_id = Some(printobserver_types::EventId::new());
assert!(
acknowledgement
.into_action(ActionKind::AcknowledgeFailure)
.expect_err("an acknowledgement needs a disposition")
.to_string()
.contains("disposition")
);
}
#[test]
fn a_reason_that_is_nothing_but_whitespace_is_no_reason() {
let mut blank = bare();
blank.reason = Some(" ".to_owned());
assert!(blank.reason().is_err());
let mut absent = bare();
absent.reason = None;
assert!(absent.reason().is_err());
assert_eq!(bare().reason().expect("a reason"), "a test is asking");
}
#[test]
fn an_image_whose_file_is_gone_answers_the_record_and_no_path() {
let record = ImageRecord::sample_full();
let missing = ImageAnswer::from(ImageLookup::FileMissing {
record: record.clone(),
});
assert_eq!(missing.record, record);
assert_eq!(missing.path, None);
let found = ImageAnswer::from(ImageLookup::Found {
record: record.clone(),
path: "/var/lib/printobserver/images/ab/cd".into(),
});
assert_eq!(
found.path.as_deref(),
Some(std::path::Path::new("/var/lib/printobserver/images/ab/cd"))
);
}
#[test]
fn a_refusal_answers_in_the_words_of_whatever_refused_it() {
assert_eq!(
ErrorAnswer::saying("the disk is full").error,
"the disk is full"
);
}
}