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