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::{AgentContext, DetectorHealth};
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 context is the agent's view of it ([`AgentContext`]): each fact once,
578/// as it is now, and the events newer than the one asked `since`.
579///
580/// The latest image is **materialized** here rather than left as the handle
581/// [`printobserver_core::PrintContext`] carries: the one thing a supervision turn does with an
582/// image is look at it, and a handle is not something anything can open. The
583/// path is absolute on this server's own filesystem, exactly as
584/// [`ImageAnswer`]'s is, and is absent when there is no image or when the
585/// record is intact and the file is not.
586#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
587#[serde(crate = "printobserver_types::serde")]
588#[schemars(crate = "printobserver_types::schemars")]
589pub struct ContextAnswer {
590    /// Everything a supervision turn is given about the print.
591    pub context: AgentContext,
592    /// Where the latest image's bytes are, absolute on this host.
593    #[serde(skip_serializing_if = "Option::is_none")]
594    pub image_path: Option<PathBuf>,
595}
596
597/// What a fresh look answers: the look, as the supervision core took it.
598///
599/// Its `image_path` is absolute on this server's own filesystem, exactly as
600/// [`ContextAnswer`]'s is.
601pub type LookAnswer = printobserver_core::Look;
602
603/// What an image read answers.
604///
605/// The path is absolute on this server's own filesystem, and is the whole of
606/// the answer about the bytes: nothing here renders them, encodes them or
607/// serves them. It is absent when the record is intact and the file is not,
608/// which is a different answer from there being no such image.
609#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
610#[serde(crate = "printobserver_types::serde")]
611#[schemars(crate = "printobserver_types::schemars")]
612pub struct ImageAnswer {
613    /// The record.
614    pub record: ImageRecord,
615    /// Where its bytes are, absolute on this host.
616    #[serde(skip_serializing_if = "Option::is_none")]
617    pub path: Option<PathBuf>,
618}
619
620impl From<ImageLookup> for ImageAnswer {
621    fn from(lookup: ImageLookup) -> Self {
622        match lookup {
623            ImageLookup::Found { record, path } => Self {
624                record,
625                path: Some(path),
626            },
627            ImageLookup::FileMissing { record } => Self { record, path: None },
628        }
629    }
630}
631
632/// What the prints read answers: every print, and the one the printer is
633/// running.
634///
635/// An open print's recorded `state` is the state it was opened in, which is
636/// `printing` whether or not the machine is paused now; what the machine is
637/// doing is the status read's answer.
638#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
639#[serde(crate = "printobserver_types::serde")]
640#[schemars(crate = "printobserver_types::schemars")]
641pub struct PrintsAnswer {
642    /// Every print this server holds, ended or not, most recently opened first.
643    pub prints: Vec<PrintRecord>,
644    /// The print the printer's current job belongs to, present exactly when the
645    /// printer reports a job it is printing or has paused. Absent when the
646    /// printer could not be read.
647    #[serde(skip_serializing_if = "Option::is_none")]
648    pub active: Option<PrintId>,
649}
650
651/// What a history read answers.
652#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
653#[serde(crate = "printobserver_types::serde")]
654#[schemars(crate = "printobserver_types::schemars")]
655pub struct HistoryAnswer {
656    /// The print's events, newest first.
657    pub events: Vec<EventRecord>,
658}
659
660/// What an events read answers: the events stored after its cursor that pass
661/// its filters, oldest first, and where the next read picks up.
662#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
663#[serde(crate = "printobserver_types::serde")]
664#[schemars(crate = "printobserver_types::schemars")]
665#[schemars(transform = cursor_is_always_sent)]
666pub struct EventsAnswer {
667    /// The events, oldest first in the order they were stored, each exactly as
668    /// a history read serves it.
669    pub events: Vec<EventRecord>,
670    /// The last event this read examined, whether or not it passed the
671    /// filters, given as `after` to read on from it; null when the log held
672    /// nothing to start after. Always sent, as null when it is that.
673    pub cursor: Option<EventId>,
674    /// The watched print's end as stored, whatever the filters said, and null
675    /// while it is open. Absent from a read that names no print.
676    // Marked as a field whose null is sent and means something its absence
677    // does not, so a generated client keeps the two apart.
678    #[serde(default, skip_serializing_if = "Option::is_none")]
679    #[schemars(extend("x-null-is-sent" = true))]
680    pub print_ended: Option<Option<PrintEnded>>,
681}
682
683/// Declare an events answer's `cursor` required, as the null it may be.
684///
685/// The derive reads an `Option` as a field that may be absent, and its own
686/// `required` attribute drops the null with the absence; this keeps the null.
687fn cursor_is_always_sent(schema: &mut printobserver_types::schemars::Schema) {
688    if let Some(Value::Array(required)) = schema.get_mut("required") {
689        required.push(Value::from("cursor"));
690    }
691}
692
693/// One print's end, as its `print_ended` event stored it.
694#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
695#[serde(crate = "printobserver_types::serde")]
696#[schemars(crate = "printobserver_types::schemars")]
697pub struct PrintEnded {
698    /// The `print_ended` event.
699    pub event_id: EventId,
700    /// When that event was received.
701    pub received_at: Timestamp,
702    /// How the print ended.
703    pub outcome: PrintOutcome,
704}
705
706/// What a manifest read or write answers.
707#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
708#[serde(crate = "printobserver_types::serde")]
709#[schemars(crate = "printobserver_types::schemars")]
710pub struct ManifestAnswer {
711    /// The manifest, when the print has one.
712    #[serde(skip_serializing_if = "Option::is_none")]
713    pub manifest: Option<JobManifest>,
714    /// Every range this manifest asked wider than the envelope allows, narrowed
715    /// to the envelope's — recorded on the print, so nobody has to wonder later
716    /// which bound applied.
717    pub narrowings: Vec<ManifestNarrowing>,
718}
719
720/// What this server answers when it will not do what it was asked.
721#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
722#[serde(crate = "printobserver_types::serde")]
723#[schemars(crate = "printobserver_types::schemars")]
724pub struct ErrorAnswer {
725    /// One line saying why, in the words of whatever refused it.
726    pub error: String,
727}
728
729impl ErrorAnswer {
730    /// One refusal, in its own words.
731    pub fn saying(detail: impl core::fmt::Display) -> Self {
732        Self {
733            error: detail.to_string(),
734        }
735    }
736}
737
738/// What the ingress answers a post it accepted.
739///
740/// It carries no field, because the only thing it could carry is that the post
741/// was accepted and this is the answer only an accepted post gets. It
742/// serializes as `{"accepted": true}`, which is what a caller reads.
743#[derive(Debug, Clone, Copy, PartialEq, Eq)]
744pub struct IngressAnswer;
745
746impl Serialize for IngressAnswer {
747    fn serialize<S: printobserver_types::serde::Serializer>(
748        &self,
749        serializer: S,
750    ) -> Result<S::Ok, S::Error> {
751        use printobserver_types::serde::ser::SerializeStruct as _;
752        let mut state = serializer.serialize_struct("IngressAnswer", 1)?;
753        state.serialize_field("accepted", &true)?;
754        state.end()
755    }
756}
757
758#[cfg(test)]
759mod tests {
760    use printobserver_core::{ActionKind, Actor, ImageRecord};
761    use printobserver_types::contract::Sample as _;
762
763    use super::{ActionBody, ErrorAnswer, ImageAnswer, ImageLookup};
764
765    /// A body carrying nothing but a reason and an actor.
766    fn bare() -> ActionBody {
767        ActionBody {
768            reason: Some("a test is asking".to_owned()),
769            actor: Actor::Operator,
770            duration_s: None,
771            factor: None,
772            target_c: None,
773            percent: None,
774            tool: None,
775            file_name: None,
776            manifest: None,
777            override_filament_check: false,
778            override_material_check: false,
779            override_sheet_check: false,
780            event_id: None,
781            disposition: None,
782            outcome: None,
783        }
784    }
785
786    /// Every action that needs a value it was not given is refused naming it.
787    ///
788    /// The walk is over the whole vocabulary rather than a sample: an action
789    /// that quietly defaulted a value nobody sent would be one this server
790    /// carried to a printer on the caller's behalf.
791    #[test]
792    fn every_action_that_needs_a_value_it_was_not_given_is_refused_naming_it() {
793        let needed = [
794            (ActionKind::StartPrint, "file_name"),
795            (ActionKind::SetFeedrateFactor, "factor"),
796            (ActionKind::SetFlowrateFactor, "factor"),
797            (ActionKind::SetToolTargetC, "tool"),
798            (ActionKind::SetBedTargetC, "target_c"),
799            (ActionKind::SetFanPercent, "percent"),
800            (ActionKind::AcknowledgeFailure, "event_id"),
801            (ActionKind::ClosePrint, "outcome"),
802        ];
803        for (kind, named) in needed {
804            let refusal = bare()
805                .into_action(kind)
806                .expect_err("this action needs a value the body does not carry");
807            assert!(
808                refusal.to_string().contains(named),
809                "{kind:?} was refused without naming `{named}`: {refusal}"
810            );
811        }
812    }
813
814    /// A spool command is no print action, so no print-action body is read as
815    /// one, whatever it carries.
816    #[test]
817    fn a_spool_command_kind_is_refused_as_a_print_action() {
818        for kind in [
819            ActionKind::RegisterSpool,
820            ActionKind::LoadSpool,
821            ActionKind::UnloadSpool,
822            ActionKind::AdjustSpool,
823            ActionKind::RetireSpool,
824        ] {
825            let refusal = bare()
826                .into_action(kind)
827                .expect_err("a spool command is not a print action");
828            assert!(
829                refusal.to_string().contains("spool command"),
830                "{kind:?} was refused without saying why: {refusal}"
831            );
832        }
833    }
834
835    /// The second value each two-valued action needs is named in its turn.
836    #[test]
837    fn the_second_value_a_two_valued_action_needs_is_named_in_its_turn() {
838        let mut starting = bare();
839        starting.file_name = Some(printobserver_types::FileName::new("a.gcode").expect("a name"));
840        assert!(
841            starting
842                .into_action(ActionKind::StartPrint)
843                .expect_err("a start needs a manifest")
844                .to_string()
845                .contains("manifest")
846        );
847
848        let mut tool = bare();
849        tool.tool = Some(0);
850        assert!(
851            tool.into_action(ActionKind::SetToolTargetC)
852                .expect_err("a tool target needs a temperature")
853                .to_string()
854                .contains("target_c")
855        );
856
857        let mut acknowledgement = bare();
858        acknowledgement.event_id = Some(printobserver_types::EventId::new());
859        assert!(
860            acknowledgement
861                .into_action(ActionKind::AcknowledgeFailure)
862                .expect_err("an acknowledgement needs a disposition")
863                .to_string()
864                .contains("disposition")
865        );
866    }
867
868    /// A reason that is nothing but whitespace is no reason.
869    #[test]
870    fn a_reason_that_is_nothing_but_whitespace_is_no_reason() {
871        let mut blank = bare();
872        blank.reason = Some("   ".to_owned());
873        assert!(blank.reason().is_err());
874        let mut absent = bare();
875        absent.reason = None;
876        assert!(absent.reason().is_err());
877        assert_eq!(bare().reason().expect("a reason"), "a test is asking");
878    }
879
880    /// An image whose file is gone answers the record and no path.
881    ///
882    /// A different answer from there being no such image, which is what tells a
883    /// caller the history is intact and the file is not.
884    #[test]
885    fn an_image_whose_file_is_gone_answers_the_record_and_no_path() {
886        let record = ImageRecord::sample_full();
887        let missing = ImageAnswer::from(ImageLookup::FileMissing {
888            record: record.clone(),
889        });
890        assert_eq!(missing.record, record);
891        assert_eq!(missing.path, None);
892
893        let found = ImageAnswer::from(ImageLookup::Found {
894            record: record.clone(),
895            path: "/var/lib/printobserver/images/ab/cd".into(),
896        });
897        assert_eq!(
898            found.path.as_deref(),
899            Some(std::path::Path::new("/var/lib/printobserver/images/ab/cd"))
900        );
901    }
902
903    /// A refusal answers in the words of whatever refused it.
904    #[test]
905    fn a_refusal_answers_in_the_words_of_whatever_refused_it() {
906        assert_eq!(
907            ErrorAnswer::saying("the disk is full").error,
908            "the disk is full"
909        );
910    }
911}