1use std::path::PathBuf;
12
13use printobserver_store_api::ImageLookup;
14use printobserver_types::schemars::JsonSchema;
15use printobserver_types::serde::{Deserialize, Serialize};
16use printobserver_types::{
17 AcknowledgementDisposition, ActionKind, ActionRecord, Actor, EventId, EventRecord, FileName,
18 ImageRecord, Intervention, JobManifest, JobSnapshot, ManifestNarrowing, PrintContext,
19 PrintRecord, PrinterSnapshot, SupervisionSession,
20};
21
22#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct BodyRefusal {
25 pub detail: String,
27}
28
29impl core::fmt::Display for BodyRefusal {
30 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
31 formatter.write_str(&self.detail)
32 }
33}
34
35#[derive(Debug, Clone, PartialEq, Deserialize)]
44#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
45pub struct ActionBody {
46 #[serde(default)]
48 pub reason: Option<String>,
49 pub actor: Actor,
51 #[serde(default)]
53 pub duration_s: Option<i64>,
54 #[serde(default)]
56 pub factor: Option<f64>,
57 #[serde(default)]
59 pub target_c: Option<f64>,
60 #[serde(default)]
62 pub percent: Option<f64>,
63 #[serde(default)]
65 pub tool: Option<i64>,
66 #[serde(default)]
68 pub file_name: Option<FileName>,
69 #[serde(default)]
71 pub manifest: Option<JobManifest>,
72 #[serde(default)]
74 pub event_id: Option<EventId>,
75 #[serde(default)]
77 pub disposition: Option<AcknowledgementDisposition>,
78}
79
80fn missing<T>(named: &str) -> Result<T, BodyRefusal> {
82 Err(BodyRefusal {
83 detail: format!("this operation needs `{named}`, and the request carries none"),
84 })
85}
86
87pub fn reason_of(reason: Option<&str>) -> Result<String, BodyRefusal> {
99 match reason.map(str::trim) {
100 Some(reason) if !reason.is_empty() => Ok(reason.to_owned()),
101 _ => Err(BodyRefusal {
102 detail: "every mutating request carries a `reason`, and this one carries none"
103 .to_owned(),
104 }),
105 }
106}
107
108#[derive(Debug, Clone, PartialEq, Deserialize)]
114#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
115pub struct ManifestBody {
116 #[serde(default)]
118 pub reason: Option<String>,
119 pub manifest: JobManifest,
121}
122
123impl ManifestBody {
124 pub fn reason(&self) -> Result<String, BodyRefusal> {
133 reason_of(self.reason.as_deref())
134 }
135}
136
137impl ActionBody {
138 pub fn reason(&self) -> Result<String, BodyRefusal> {
147 reason_of(self.reason.as_deref())
148 }
149
150 pub fn into_action(
158 self,
159 kind: ActionKind,
160 ) -> Result<printobserver_types::PrintAction, BodyRefusal> {
161 use printobserver_types::PrintAction as Action;
162
163 let reason = self.reason()?;
164 let actor = self.actor.clone();
165 let duration_s = self.duration_s;
166 Ok(match kind {
167 ActionKind::Pause => Action::Pause { reason, actor },
168 ActionKind::Resume => Action::Resume { reason, actor },
169 ActionKind::Cancel => Action::Cancel { reason, actor },
170 ActionKind::StartPrint => Action::StartPrint {
171 file_name: match self.file_name {
172 Some(name) => name,
173 None => return missing("file_name"),
174 },
175 manifest: match self.manifest {
176 Some(manifest) => manifest,
177 None => return missing("manifest"),
178 },
179 reason,
180 actor,
181 },
182 ActionKind::SetFeedrateFactor => Action::SetFeedrateFactor {
183 factor: match self.factor {
184 Some(factor) => factor,
185 None => return missing("factor"),
186 },
187 duration_s,
188 reason,
189 actor,
190 },
191 ActionKind::SetFlowrateFactor => Action::SetFlowrateFactor {
192 factor: match self.factor {
193 Some(factor) => factor,
194 None => return missing("factor"),
195 },
196 duration_s,
197 reason,
198 actor,
199 },
200 ActionKind::SetToolTargetC => Action::SetToolTargetC {
201 tool: match self.tool {
202 Some(tool) => tool,
203 None => return missing("tool"),
204 },
205 target_c: match self.target_c {
206 Some(target) => target,
207 None => return missing("target_c"),
208 },
209 duration_s,
210 reason,
211 actor,
212 },
213 ActionKind::SetBedTargetC => Action::SetBedTargetC {
214 target_c: match self.target_c {
215 Some(target) => target,
216 None => return missing("target_c"),
217 },
218 duration_s,
219 reason,
220 actor,
221 },
222 ActionKind::SetFanPercent => Action::SetFanPercent {
223 percent: match self.percent {
224 Some(percent) => percent,
225 None => return missing("percent"),
226 },
227 duration_s,
228 reason,
229 actor,
230 },
231 ActionKind::AcknowledgeFailure => Action::AcknowledgeFailure {
232 event_id: match self.event_id {
233 Some(event_id) => event_id,
234 None => return missing("event_id"),
235 },
236 disposition: match self.disposition {
237 Some(disposition) => disposition,
238 None => return missing("disposition"),
239 },
240 reason,
241 actor,
242 },
243 })
244 }
245}
246
247#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
249#[serde(crate = "printobserver_types::serde")]
250#[schemars(crate = "printobserver_types::schemars")]
251pub struct ActionAnswer {
252 pub record: ActionRecord,
256 #[serde(skip_serializing_if = "Option::is_none")]
258 pub intervention: Option<Intervention>,
259 #[serde(skip_serializing_if = "Option::is_none")]
261 pub printer_refusal: Option<String>,
262}
263
264#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
266#[serde(crate = "printobserver_types::serde")]
267#[schemars(crate = "printobserver_types::schemars")]
268pub struct StatusAnswer {
269 pub print: PrintRecord,
271 #[serde(skip_serializing_if = "Option::is_none")]
273 pub printer: Option<PrinterSnapshot>,
274 #[serde(skip_serializing_if = "Option::is_none")]
276 pub job: Option<JobSnapshot>,
277 #[serde(skip_serializing_if = "Option::is_none")]
279 pub session: Option<SupervisionSession>,
280 pub interventions: Vec<Intervention>,
282}
283
284#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
293#[serde(crate = "printobserver_types::serde")]
294#[schemars(crate = "printobserver_types::schemars")]
295pub struct ContextAnswer {
296 pub context: PrintContext,
298 #[serde(skip_serializing_if = "Option::is_none")]
300 pub image_path: Option<PathBuf>,
301}
302
303#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
310#[serde(crate = "printobserver_types::serde")]
311#[schemars(crate = "printobserver_types::schemars")]
312pub struct ImageAnswer {
313 pub record: ImageRecord,
315 #[serde(skip_serializing_if = "Option::is_none")]
317 pub path: Option<PathBuf>,
318}
319
320impl From<ImageLookup> for ImageAnswer {
321 fn from(lookup: ImageLookup) -> Self {
322 match lookup {
323 ImageLookup::Found { record, path } => Self {
324 record,
325 path: Some(path),
326 },
327 ImageLookup::FileMissing { record } => Self { record, path: None },
328 }
329 }
330}
331
332#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
334#[serde(crate = "printobserver_types::serde")]
335#[schemars(crate = "printobserver_types::schemars")]
336pub struct HistoryAnswer {
337 pub events: Vec<EventRecord>,
339}
340
341#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
343#[serde(crate = "printobserver_types::serde")]
344#[schemars(crate = "printobserver_types::schemars")]
345pub struct ManifestAnswer {
346 #[serde(skip_serializing_if = "Option::is_none")]
348 pub manifest: Option<JobManifest>,
349 pub narrowings: Vec<ManifestNarrowing>,
353}
354
355#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
357#[serde(crate = "printobserver_types::serde")]
358#[schemars(crate = "printobserver_types::schemars")]
359pub struct ErrorAnswer {
360 pub error: String,
362}
363
364impl ErrorAnswer {
365 pub fn saying(detail: impl core::fmt::Display) -> Self {
367 Self {
368 error: detail.to_string(),
369 }
370 }
371}
372
373#[derive(Debug, Clone, Copy, PartialEq, Eq)]
379pub struct IngressAnswer;
380
381impl Serialize for IngressAnswer {
382 fn serialize<S: printobserver_types::serde::Serializer>(
383 &self,
384 serializer: S,
385 ) -> Result<S::Ok, S::Error> {
386 use printobserver_types::serde::ser::SerializeStruct as _;
387 let mut state = serializer.serialize_struct("IngressAnswer", 1)?;
388 state.serialize_field("accepted", &true)?;
389 state.end()
390 }
391}
392
393#[cfg(test)]
394mod tests {
395 use printobserver_types::contract::Sample as _;
396 use printobserver_types::{ActionKind, Actor, ImageRecord};
397
398 use super::{ActionBody, ErrorAnswer, ImageAnswer, ImageLookup};
399
400 fn bare() -> ActionBody {
402 ActionBody {
403 reason: Some("a test is asking".to_owned()),
404 actor: Actor::Operator,
405 duration_s: None,
406 factor: None,
407 target_c: None,
408 percent: None,
409 tool: None,
410 file_name: None,
411 manifest: None,
412 event_id: None,
413 disposition: None,
414 }
415 }
416
417 #[test]
423 fn every_action_that_needs_a_value_it_was_not_given_is_refused_naming_it() {
424 let needed = [
425 (ActionKind::StartPrint, "file_name"),
426 (ActionKind::SetFeedrateFactor, "factor"),
427 (ActionKind::SetFlowrateFactor, "factor"),
428 (ActionKind::SetToolTargetC, "tool"),
429 (ActionKind::SetBedTargetC, "target_c"),
430 (ActionKind::SetFanPercent, "percent"),
431 (ActionKind::AcknowledgeFailure, "event_id"),
432 ];
433 for (kind, named) in needed {
434 let refusal = bare()
435 .into_action(kind)
436 .expect_err("this action needs a value the body does not carry");
437 assert!(
438 refusal.to_string().contains(named),
439 "{kind:?} was refused without naming `{named}`: {refusal}"
440 );
441 }
442 }
443
444 #[test]
446 fn the_second_value_a_two_valued_action_needs_is_named_in_its_turn() {
447 let mut starting = bare();
448 starting.file_name = Some(printobserver_types::FileName::new("a.gcode").expect("a name"));
449 assert!(
450 starting
451 .into_action(ActionKind::StartPrint)
452 .expect_err("a start needs a manifest")
453 .to_string()
454 .contains("manifest")
455 );
456
457 let mut tool = bare();
458 tool.tool = Some(0);
459 assert!(
460 tool.into_action(ActionKind::SetToolTargetC)
461 .expect_err("a tool target needs a temperature")
462 .to_string()
463 .contains("target_c")
464 );
465
466 let mut acknowledgement = bare();
467 acknowledgement.event_id = Some(printobserver_types::EventId::new());
468 assert!(
469 acknowledgement
470 .into_action(ActionKind::AcknowledgeFailure)
471 .expect_err("an acknowledgement needs a disposition")
472 .to_string()
473 .contains("disposition")
474 );
475 }
476
477 #[test]
479 fn a_reason_that_is_nothing_but_whitespace_is_no_reason() {
480 let mut blank = bare();
481 blank.reason = Some(" ".to_owned());
482 assert!(blank.reason().is_err());
483 let mut absent = bare();
484 absent.reason = None;
485 assert!(absent.reason().is_err());
486 assert_eq!(bare().reason().expect("a reason"), "a test is asking");
487 }
488
489 #[test]
494 fn an_image_whose_file_is_gone_answers_the_record_and_no_path() {
495 let record = ImageRecord::sample_full();
496 let missing = ImageAnswer::from(ImageLookup::FileMissing {
497 record: record.clone(),
498 });
499 assert_eq!(missing.record, record);
500 assert_eq!(missing.path, None);
501
502 let found = ImageAnswer::from(ImageLookup::Found {
503 record: record.clone(),
504 path: "/var/lib/printobserver/images/ab/cd".into(),
505 });
506 assert_eq!(
507 found.path.as_deref(),
508 Some(std::path::Path::new("/var/lib/printobserver/images/ab/cd"))
509 );
510 }
511
512 #[test]
514 fn a_refusal_answers_in_the_words_of_whatever_refused_it() {
515 assert_eq!(
516 ErrorAnswer::saying("the disk is full").error,
517 "the disk is full"
518 );
519 }
520}