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