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::store::ImageLookup;
14use printobserver_core::{
15    AcknowledgementDisposition, ActionKind, ActionRecord, Actor, ImageRecord, Intervention,
16    JobManifest, ManifestNarrowing, PendingCharge, PolicyDecision, Preflight, PrintOutcome,
17    PrintRecord, SpoolCommand, SpoolId, SpoolRecord, SpoolTrust,
18};
19use printobserver_core::{DetectorHealth, PrintContext};
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    /// The failure detector's health, and since when it has been so.
488    pub detector: DetectorHealth,
489}
490
491/// What a context read answers.
492///
493/// The latest image is **materialized** here rather than left as the handle
494/// [`PrintContext`] carries: the one thing a supervision turn does with an
495/// image is look at it, and a handle is not something anything can open. The
496/// path is absolute on this server's own filesystem, exactly as
497/// [`ImageAnswer`]'s is, and is absent when there is no image or when the
498/// record is intact and the file is not.
499#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
500#[serde(crate = "printobserver_types::serde")]
501#[schemars(crate = "printobserver_types::schemars")]
502pub struct ContextAnswer {
503    /// Everything a supervision turn is given about the print.
504    pub context: PrintContext,
505    /// Where the latest image's bytes are, absolute on this host.
506    #[serde(skip_serializing_if = "Option::is_none")]
507    pub image_path: Option<PathBuf>,
508}
509
510/// What a fresh look answers: the look, as the supervision core took it.
511///
512/// Its `image_path` is absolute on this server's own filesystem, exactly as
513/// [`ContextAnswer`]'s is.
514pub type LookAnswer = printobserver_core::Look;
515
516/// What an image read answers.
517///
518/// The path is absolute on this server's own filesystem, and is the whole of
519/// the answer about the bytes: nothing here renders them, encodes them or
520/// serves them. It is absent when the record is intact and the file is not,
521/// which is a different answer from there being no such image.
522#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
523#[serde(crate = "printobserver_types::serde")]
524#[schemars(crate = "printobserver_types::schemars")]
525pub struct ImageAnswer {
526    /// The record.
527    pub record: ImageRecord,
528    /// Where its bytes are, absolute on this host.
529    #[serde(skip_serializing_if = "Option::is_none")]
530    pub path: Option<PathBuf>,
531}
532
533impl From<ImageLookup> for ImageAnswer {
534    fn from(lookup: ImageLookup) -> Self {
535        match lookup {
536            ImageLookup::Found { record, path } => Self {
537                record,
538                path: Some(path),
539            },
540            ImageLookup::FileMissing { record } => Self { record, path: None },
541        }
542    }
543}
544
545/// What the prints read answers: every print, and the one the printer is
546/// running.
547///
548/// An open print's recorded `state` is the state it was opened in, which is
549/// `printing` whether or not the machine is paused now; what the machine is
550/// doing is the status read's answer.
551#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
552#[serde(crate = "printobserver_types::serde")]
553#[schemars(crate = "printobserver_types::schemars")]
554pub struct PrintsAnswer {
555    /// Every print this server holds, ended or not, most recently opened first.
556    pub prints: Vec<PrintRecord>,
557    /// The print the printer's current job belongs to, present exactly when the
558    /// printer reports a job it is printing or has paused. Absent when the
559    /// printer could not be read.
560    #[serde(skip_serializing_if = "Option::is_none")]
561    pub active: Option<PrintId>,
562}
563
564/// What a history read answers.
565#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
566#[serde(crate = "printobserver_types::serde")]
567#[schemars(crate = "printobserver_types::schemars")]
568pub struct HistoryAnswer {
569    /// The print's events, newest first.
570    pub events: Vec<EventRecord>,
571}
572
573/// What an events read answers: the events stored after its cursor that pass
574/// its filters, oldest first, and where the next read picks up.
575#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
576#[serde(crate = "printobserver_types::serde")]
577#[schemars(crate = "printobserver_types::schemars")]
578#[schemars(transform = cursor_is_always_sent)]
579pub struct EventsAnswer {
580    /// The events, oldest first in the order they were stored, each exactly as
581    /// a history read serves it.
582    pub events: Vec<EventRecord>,
583    /// The last event this read examined, whether or not it passed the
584    /// filters, given as `after` to read on from it; null when the log held
585    /// nothing to start after. Always sent, as null when it is that.
586    pub cursor: Option<EventId>,
587    /// The watched print's end as stored, whatever the filters said, and null
588    /// while it is open. Absent from a read that names no print.
589    // Marked as a field whose null is sent and means something its absence
590    // does not, so a generated client keeps the two apart.
591    #[serde(default, skip_serializing_if = "Option::is_none")]
592    #[schemars(extend("x-null-is-sent" = true))]
593    pub print_ended: Option<Option<PrintEnded>>,
594}
595
596/// Declare an events answer's `cursor` required, as the null it may be.
597///
598/// The derive reads an `Option` as a field that may be absent, and its own
599/// `required` attribute drops the null with the absence; this keeps the null.
600fn cursor_is_always_sent(schema: &mut printobserver_types::schemars::Schema) {
601    if let Some(Value::Array(required)) = schema.get_mut("required") {
602        required.push(Value::from("cursor"));
603    }
604}
605
606/// One print's end, as its `print_ended` event stored it.
607#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
608#[serde(crate = "printobserver_types::serde")]
609#[schemars(crate = "printobserver_types::schemars")]
610pub struct PrintEnded {
611    /// The `print_ended` event.
612    pub event_id: EventId,
613    /// When that event was received.
614    pub received_at: Timestamp,
615    /// How the print ended.
616    pub outcome: PrintOutcome,
617}
618
619/// What a manifest read or write answers.
620#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
621#[serde(crate = "printobserver_types::serde")]
622#[schemars(crate = "printobserver_types::schemars")]
623pub struct ManifestAnswer {
624    /// The manifest, when the print has one.
625    #[serde(skip_serializing_if = "Option::is_none")]
626    pub manifest: Option<JobManifest>,
627    /// Every range this manifest asked wider than the envelope allows, narrowed
628    /// to the envelope's — recorded on the print, so nobody has to wonder later
629    /// which bound applied.
630    pub narrowings: Vec<ManifestNarrowing>,
631}
632
633/// What this server answers when it will not do what it was asked.
634#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
635#[serde(crate = "printobserver_types::serde")]
636#[schemars(crate = "printobserver_types::schemars")]
637pub struct ErrorAnswer {
638    /// One line saying why, in the words of whatever refused it.
639    pub error: String,
640}
641
642impl ErrorAnswer {
643    /// One refusal, in its own words.
644    pub fn saying(detail: impl core::fmt::Display) -> Self {
645        Self {
646            error: detail.to_string(),
647        }
648    }
649}
650
651/// What the ingress answers a post it accepted.
652///
653/// It carries no field, because the only thing it could carry is that the post
654/// was accepted and this is the answer only an accepted post gets. It
655/// serializes as `{"accepted": true}`, which is what a caller reads.
656#[derive(Debug, Clone, Copy, PartialEq, Eq)]
657pub struct IngressAnswer;
658
659impl Serialize for IngressAnswer {
660    fn serialize<S: printobserver_types::serde::Serializer>(
661        &self,
662        serializer: S,
663    ) -> Result<S::Ok, S::Error> {
664        use printobserver_types::serde::ser::SerializeStruct as _;
665        let mut state = serializer.serialize_struct("IngressAnswer", 1)?;
666        state.serialize_field("accepted", &true)?;
667        state.end()
668    }
669}
670
671#[cfg(test)]
672mod tests {
673    use printobserver_core::{ActionKind, Actor, ImageRecord};
674    use printobserver_types::contract::Sample as _;
675
676    use super::{ActionBody, ErrorAnswer, ImageAnswer, ImageLookup};
677
678    /// A body carrying nothing but a reason and an actor.
679    fn bare() -> ActionBody {
680        ActionBody {
681            reason: Some("a test is asking".to_owned()),
682            actor: Actor::Operator,
683            duration_s: None,
684            factor: None,
685            target_c: None,
686            percent: None,
687            tool: None,
688            file_name: None,
689            manifest: None,
690            override_filament_check: false,
691            event_id: None,
692            disposition: None,
693            outcome: None,
694        }
695    }
696
697    /// Every action that needs a value it was not given is refused naming it.
698    ///
699    /// The walk is over the whole vocabulary rather than a sample: an action
700    /// that quietly defaulted a value nobody sent would be one this server
701    /// carried to a printer on the caller's behalf.
702    #[test]
703    fn every_action_that_needs_a_value_it_was_not_given_is_refused_naming_it() {
704        let needed = [
705            (ActionKind::StartPrint, "file_name"),
706            (ActionKind::SetFeedrateFactor, "factor"),
707            (ActionKind::SetFlowrateFactor, "factor"),
708            (ActionKind::SetToolTargetC, "tool"),
709            (ActionKind::SetBedTargetC, "target_c"),
710            (ActionKind::SetFanPercent, "percent"),
711            (ActionKind::AcknowledgeFailure, "event_id"),
712            (ActionKind::ClosePrint, "outcome"),
713        ];
714        for (kind, named) in needed {
715            let refusal = bare()
716                .into_action(kind)
717                .expect_err("this action needs a value the body does not carry");
718            assert!(
719                refusal.to_string().contains(named),
720                "{kind:?} was refused without naming `{named}`: {refusal}"
721            );
722        }
723    }
724
725    /// A spool command is no print action, so no print-action body is read as
726    /// one, whatever it carries.
727    #[test]
728    fn a_spool_command_kind_is_refused_as_a_print_action() {
729        for kind in [
730            ActionKind::RegisterSpool,
731            ActionKind::LoadSpool,
732            ActionKind::UnloadSpool,
733            ActionKind::AdjustSpool,
734            ActionKind::RetireSpool,
735        ] {
736            let refusal = bare()
737                .into_action(kind)
738                .expect_err("a spool command is not a print action");
739            assert!(
740                refusal.to_string().contains("spool command"),
741                "{kind:?} was refused without saying why: {refusal}"
742            );
743        }
744    }
745
746    /// The second value each two-valued action needs is named in its turn.
747    #[test]
748    fn the_second_value_a_two_valued_action_needs_is_named_in_its_turn() {
749        let mut starting = bare();
750        starting.file_name = Some(printobserver_types::FileName::new("a.gcode").expect("a name"));
751        assert!(
752            starting
753                .into_action(ActionKind::StartPrint)
754                .expect_err("a start needs a manifest")
755                .to_string()
756                .contains("manifest")
757        );
758
759        let mut tool = bare();
760        tool.tool = Some(0);
761        assert!(
762            tool.into_action(ActionKind::SetToolTargetC)
763                .expect_err("a tool target needs a temperature")
764                .to_string()
765                .contains("target_c")
766        );
767
768        let mut acknowledgement = bare();
769        acknowledgement.event_id = Some(printobserver_types::EventId::new());
770        assert!(
771            acknowledgement
772                .into_action(ActionKind::AcknowledgeFailure)
773                .expect_err("an acknowledgement needs a disposition")
774                .to_string()
775                .contains("disposition")
776        );
777    }
778
779    /// A reason that is nothing but whitespace is no reason.
780    #[test]
781    fn a_reason_that_is_nothing_but_whitespace_is_no_reason() {
782        let mut blank = bare();
783        blank.reason = Some("   ".to_owned());
784        assert!(blank.reason().is_err());
785        let mut absent = bare();
786        absent.reason = None;
787        assert!(absent.reason().is_err());
788        assert_eq!(bare().reason().expect("a reason"), "a test is asking");
789    }
790
791    /// An image whose file is gone answers the record and no path.
792    ///
793    /// A different answer from there being no such image, which is what tells a
794    /// caller the history is intact and the file is not.
795    #[test]
796    fn an_image_whose_file_is_gone_answers_the_record_and_no_path() {
797        let record = ImageRecord::sample_full();
798        let missing = ImageAnswer::from(ImageLookup::FileMissing {
799            record: record.clone(),
800        });
801        assert_eq!(missing.record, record);
802        assert_eq!(missing.path, None);
803
804        let found = ImageAnswer::from(ImageLookup::Found {
805            record: record.clone(),
806            path: "/var/lib/printobserver/images/ab/cd".into(),
807        });
808        assert_eq!(
809            found.path.as_deref(),
810            Some(std::path::Path::new("/var/lib/printobserver/images/ab/cd"))
811        );
812    }
813
814    /// A refusal answers in the words of whatever refused it.
815    #[test]
816    fn a_refusal_answers_in_the_words_of_whatever_refused_it() {
817        assert_eq!(
818            ErrorAnswer::saying("the disk is full").error,
819            "the disk is full"
820        );
821    }
822}