1use std::path::PathBuf;
12
13use printobserver_core::PrintContext;
14use printobserver_core::store::ImageLookup;
15use printobserver_core::{
16 AcknowledgementDisposition, ActionKind, ActionRecord, Actor, ImageRecord, Intervention,
17 JobManifest, ManifestNarrowing, PrintRecord,
18};
19use printobserver_printer_api::{JobSnapshot, PrinterSnapshot};
20use printobserver_supervisor_api::SupervisionSession;
21use printobserver_types::schemars::JsonSchema;
22use printobserver_types::serde::{Deserialize, Serialize};
23use printobserver_types::{EventId, EventRecord, FileName, PrintId};
24
25#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct BodyRefusal {
28 pub detail: String,
30}
31
32impl core::fmt::Display for BodyRefusal {
33 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
34 formatter.write_str(&self.detail)
35 }
36}
37
38#[derive(Debug, Clone, PartialEq, Deserialize)]
47#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
48pub struct ActionBody {
49 #[serde(default)]
51 pub reason: Option<String>,
52 pub actor: Actor,
54 #[serde(default)]
56 pub duration_s: Option<i64>,
57 #[serde(default)]
59 pub factor: Option<f64>,
60 #[serde(default)]
62 pub target_c: Option<f64>,
63 #[serde(default)]
65 pub percent: Option<f64>,
66 #[serde(default)]
68 pub tool: Option<i64>,
69 #[serde(default)]
71 pub file_name: Option<FileName>,
72 #[serde(default)]
74 pub manifest: Option<JobManifest>,
75 #[serde(default)]
77 pub event_id: Option<EventId>,
78 #[serde(default)]
80 pub disposition: Option<AcknowledgementDisposition>,
81}
82
83fn missing<T>(named: &str) -> Result<T, BodyRefusal> {
85 Err(BodyRefusal {
86 detail: format!("this operation needs `{named}`, and the request carries none"),
87 })
88}
89
90pub fn reason_of(reason: Option<&str>) -> Result<String, BodyRefusal> {
102 match reason.map(str::trim) {
103 Some(reason) if !reason.is_empty() => Ok(reason.to_owned()),
104 _ => Err(BodyRefusal {
105 detail: "every mutating request carries a `reason`, and this one carries none"
106 .to_owned(),
107 }),
108 }
109}
110
111#[derive(Debug, Clone, PartialEq, Deserialize)]
117#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
118pub struct ManifestBody {
119 #[serde(default)]
121 pub reason: Option<String>,
122 pub manifest: JobManifest,
124}
125
126impl ManifestBody {
127 pub fn reason(&self) -> Result<String, BodyRefusal> {
136 reason_of(self.reason.as_deref())
137 }
138}
139
140impl ActionBody {
141 pub fn reason(&self) -> Result<String, BodyRefusal> {
150 reason_of(self.reason.as_deref())
151 }
152
153 pub fn into_action(
161 self,
162 kind: ActionKind,
163 ) -> Result<printobserver_core::PrintAction, BodyRefusal> {
164 use printobserver_core::PrintAction as Action;
165
166 let reason = self.reason()?;
167 let actor = self.actor.clone();
168 let duration_s = self.duration_s;
169 Ok(match kind {
170 ActionKind::Pause => Action::Pause { reason, actor },
171 ActionKind::Resume => Action::Resume { reason, actor },
172 ActionKind::Cancel => Action::Cancel { reason, actor },
173 ActionKind::StartPrint => Action::StartPrint {
174 file_name: match self.file_name {
175 Some(name) => name,
176 None => return missing("file_name"),
177 },
178 manifest: match self.manifest {
179 Some(manifest) => manifest,
180 None => return missing("manifest"),
181 },
182 reason,
183 actor,
184 },
185 ActionKind::SetFeedrateFactor => Action::SetFeedrateFactor {
186 factor: match self.factor {
187 Some(factor) => factor,
188 None => return missing("factor"),
189 },
190 duration_s,
191 reason,
192 actor,
193 },
194 ActionKind::SetFlowrateFactor => Action::SetFlowrateFactor {
195 factor: match self.factor {
196 Some(factor) => factor,
197 None => return missing("factor"),
198 },
199 duration_s,
200 reason,
201 actor,
202 },
203 ActionKind::SetToolTargetC => Action::SetToolTargetC {
204 tool: match self.tool {
205 Some(tool) => tool,
206 None => return missing("tool"),
207 },
208 target_c: match self.target_c {
209 Some(target) => target,
210 None => return missing("target_c"),
211 },
212 duration_s,
213 reason,
214 actor,
215 },
216 ActionKind::SetBedTargetC => Action::SetBedTargetC {
217 target_c: match self.target_c {
218 Some(target) => target,
219 None => return missing("target_c"),
220 },
221 duration_s,
222 reason,
223 actor,
224 },
225 ActionKind::SetFanPercent => Action::SetFanPercent {
226 percent: match self.percent {
227 Some(percent) => percent,
228 None => return missing("percent"),
229 },
230 duration_s,
231 reason,
232 actor,
233 },
234 ActionKind::AcknowledgeFailure => Action::AcknowledgeFailure {
235 event_id: match self.event_id {
236 Some(event_id) => event_id,
237 None => return missing("event_id"),
238 },
239 disposition: match self.disposition {
240 Some(disposition) => disposition,
241 None => return missing("disposition"),
242 },
243 reason,
244 actor,
245 },
246 })
247 }
248}
249
250#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
252#[serde(crate = "printobserver_types::serde")]
253#[schemars(crate = "printobserver_types::schemars")]
254pub struct ActionAnswer {
255 pub record: ActionRecord,
259 #[serde(skip_serializing_if = "Option::is_none")]
261 pub intervention: Option<Intervention>,
262 #[serde(skip_serializing_if = "Option::is_none")]
264 pub printer_refusal: Option<String>,
265}
266
267#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
269#[serde(crate = "printobserver_types::serde")]
270#[schemars(crate = "printobserver_types::schemars")]
271pub struct StatusAnswer {
272 pub print: PrintRecord,
274 #[serde(skip_serializing_if = "Option::is_none")]
276 pub printer: Option<PrinterSnapshot>,
277 #[serde(skip_serializing_if = "Option::is_none")]
279 pub job: Option<JobSnapshot>,
280 #[serde(skip_serializing_if = "Option::is_none")]
282 pub session: Option<SupervisionSession>,
283 pub interventions: Vec<Intervention>,
285}
286
287#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
296#[serde(crate = "printobserver_types::serde")]
297#[schemars(crate = "printobserver_types::schemars")]
298pub struct ContextAnswer {
299 pub context: PrintContext,
301 #[serde(skip_serializing_if = "Option::is_none")]
303 pub image_path: Option<PathBuf>,
304}
305
306#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
313#[serde(crate = "printobserver_types::serde")]
314#[schemars(crate = "printobserver_types::schemars")]
315pub struct ImageAnswer {
316 pub record: ImageRecord,
318 #[serde(skip_serializing_if = "Option::is_none")]
320 pub path: Option<PathBuf>,
321}
322
323impl From<ImageLookup> for ImageAnswer {
324 fn from(lookup: ImageLookup) -> Self {
325 match lookup {
326 ImageLookup::Found { record, path } => Self {
327 record,
328 path: Some(path),
329 },
330 ImageLookup::FileMissing { record } => Self { record, path: None },
331 }
332 }
333}
334
335#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
342#[serde(crate = "printobserver_types::serde")]
343#[schemars(crate = "printobserver_types::schemars")]
344pub struct PrintsAnswer {
345 pub prints: Vec<PrintRecord>,
347 #[serde(skip_serializing_if = "Option::is_none")]
351 pub active: Option<PrintId>,
352}
353
354#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
356#[serde(crate = "printobserver_types::serde")]
357#[schemars(crate = "printobserver_types::schemars")]
358pub struct HistoryAnswer {
359 pub events: Vec<EventRecord>,
361}
362
363#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
365#[serde(crate = "printobserver_types::serde")]
366#[schemars(crate = "printobserver_types::schemars")]
367pub struct ManifestAnswer {
368 #[serde(skip_serializing_if = "Option::is_none")]
370 pub manifest: Option<JobManifest>,
371 pub narrowings: Vec<ManifestNarrowing>,
375}
376
377#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
379#[serde(crate = "printobserver_types::serde")]
380#[schemars(crate = "printobserver_types::schemars")]
381pub struct ErrorAnswer {
382 pub error: String,
384}
385
386impl ErrorAnswer {
387 pub fn saying(detail: impl core::fmt::Display) -> Self {
389 Self {
390 error: detail.to_string(),
391 }
392 }
393}
394
395#[derive(Debug, Clone, Copy, PartialEq, Eq)]
401pub struct IngressAnswer;
402
403impl Serialize for IngressAnswer {
404 fn serialize<S: printobserver_types::serde::Serializer>(
405 &self,
406 serializer: S,
407 ) -> Result<S::Ok, S::Error> {
408 use printobserver_types::serde::ser::SerializeStruct as _;
409 let mut state = serializer.serialize_struct("IngressAnswer", 1)?;
410 state.serialize_field("accepted", &true)?;
411 state.end()
412 }
413}
414
415#[cfg(test)]
416mod tests {
417 use printobserver_core::{ActionKind, Actor, ImageRecord};
418 use printobserver_types::contract::Sample as _;
419
420 use super::{ActionBody, ErrorAnswer, ImageAnswer, ImageLookup};
421
422 fn bare() -> ActionBody {
424 ActionBody {
425 reason: Some("a test is asking".to_owned()),
426 actor: Actor::Operator,
427 duration_s: None,
428 factor: None,
429 target_c: None,
430 percent: None,
431 tool: None,
432 file_name: None,
433 manifest: None,
434 event_id: None,
435 disposition: None,
436 }
437 }
438
439 #[test]
445 fn every_action_that_needs_a_value_it_was_not_given_is_refused_naming_it() {
446 let needed = [
447 (ActionKind::StartPrint, "file_name"),
448 (ActionKind::SetFeedrateFactor, "factor"),
449 (ActionKind::SetFlowrateFactor, "factor"),
450 (ActionKind::SetToolTargetC, "tool"),
451 (ActionKind::SetBedTargetC, "target_c"),
452 (ActionKind::SetFanPercent, "percent"),
453 (ActionKind::AcknowledgeFailure, "event_id"),
454 ];
455 for (kind, named) in needed {
456 let refusal = bare()
457 .into_action(kind)
458 .expect_err("this action needs a value the body does not carry");
459 assert!(
460 refusal.to_string().contains(named),
461 "{kind:?} was refused without naming `{named}`: {refusal}"
462 );
463 }
464 }
465
466 #[test]
468 fn the_second_value_a_two_valued_action_needs_is_named_in_its_turn() {
469 let mut starting = bare();
470 starting.file_name = Some(printobserver_types::FileName::new("a.gcode").expect("a name"));
471 assert!(
472 starting
473 .into_action(ActionKind::StartPrint)
474 .expect_err("a start needs a manifest")
475 .to_string()
476 .contains("manifest")
477 );
478
479 let mut tool = bare();
480 tool.tool = Some(0);
481 assert!(
482 tool.into_action(ActionKind::SetToolTargetC)
483 .expect_err("a tool target needs a temperature")
484 .to_string()
485 .contains("target_c")
486 );
487
488 let mut acknowledgement = bare();
489 acknowledgement.event_id = Some(printobserver_types::EventId::new());
490 assert!(
491 acknowledgement
492 .into_action(ActionKind::AcknowledgeFailure)
493 .expect_err("an acknowledgement needs a disposition")
494 .to_string()
495 .contains("disposition")
496 );
497 }
498
499 #[test]
501 fn a_reason_that_is_nothing_but_whitespace_is_no_reason() {
502 let mut blank = bare();
503 blank.reason = Some(" ".to_owned());
504 assert!(blank.reason().is_err());
505 let mut absent = bare();
506 absent.reason = None;
507 assert!(absent.reason().is_err());
508 assert_eq!(bare().reason().expect("a reason"), "a test is asking");
509 }
510
511 #[test]
516 fn an_image_whose_file_is_gone_answers_the_record_and_no_path() {
517 let record = ImageRecord::sample_full();
518 let missing = ImageAnswer::from(ImageLookup::FileMissing {
519 record: record.clone(),
520 });
521 assert_eq!(missing.record, record);
522 assert_eq!(missing.path, None);
523
524 let found = ImageAnswer::from(ImageLookup::Found {
525 record: record.clone(),
526 path: "/var/lib/printobserver/images/ab/cd".into(),
527 });
528 assert_eq!(
529 found.path.as_deref(),
530 Some(std::path::Path::new("/var/lib/printobserver/images/ab/cd"))
531 );
532 }
533
534 #[test]
536 fn a_refusal_answers_in_the_words_of_whatever_refused_it() {
537 assert_eq!(
538 ErrorAnswer::saying("the disk is full").error,
539 "the disk is full"
540 );
541 }
542}