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