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