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