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