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, PendingCharge, PolicyDecision, Preflight, PrintOutcome,
18    PrintRecord, SpoolCommand, SpoolId, SpoolRecord, SpoolTrust,
19};
20use printobserver_printer_api::{JobSnapshot, PrinterSnapshot};
21use printobserver_supervisor_api::SupervisionSession;
22use printobserver_types::schemars::JsonSchema;
23use printobserver_types::serde::{Deserialize, Serialize};
24use printobserver_types::serde_json::{Map, Value};
25use printobserver_types::{EventId, EventRecord, FileName, PrintId, Timestamp};
26
27/// Why a request could not be turned into one action of the vocabulary.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct BodyRefusal {
30    /// What is missing or wrong, named so the caller can send it.
31    pub detail: String,
32}
33
34impl core::fmt::Display for BodyRefusal {
35    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
36        formatter.write_str(&self.detail)
37    }
38}
39
40/// One request for one action of the vocabulary.
41///
42/// Every mutating operation takes this shape: the reason it carries, who is
43/// asking, the optional duration a bounded change stands for, and whichever of
44/// the values the asked-for action needs. A field the action does not need is
45/// ignored; a field it needs and the request omits is refused naming it, and
46/// **a request carrying no reason is refused before anything reaches the
47/// printer or the record**.
48#[derive(Debug, Clone, PartialEq, Deserialize)]
49#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
50pub struct ActionBody {
51    /// Why the actor is asking for this.
52    #[serde(default)]
53    pub reason: Option<String>,
54    /// Who is asking.
55    pub actor: Actor,
56    /// How long the change stands for, in whole seconds.
57    #[serde(default)]
58    pub duration_s: Option<i64>,
59    /// The multiplier a feedrate or flowrate adjustment asks for.
60    #[serde(default)]
61    pub factor: Option<f64>,
62    /// The temperature a heater adjustment asks for.
63    #[serde(default)]
64    pub target_c: Option<f64>,
65    /// The percentage a fan adjustment asks for.
66    #[serde(default)]
67    pub percent: Option<f64>,
68    /// The tool a tool adjustment is about.
69    #[serde(default)]
70    pub tool: Option<i64>,
71    /// The file a start asks for.
72    #[serde(default)]
73    pub file_name: Option<FileName>,
74    /// The manifest a start is bounded by.
75    #[serde(default)]
76    pub manifest: Option<JobManifest>,
77    /// Whether a start goes ahead despite the filament check; absent, it does
78    /// not.
79    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
80    #[serde(default)]
81    pub override_filament_check: bool,
82    /// The event an acknowledgement is about.
83    #[serde(default)]
84    pub event_id: Option<EventId>,
85    /// What an acknowledgement asks for next.
86    #[serde(default)]
87    pub disposition: Option<AcknowledgementDisposition>,
88    /// How a closed print ended, in the operator's judgement.
89    #[serde(default)]
90    pub outcome: Option<PrintOutcome>,
91}
92
93/// One value a request had to carry and did not.
94fn missing<T>(named: &str) -> Result<T, BodyRefusal> {
95    Err(BodyRefusal {
96        detail: format!("this operation needs `{named}`, and the request carries none"),
97    })
98}
99
100/// One value a request has to carry, refused naming it when it carries none.
101fn needed<T>(value: Option<T>, named: &str) -> Result<T, BodyRefusal> {
102    value.map_or_else(|| missing(named), Ok)
103}
104
105/// The reason a mutating request carries, refused when it carries none.
106///
107/// One rule for every mutating operation, whether it asks something of the
108/// machine or writes a record: a change nobody gave a reason for is one the
109/// history cannot account for afterwards, and the answer to it is the same
110/// refusal whichever operation it arrived at.
111///
112/// # Errors
113///
114/// Returns [`BodyRefusal`] when the reason is absent or is nothing but
115/// whitespace.
116pub fn reason_of(reason: Option<&str>) -> Result<String, BodyRefusal> {
117    match reason.map(str::trim) {
118        Some(reason) if !reason.is_empty() => Ok(reason.to_owned()),
119        _ => Err(BodyRefusal {
120            detail: "every mutating request carries a `reason`, and this one carries none"
121                .to_owned(),
122        }),
123    }
124}
125
126/// One request to replace a print's manifest.
127///
128/// It carries a reason for the same reason every action does: a manifest
129/// narrows what any actor may ask for, so replacing one is a change to the
130/// bounds a print runs under rather than a note about it.
131#[derive(Debug, Clone, PartialEq, Deserialize)]
132#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
133pub struct ManifestBody {
134    /// Why the manifest is being replaced.
135    #[serde(default)]
136    pub reason: Option<String>,
137    /// The manifest to write.
138    pub manifest: JobManifest,
139}
140
141impl ManifestBody {
142    /// The reason this request carries, refused when it carries none.
143    ///
144    /// # Errors
145    ///
146    /// Returns [`BodyRefusal`] when the reason is absent or is nothing but
147    /// whitespace. It is checked **before** the manifest is written, so a
148    /// request without one leaves the stored manifest and the print's
149    /// narrowings exactly as they were.
150    pub fn reason(&self) -> Result<String, BodyRefusal> {
151        reason_of(self.reason.as_deref())
152    }
153}
154
155impl ActionBody {
156    /// The reason this request carries, refused when it carries none.
157    ///
158    /// # Errors
159    ///
160    /// Returns [`BodyRefusal`] when the reason is absent or is nothing but
161    /// whitespace. Every mutating operation carries a reason, and this is
162    /// checked before the action is assembled, so a request without one reaches
163    /// neither the policy, the printer nor the record.
164    pub fn reason(&self) -> Result<String, BodyRefusal> {
165        reason_of(self.reason.as_deref())
166    }
167
168    /// The action this request asks for.
169    ///
170    /// # Errors
171    ///
172    /// Returns [`BodyRefusal`] naming the value the asked-for action needs and
173    /// the request does not carry, and naming the absent reason before
174    /// anything else.
175    pub fn into_action(
176        self,
177        kind: ActionKind,
178    ) -> Result<printobserver_core::PrintAction, BodyRefusal> {
179        use printobserver_core::PrintAction as Action;
180
181        let reason = self.reason()?;
182        let actor = self.actor.clone();
183        let duration_s = self.duration_s;
184        Ok(match kind {
185            ActionKind::Pause => Action::Pause { reason, actor },
186            ActionKind::Resume => Action::Resume { reason, actor },
187            ActionKind::Cancel => Action::Cancel { reason, actor },
188            ActionKind::StartPrint => Action::StartPrint {
189                file_name: needed(self.file_name, "file_name")?,
190                manifest: needed(self.manifest, "manifest")?,
191                override_filament_check: self.override_filament_check,
192                reason,
193                actor,
194            },
195            ActionKind::SetFeedrateFactor => Action::SetFeedrateFactor {
196                factor: needed(self.factor, "factor")?,
197                duration_s,
198                reason,
199                actor,
200            },
201            ActionKind::SetFlowrateFactor => Action::SetFlowrateFactor {
202                factor: needed(self.factor, "factor")?,
203                duration_s,
204                reason,
205                actor,
206            },
207            ActionKind::SetToolTargetC => Action::SetToolTargetC {
208                tool: needed(self.tool, "tool")?,
209                target_c: needed(self.target_c, "target_c")?,
210                duration_s,
211                reason,
212                actor,
213            },
214            ActionKind::SetBedTargetC => Action::SetBedTargetC {
215                target_c: needed(self.target_c, "target_c")?,
216                duration_s,
217                reason,
218                actor,
219            },
220            ActionKind::SetFanPercent => Action::SetFanPercent {
221                percent: needed(self.percent, "percent")?,
222                duration_s,
223                reason,
224                actor,
225            },
226            ActionKind::AcknowledgeFailure => Action::AcknowledgeFailure {
227                event_id: needed(self.event_id, "event_id")?,
228                disposition: needed(self.disposition, "disposition")?,
229                reason,
230                actor,
231            },
232            ActionKind::ClosePrint => Action::ClosePrint {
233                outcome: needed(self.outcome, "outcome")?,
234                reason,
235                actor,
236            },
237            ActionKind::RegisterSpool
238            | ActionKind::LoadSpool
239            | ActionKind::UnloadSpool
240            | ActionKind::AdjustSpool
241            | ActionKind::RetireSpool => {
242                return Err(BodyRefusal {
243                    detail: format!(
244                        "{kind:?} is a spool command, and no print-action operation carries one"
245                    ),
246                });
247            }
248        })
249    }
250}
251
252/// What one mutating request left behind it.
253#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
254#[serde(crate = "printobserver_types::serde")]
255#[schemars(crate = "printobserver_types::schemars")]
256pub struct ActionAnswer {
257    /// The record of the request and the decision taken on it. A rejected
258    /// request's rejection is here, carrying its reason, the value asked for
259    /// and the range allowed, so a caller can ask again inside the range.
260    pub record: ActionRecord,
261    /// The bounded intervention it opened, when it opened one.
262    #[serde(skip_serializing_if = "Option::is_none")]
263    pub intervention: Option<Intervention>,
264    /// What the printer said, when the request reached it and it refused.
265    #[serde(skip_serializing_if = "Option::is_none")]
266    pub printer_refusal: Option<String>,
267}
268
269/// The spool command one request asks for, assembled from its body.
270///
271/// The body is the command's own fields, less the two a caller never supplies:
272/// the tag, which the operation it was sent to names, and — for a command about
273/// one spool — the spool, which its path names. Everything else is read by the
274/// contracts' own type, so a field it refuses is refused in its own words and
275/// a field it gains is one this reads with nothing written here. The reason is
276/// ruled on first and travels trimmed, exactly as a print action's does.
277///
278/// # Errors
279///
280/// Returns [`BodyRefusal`] when the body is not a document, carries no reason,
281/// names the tag or the spool itself, or is not the command's own fields.
282pub fn spool_command_of(
283    kind: ActionKind,
284    spool_id: Option<SpoolId>,
285    body: Value,
286) -> Result<SpoolCommand, BodyRefusal> {
287    let Value::Object(mut fields) = body else {
288        return Err(BodyRefusal {
289            detail: "a spool command's body is a document of its fields".to_owned(),
290        });
291    };
292    let reason = reason_of(fields.get("reason").and_then(Value::as_str))?;
293    fields.insert("reason".to_owned(), Value::String(reason));
294    let tag = crate::operations::COMMAND_TAG;
295    for routed in [tag, "spool_id"] {
296        if fields.contains_key(routed) {
297            return Err(BodyRefusal {
298                detail: format!(
299                    "a spool command's body does not carry `{routed}`: the operation it is \
300                     sent to names it"
301                ),
302            });
303        }
304    }
305    let named = printobserver_types::serde_json::to_value(kind).map_err(|error| BodyRefusal {
306        detail: error.to_string(),
307    })?;
308    fields.insert(tag.to_owned(), named);
309    if let Some(spool_id) = spool_id {
310        fields.insert("spool_id".to_owned(), Value::String(spool_id.to_string()));
311    }
312    let command: SpoolCommand = printobserver_types::serde_json::from_value(Value::Object(fields))
313        .map_err(|error| BodyRefusal {
314            detail: format!("this is not a `{}` body: {error}", spool_command_name(kind)),
315        })?;
316    if command.kind() == kind {
317        Ok(command)
318    } else {
319        Err(BodyRefusal {
320            detail: format!("this body is not a `{}`", spool_command_name(kind)),
321        })
322    }
323}
324
325/// One command's own name, as the wire spells it.
326fn spool_command_name(kind: ActionKind) -> String {
327    printobserver_types::serde_json::to_value(kind)
328        .ok()
329        .and_then(|value| value.as_str().map(str::to_owned))
330        .unwrap_or_else(|| format!("{kind:?}"))
331}
332
333/// The actor a spool command's body claims, read before anything else of it,
334/// so the claim is held to the caller before the body is ruled on.
335///
336/// # Errors
337///
338/// Returns [`BodyRefusal`] when the body names no actor this system has.
339pub fn claimed_actor(body: &Map<String, Value>) -> Result<Actor, BodyRefusal> {
340    let Some(actor) = body.get("actor") else {
341        return missing("actor");
342    };
343    printobserver_types::serde_json::from_value(actor.clone()).map_err(|error| BodyRefusal {
344        detail: format!("`actor` is not an actor this system has: {error}"),
345    })
346}
347
348/// What a spool command answers, accepted or refused.
349///
350/// A refusal is the same shape and deliberately so: the decision carries the
351/// grant or the ledger's own reason, and the events are the record the refusal
352/// wrote.
353#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
354#[serde(crate = "printobserver_types::serde")]
355#[schemars(crate = "printobserver_types::schemars")]
356pub struct SpoolCommandAnswer {
357    /// The decision taken on the command.
358    pub decision: PolicyDecision,
359    /// The spool it was about, as the command left it, when there is one.
360    #[serde(skip_serializing_if = "Option::is_none")]
361    pub spool: Option<SpoolRecord>,
362    /// Every event it wrote, in the order they were written.
363    pub events: Vec<EventRecord>,
364}
365
366/// What the spools read answers.
367///
368/// `at_a_glance` is one line per spool, in the order `spools` lists them,
369/// composed here so that what is left on each spool is the first thing a
370/// reader of either rendering meets rather than a figure inside a whole
371/// record. Its name is what puts it first: both renderings walk an answer's
372/// fields in name order, ahead of `pending` and `spools`.
373#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
374#[serde(crate = "printobserver_types::serde")]
375#[schemars(crate = "printobserver_types::schemars")]
376pub struct SpoolsAnswer {
377    /// One line per spool in `spools`, in the same order.
378    pub at_a_glance: Vec<String>,
379    /// Every spool, retired ones only when asked for, most recently registered
380    /// first.
381    pub spools: Vec<SpoolRecord>,
382    /// Every charge held after a filament change nobody has confirmed, oldest
383    /// first: what the next spool loaded on that tool is charged.
384    pub pending: Vec<PendingCharge>,
385}
386
387impl SpoolsAnswer {
388    /// The answer for these spools and these held charges.
389    #[must_use]
390    pub fn of(spools: Vec<SpoolRecord>, pending: Vec<PendingCharge>) -> Self {
391        Self {
392            at_a_glance: spools.iter().map(at_a_glance).collect(),
393            spools,
394            pending,
395        }
396    }
397}
398
399/// One spool, in one line: its name, its material, what is left of what it
400/// held, where it is, whether its figure can be trusted, and whether it is
401/// retired.
402///
403/// `PLA white | PLA | 812.4 g of 1000.0 g left | on tool 0 | verified`, and
404/// for a spool whose figure is in doubt the oldest reason, with how many more
405/// it holds: `| unverified: uncharged_print (+1 more)`.
406#[must_use]
407pub fn at_a_glance(spool: &SpoolRecord) -> String {
408    let place = spool
409        .loaded_tool()
410        .map_or_else(|| "not loaded".to_owned(), |tool| format!("on tool {tool}"));
411    let trust = match &spool.trust {
412        SpoolTrust::Verified => "verified".to_owned(),
413        SpoolTrust::Unverified { marks } => {
414            let oldest = marks.first().map_or_else(String::new, |mark| {
415                printobserver_types::serde_json::to_value(mark.reason.kind())
416                    .ok()
417                    .and_then(|named| named.as_str().map(str::to_owned))
418                    .unwrap_or_default()
419            });
420            let more = marks.len().saturating_sub(1);
421            if more == 0 {
422                format!("unverified: {oldest}")
423            } else {
424                format!("unverified: {oldest} (+{more} more)")
425            }
426        }
427    };
428    let retired = if spool.is_retired() { " | retired" } else { "" };
429    format!(
430        "{} | {} | {:.1} g of {:.1} g left | {place} | {trust}{retired}",
431        spool.name, spool.material, spool.remaining_g, spool.initial_g
432    )
433}
434
435/// What one spool's read answers: the spool, and the newest of the printer's
436/// own events that name it.
437#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
438#[serde(crate = "printobserver_types::serde")]
439#[schemars(crate = "printobserver_types::schemars")]
440pub struct SpoolAnswer {
441    /// The spool, retired or not.
442    pub spool: SpoolRecord,
443    /// The newest timeline events naming it, newest first.
444    pub recent: Vec<EventRecord>,
445}
446
447/// What a printer history read answers: one page of the printer's own events.
448#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
449#[serde(crate = "printobserver_types::serde")]
450#[schemars(crate = "printobserver_types::schemars")]
451pub struct TimelineAnswer {
452    /// The events, newest first.
453    pub events: Vec<EventRecord>,
454    /// The cursor for the following, older page, given as `before`; absent
455    /// when there is none.
456    #[serde(skip_serializing_if = "Option::is_none")]
457    pub next: Option<EventId>,
458}
459
460/// What a filament check answers.
461#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
462#[serde(crate = "printobserver_types::serde")]
463#[schemars(crate = "printobserver_types::schemars")]
464pub struct PreflightAnswer {
465    /// What the check found, read now.
466    pub preflight: Preflight,
467}
468
469/// What a status read answers.
470#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
471#[serde(crate = "printobserver_types::serde")]
472#[schemars(crate = "printobserver_types::schemars")]
473pub struct StatusAnswer {
474    /// The print.
475    pub print: PrintRecord,
476    /// The printer, when a snapshot could be taken.
477    #[serde(skip_serializing_if = "Option::is_none")]
478    pub printer: Option<PrinterSnapshot>,
479    /// The job, when a snapshot could be taken.
480    #[serde(skip_serializing_if = "Option::is_none")]
481    pub job: Option<JobSnapshot>,
482    /// The supervision session watching it, when one is.
483    #[serde(skip_serializing_if = "Option::is_none")]
484    pub session: Option<SupervisionSession>,
485    /// The bounded interventions still in force.
486    pub interventions: Vec<Intervention>,
487}
488
489/// What a context read answers.
490///
491/// The latest image is **materialized** here rather than left as the handle
492/// [`PrintContext`] carries: the one thing a supervision turn does with an
493/// image is look at it, and a handle is not something anything can open. The
494/// path is absolute on this server's own filesystem, exactly as
495/// [`ImageAnswer`]'s is, and is absent when there is no image or when the
496/// record is intact and the file is not.
497#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
498#[serde(crate = "printobserver_types::serde")]
499#[schemars(crate = "printobserver_types::schemars")]
500pub struct ContextAnswer {
501    /// Everything a supervision turn is given about the print.
502    pub context: PrintContext,
503    /// Where the latest image's bytes are, absolute on this host.
504    #[serde(skip_serializing_if = "Option::is_none")]
505    pub image_path: Option<PathBuf>,
506}
507
508/// What a fresh look answers: the look, as the supervision core took it.
509///
510/// Its `image_path` is absolute on this server's own filesystem, exactly as
511/// [`ContextAnswer`]'s is.
512pub type LookAnswer = printobserver_core::Look;
513
514/// What an image read answers.
515///
516/// The path is absolute on this server's own filesystem, and is the whole of
517/// the answer about the bytes: nothing here renders them, encodes them or
518/// serves them. It is absent when the record is intact and the file is not,
519/// which is a different answer from there being no such image.
520#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
521#[serde(crate = "printobserver_types::serde")]
522#[schemars(crate = "printobserver_types::schemars")]
523pub struct ImageAnswer {
524    /// The record.
525    pub record: ImageRecord,
526    /// Where its bytes are, absolute on this host.
527    #[serde(skip_serializing_if = "Option::is_none")]
528    pub path: Option<PathBuf>,
529}
530
531impl From<ImageLookup> for ImageAnswer {
532    fn from(lookup: ImageLookup) -> Self {
533        match lookup {
534            ImageLookup::Found { record, path } => Self {
535                record,
536                path: Some(path),
537            },
538            ImageLookup::FileMissing { record } => Self { record, path: None },
539        }
540    }
541}
542
543/// What the prints read answers: every print, and the one the printer is
544/// running.
545///
546/// An open print's recorded `state` is the state it was opened in, which is
547/// `printing` whether or not the machine is paused now; what the machine is
548/// doing is the status read's answer.
549#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
550#[serde(crate = "printobserver_types::serde")]
551#[schemars(crate = "printobserver_types::schemars")]
552pub struct PrintsAnswer {
553    /// Every print this server holds, ended or not, most recently opened first.
554    pub prints: Vec<PrintRecord>,
555    /// The print the printer's current job belongs to, present exactly when the
556    /// printer reports a job it is printing or has paused. Absent when the
557    /// printer could not be read.
558    #[serde(skip_serializing_if = "Option::is_none")]
559    pub active: Option<PrintId>,
560}
561
562/// What a history read answers.
563#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
564#[serde(crate = "printobserver_types::serde")]
565#[schemars(crate = "printobserver_types::schemars")]
566pub struct HistoryAnswer {
567    /// The print's events, newest first.
568    pub events: Vec<EventRecord>,
569}
570
571/// What an events read answers: the events stored after its cursor that pass
572/// its filters, oldest first, and where the next read picks up.
573#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
574#[serde(crate = "printobserver_types::serde")]
575#[schemars(crate = "printobserver_types::schemars")]
576#[schemars(transform = cursor_is_always_sent)]
577pub struct EventsAnswer {
578    /// The events, oldest first in the order they were stored, each exactly as
579    /// a history read serves it.
580    pub events: Vec<EventRecord>,
581    /// The last event this read examined, whether or not it passed the
582    /// filters, given as `after` to read on from it; null when the log held
583    /// nothing to start after. Always sent, as null when it is that.
584    pub cursor: Option<EventId>,
585    /// The watched print's end as stored, whatever the filters said, and null
586    /// while it is open. Absent from a read that names no print.
587    // Marked as a field whose null is sent and means something its absence
588    // does not, so a generated client keeps the two apart.
589    #[serde(default, skip_serializing_if = "Option::is_none")]
590    #[schemars(extend("x-null-is-sent" = true))]
591    pub print_ended: Option<Option<PrintEnded>>,
592}
593
594/// Declare an events answer's `cursor` required, as the null it may be.
595///
596/// The derive reads an `Option` as a field that may be absent, and its own
597/// `required` attribute drops the null with the absence; this keeps the null.
598fn cursor_is_always_sent(schema: &mut printobserver_types::schemars::Schema) {
599    if let Some(Value::Array(required)) = schema.get_mut("required") {
600        required.push(Value::from("cursor"));
601    }
602}
603
604/// One print's end, as its `print_ended` event stored it.
605#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
606#[serde(crate = "printobserver_types::serde")]
607#[schemars(crate = "printobserver_types::schemars")]
608pub struct PrintEnded {
609    /// The `print_ended` event.
610    pub event_id: EventId,
611    /// When that event was received.
612    pub received_at: Timestamp,
613    /// How the print ended.
614    pub outcome: PrintOutcome,
615}
616
617/// What a manifest read or write answers.
618#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
619#[serde(crate = "printobserver_types::serde")]
620#[schemars(crate = "printobserver_types::schemars")]
621pub struct ManifestAnswer {
622    /// The manifest, when the print has one.
623    #[serde(skip_serializing_if = "Option::is_none")]
624    pub manifest: Option<JobManifest>,
625    /// Every range this manifest asked wider than the envelope allows, narrowed
626    /// to the envelope's — recorded on the print, so nobody has to wonder later
627    /// which bound applied.
628    pub narrowings: Vec<ManifestNarrowing>,
629}
630
631/// What this server answers when it will not do what it was asked.
632#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
633#[serde(crate = "printobserver_types::serde")]
634#[schemars(crate = "printobserver_types::schemars")]
635pub struct ErrorAnswer {
636    /// One line saying why, in the words of whatever refused it.
637    pub error: String,
638}
639
640impl ErrorAnswer {
641    /// One refusal, in its own words.
642    pub fn saying(detail: impl core::fmt::Display) -> Self {
643        Self {
644            error: detail.to_string(),
645        }
646    }
647}
648
649/// What the ingress answers a post it accepted.
650///
651/// It carries no field, because the only thing it could carry is that the post
652/// was accepted and this is the answer only an accepted post gets. It
653/// serializes as `{"accepted": true}`, which is what a caller reads.
654#[derive(Debug, Clone, Copy, PartialEq, Eq)]
655pub struct IngressAnswer;
656
657impl Serialize for IngressAnswer {
658    fn serialize<S: printobserver_types::serde::Serializer>(
659        &self,
660        serializer: S,
661    ) -> Result<S::Ok, S::Error> {
662        use printobserver_types::serde::ser::SerializeStruct as _;
663        let mut state = serializer.serialize_struct("IngressAnswer", 1)?;
664        state.serialize_field("accepted", &true)?;
665        state.end()
666    }
667}
668
669#[cfg(test)]
670mod tests {
671    use printobserver_core::{ActionKind, Actor, ImageRecord};
672    use printobserver_types::contract::Sample as _;
673
674    use super::{ActionBody, ErrorAnswer, ImageAnswer, ImageLookup};
675
676    /// A body carrying nothing but a reason and an actor.
677    fn bare() -> ActionBody {
678        ActionBody {
679            reason: Some("a test is asking".to_owned()),
680            actor: Actor::Operator,
681            duration_s: None,
682            factor: None,
683            target_c: None,
684            percent: None,
685            tool: None,
686            file_name: None,
687            manifest: None,
688            override_filament_check: false,
689            event_id: None,
690            disposition: None,
691            outcome: None,
692        }
693    }
694
695    /// Every action that needs a value it was not given is refused naming it.
696    ///
697    /// The walk is over the whole vocabulary rather than a sample: an action
698    /// that quietly defaulted a value nobody sent would be one this server
699    /// carried to a printer on the caller's behalf.
700    #[test]
701    fn every_action_that_needs_a_value_it_was_not_given_is_refused_naming_it() {
702        let needed = [
703            (ActionKind::StartPrint, "file_name"),
704            (ActionKind::SetFeedrateFactor, "factor"),
705            (ActionKind::SetFlowrateFactor, "factor"),
706            (ActionKind::SetToolTargetC, "tool"),
707            (ActionKind::SetBedTargetC, "target_c"),
708            (ActionKind::SetFanPercent, "percent"),
709            (ActionKind::AcknowledgeFailure, "event_id"),
710            (ActionKind::ClosePrint, "outcome"),
711        ];
712        for (kind, named) in needed {
713            let refusal = bare()
714                .into_action(kind)
715                .expect_err("this action needs a value the body does not carry");
716            assert!(
717                refusal.to_string().contains(named),
718                "{kind:?} was refused without naming `{named}`: {refusal}"
719            );
720        }
721    }
722
723    /// A spool command is no print action, so no print-action body is read as
724    /// one, whatever it carries.
725    #[test]
726    fn a_spool_command_kind_is_refused_as_a_print_action() {
727        for kind in [
728            ActionKind::RegisterSpool,
729            ActionKind::LoadSpool,
730            ActionKind::UnloadSpool,
731            ActionKind::AdjustSpool,
732            ActionKind::RetireSpool,
733        ] {
734            let refusal = bare()
735                .into_action(kind)
736                .expect_err("a spool command is not a print action");
737            assert!(
738                refusal.to_string().contains("spool command"),
739                "{kind:?} was refused without saying why: {refusal}"
740            );
741        }
742    }
743
744    /// The second value each two-valued action needs is named in its turn.
745    #[test]
746    fn the_second_value_a_two_valued_action_needs_is_named_in_its_turn() {
747        let mut starting = bare();
748        starting.file_name = Some(printobserver_types::FileName::new("a.gcode").expect("a name"));
749        assert!(
750            starting
751                .into_action(ActionKind::StartPrint)
752                .expect_err("a start needs a manifest")
753                .to_string()
754                .contains("manifest")
755        );
756
757        let mut tool = bare();
758        tool.tool = Some(0);
759        assert!(
760            tool.into_action(ActionKind::SetToolTargetC)
761                .expect_err("a tool target needs a temperature")
762                .to_string()
763                .contains("target_c")
764        );
765
766        let mut acknowledgement = bare();
767        acknowledgement.event_id = Some(printobserver_types::EventId::new());
768        assert!(
769            acknowledgement
770                .into_action(ActionKind::AcknowledgeFailure)
771                .expect_err("an acknowledgement needs a disposition")
772                .to_string()
773                .contains("disposition")
774        );
775    }
776
777    /// A reason that is nothing but whitespace is no reason.
778    #[test]
779    fn a_reason_that_is_nothing_but_whitespace_is_no_reason() {
780        let mut blank = bare();
781        blank.reason = Some("   ".to_owned());
782        assert!(blank.reason().is_err());
783        let mut absent = bare();
784        absent.reason = None;
785        assert!(absent.reason().is_err());
786        assert_eq!(bare().reason().expect("a reason"), "a test is asking");
787    }
788
789    /// An image whose file is gone answers the record and no path.
790    ///
791    /// A different answer from there being no such image, which is what tells a
792    /// caller the history is intact and the file is not.
793    #[test]
794    fn an_image_whose_file_is_gone_answers_the_record_and_no_path() {
795        let record = ImageRecord::sample_full();
796        let missing = ImageAnswer::from(ImageLookup::FileMissing {
797            record: record.clone(),
798        });
799        assert_eq!(missing.record, record);
800        assert_eq!(missing.path, None);
801
802        let found = ImageAnswer::from(ImageLookup::Found {
803            record: record.clone(),
804            path: "/var/lib/printobserver/images/ab/cd".into(),
805        });
806        assert_eq!(
807            found.path.as_deref(),
808            Some(std::path::Path::new("/var/lib/printobserver/images/ab/cd"))
809        );
810    }
811
812    /// A refusal answers in the words of whatever refused it.
813    #[test]
814    fn a_refusal_answers_in_the_words_of_whatever_refused_it() {
815        assert_eq!(
816            ErrorAnswer::saying("the disk is full").error,
817            "the disk is full"
818        );
819    }
820}