use std::path::PathBuf;
use printobserver_store_api::ImageLookup;
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};
use printobserver_types::{
AcknowledgementDisposition, ActionKind, ActionRecord, Actor, EventId, EventRecord, FileName,
ImageRecord, Intervention, JobManifest, JobSnapshot, ManifestNarrowing, PrintContext,
PrintRecord, PrinterSnapshot, SupervisionSession,
};
#[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 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_types::PrintAction, BodyRefusal> {
use printobserver_types::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"),
},
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,
},
})
}
}
#[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>,
}
#[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>,
}
#[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 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_types::contract::Sample as _;
use printobserver_types::{ActionKind, Actor, ImageRecord};
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,
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 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"
);
}
}