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