Skip to main content

printobserver_server/
wire.rs

1//! The JSON a caller sends and the JSON this server answers with.
2//!
3//! Nothing here restates a contract type. A request carries the values one
4//! [`PrintAction`] variant needs and this module assembles the action; an
5//! answer carries the contract's own records as they are. In particular **no
6//! answer carries image bytes**: [`ImageAnswer`] carries the record and the
7//! absolute path its bytes are at, because the server, the command-line program
8//! and the agent all run on the one host and image transport is a filesystem
9//! path.
10
11use 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/// Why a request could not be turned into one action of the vocabulary.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct BodyRefusal {
28    /// What is missing or wrong, named so the caller can send it.
29    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/// One request for one action of the vocabulary.
39///
40/// Every mutating operation takes this shape: the reason it carries, who is
41/// asking, the optional duration a bounded change stands for, and whichever of
42/// the values the asked-for action needs. A field the action does not need is
43/// ignored; a field it needs and the request omits is refused naming it, and
44/// **a request carrying no reason is refused before anything reaches the
45/// printer or the record**.
46#[derive(Debug, Clone, PartialEq, Deserialize)]
47#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
48pub struct ActionBody {
49    /// Why the actor is asking for this.
50    #[serde(default)]
51    pub reason: Option<String>,
52    /// Who is asking.
53    pub actor: Actor,
54    /// How long the change stands for, in whole seconds.
55    #[serde(default)]
56    pub duration_s: Option<i64>,
57    /// The multiplier a feedrate or flowrate adjustment asks for.
58    #[serde(default)]
59    pub factor: Option<f64>,
60    /// The temperature a heater adjustment asks for.
61    #[serde(default)]
62    pub target_c: Option<f64>,
63    /// The percentage a fan adjustment asks for.
64    #[serde(default)]
65    pub percent: Option<f64>,
66    /// The tool a tool adjustment is about.
67    #[serde(default)]
68    pub tool: Option<i64>,
69    /// The file a start asks for.
70    #[serde(default)]
71    pub file_name: Option<FileName>,
72    /// The manifest a start is bounded by.
73    #[serde(default)]
74    pub manifest: Option<JobManifest>,
75    /// The event an acknowledgement is about.
76    #[serde(default)]
77    pub event_id: Option<EventId>,
78    /// What an acknowledgement asks for next.
79    #[serde(default)]
80    pub disposition: Option<AcknowledgementDisposition>,
81}
82
83/// One value a request had to carry and did not.
84fn 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
90/// The reason a mutating request carries, refused when it carries none.
91///
92/// One rule for every mutating operation, whether it asks something of the
93/// machine or writes a record: a change nobody gave a reason for is one the
94/// history cannot account for afterwards, and the answer to it is the same
95/// refusal whichever operation it arrived at.
96///
97/// # Errors
98///
99/// Returns [`BodyRefusal`] when the reason is absent or is nothing but
100/// whitespace.
101pub 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/// One request to replace a print's manifest.
112///
113/// It carries a reason for the same reason every action does: a manifest
114/// narrows what any actor may ask for, so replacing one is a change to the
115/// bounds a print runs under rather than a note about it.
116#[derive(Debug, Clone, PartialEq, Deserialize)]
117#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
118pub struct ManifestBody {
119    /// Why the manifest is being replaced.
120    #[serde(default)]
121    pub reason: Option<String>,
122    /// The manifest to write.
123    pub manifest: JobManifest,
124}
125
126impl ManifestBody {
127    /// The reason this request carries, refused when it carries none.
128    ///
129    /// # Errors
130    ///
131    /// Returns [`BodyRefusal`] when the reason is absent or is nothing but
132    /// whitespace. It is checked **before** the manifest is written, so a
133    /// request without one leaves the stored manifest and the print's
134    /// narrowings exactly as they were.
135    pub fn reason(&self) -> Result<String, BodyRefusal> {
136        reason_of(self.reason.as_deref())
137    }
138}
139
140impl ActionBody {
141    /// The reason this request carries, refused when it carries none.
142    ///
143    /// # Errors
144    ///
145    /// Returns [`BodyRefusal`] when the reason is absent or is nothing but
146    /// whitespace. Every mutating operation carries a reason, and this is
147    /// checked before the action is assembled, so a request without one reaches
148    /// neither the policy, the printer nor the record.
149    pub fn reason(&self) -> Result<String, BodyRefusal> {
150        reason_of(self.reason.as_deref())
151    }
152
153    /// The action this request asks for.
154    ///
155    /// # Errors
156    ///
157    /// Returns [`BodyRefusal`] naming the value the asked-for action needs and
158    /// the request does not carry, and naming the absent reason before
159    /// anything else.
160    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/// What one mutating request left behind it.
251#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
252#[serde(crate = "printobserver_types::serde")]
253#[schemars(crate = "printobserver_types::schemars")]
254pub struct ActionAnswer {
255    /// The record of the request and the decision taken on it. A rejected
256    /// request's rejection is here, carrying its reason, the value asked for
257    /// and the range allowed, so a caller can ask again inside the range.
258    pub record: ActionRecord,
259    /// The bounded intervention it opened, when it opened one.
260    #[serde(skip_serializing_if = "Option::is_none")]
261    pub intervention: Option<Intervention>,
262    /// What the printer said, when the request reached it and it refused.
263    #[serde(skip_serializing_if = "Option::is_none")]
264    pub printer_refusal: Option<String>,
265}
266
267/// What a status read answers.
268#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
269#[serde(crate = "printobserver_types::serde")]
270#[schemars(crate = "printobserver_types::schemars")]
271pub struct StatusAnswer {
272    /// The print.
273    pub print: PrintRecord,
274    /// The printer, when a snapshot could be taken.
275    #[serde(skip_serializing_if = "Option::is_none")]
276    pub printer: Option<PrinterSnapshot>,
277    /// The job, when a snapshot could be taken.
278    #[serde(skip_serializing_if = "Option::is_none")]
279    pub job: Option<JobSnapshot>,
280    /// The supervision session watching it, when one is.
281    #[serde(skip_serializing_if = "Option::is_none")]
282    pub session: Option<SupervisionSession>,
283    /// The bounded interventions still in force.
284    pub interventions: Vec<Intervention>,
285}
286
287/// What a context read answers.
288///
289/// The latest image is **materialized** here rather than left as the handle
290/// [`PrintContext`] carries: the one thing a supervision turn does with an
291/// image is look at it, and a handle is not something anything can open. The
292/// path is absolute on this server's own filesystem, exactly as
293/// [`ImageAnswer`]'s is, and is absent when there is no image or when the
294/// record is intact and the file is not.
295#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
296#[serde(crate = "printobserver_types::serde")]
297#[schemars(crate = "printobserver_types::schemars")]
298pub struct ContextAnswer {
299    /// Everything a supervision turn is given about the print.
300    pub context: PrintContext,
301    /// Where the latest image's bytes are, absolute on this host.
302    #[serde(skip_serializing_if = "Option::is_none")]
303    pub image_path: Option<PathBuf>,
304}
305
306/// What an image read answers.
307///
308/// The path is absolute on this server's own filesystem, and is the whole of
309/// the answer about the bytes: nothing here renders them, encodes them or
310/// serves them. It is absent when the record is intact and the file is not,
311/// which is a different answer from there being no such image.
312#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
313#[serde(crate = "printobserver_types::serde")]
314#[schemars(crate = "printobserver_types::schemars")]
315pub struct ImageAnswer {
316    /// The record.
317    pub record: ImageRecord,
318    /// Where its bytes are, absolute on this host.
319    #[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/// What the prints read answers: every print, and the one the printer is
336/// running.
337///
338/// An open print's recorded `state` is the state it was opened in, which is
339/// `printing` whether or not the machine is paused now; what the machine is
340/// doing is the status read's answer.
341#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
342#[serde(crate = "printobserver_types::serde")]
343#[schemars(crate = "printobserver_types::schemars")]
344pub struct PrintsAnswer {
345    /// Every print this server holds, ended or not, most recently opened first.
346    pub prints: Vec<PrintRecord>,
347    /// The print the printer's current job belongs to, present exactly when the
348    /// printer reports a job it is printing or has paused. Absent when the
349    /// printer could not be read.
350    #[serde(skip_serializing_if = "Option::is_none")]
351    pub active: Option<PrintId>,
352}
353
354/// What a history read answers.
355#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
356#[serde(crate = "printobserver_types::serde")]
357#[schemars(crate = "printobserver_types::schemars")]
358pub struct HistoryAnswer {
359    /// The print's events, newest first.
360    pub events: Vec<EventRecord>,
361}
362
363/// What a manifest read or write answers.
364#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
365#[serde(crate = "printobserver_types::serde")]
366#[schemars(crate = "printobserver_types::schemars")]
367pub struct ManifestAnswer {
368    /// The manifest, when the print has one.
369    #[serde(skip_serializing_if = "Option::is_none")]
370    pub manifest: Option<JobManifest>,
371    /// Every range this manifest asked wider than the envelope allows, narrowed
372    /// to the envelope's — recorded on the print, so nobody has to wonder later
373    /// which bound applied.
374    pub narrowings: Vec<ManifestNarrowing>,
375}
376
377/// What this server answers when it will not do what it was asked.
378#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
379#[serde(crate = "printobserver_types::serde")]
380#[schemars(crate = "printobserver_types::schemars")]
381pub struct ErrorAnswer {
382    /// One line saying why, in the words of whatever refused it.
383    pub error: String,
384}
385
386impl ErrorAnswer {
387    /// One refusal, in its own words.
388    pub fn saying(detail: impl core::fmt::Display) -> Self {
389        Self {
390            error: detail.to_string(),
391        }
392    }
393}
394
395/// What the ingress answers a post it accepted.
396///
397/// It carries no field, because the only thing it could carry is that the post
398/// was accepted and this is the answer only an accepted post gets. It
399/// serializes as `{"accepted": true}`, which is what a caller reads.
400#[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    /// A body carrying nothing but a reason and an actor.
423    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    /// Every action that needs a value it was not given is refused naming it.
440    ///
441    /// The walk is over the whole vocabulary rather than a sample: an action
442    /// that quietly defaulted a value nobody sent would be one this server
443    /// carried to a printer on the caller's behalf.
444    #[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    /// The second value each two-valued action needs is named in its turn.
467    #[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    /// A reason that is nothing but whitespace is no reason.
500    #[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    /// An image whose file is gone answers the record and no path.
512    ///
513    /// A different answer from there being no such image, which is what tells a
514    /// caller the history is intact and the file is not.
515    #[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    /// A refusal answers in the words of whatever refused it.
535    #[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}