Skip to main content

printobserver_core/
context.rs

1//! The one aggregate a caller and the agent both read.
2//!
3//! [`PrintContext`] is the supervision domain's own view of one print: the
4//! record, the printer and job as the printer port last reported them, the
5//! manifest and the bounds in force, the interventions still active, the
6//! events most recently written down — the print's own, and what the printer
7//! watch recorded of the machine since the print opened — the failure
8//! detector's health, and what the slicer planned at the job's current file
9//! position ([`crate::gcode_index`]). The loop collects it when it handles an
10//! event, holds it for the turn that event prompts, and answers it to the
11//! `context` operation, so what the agent reasons about is the state the event
12//! was handled at rather than whatever the machine has drifted to since.
13//!
14//! It is declared here rather than centrally because every field of it is
15//! this domain's to collect: a domain that adds a fact a turn should see edits
16//! this crate and regenerates the clients, and nothing central.
17
18use crate::gcode_index::SlicerPlan;
19use crate::records::{EffectiveBounds, Intervention, JobManifest, PrintRecord};
20use crate::watch::DetectorHealth;
21use printobserver_printer_api::{
22    HeaterSnapshot, JobError, JobSnapshot, PrinterSnapshot, PrinterState,
23};
24use printobserver_types::contract::Sample;
25use printobserver_types::schemars::JsonSchema;
26use printobserver_types::serde::{Deserialize, Serialize};
27use printobserver_types::serde_json::Value;
28use printobserver_types::{
29    EventId, EventKind, EventRecord, ImageRef, PrintId, Reported, Timestamp,
30};
31
32/// Everything a supervision turn is given about one print.
33#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
34#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
35#[schemars(crate = "printobserver_types::schemars")]
36pub struct PrintContext {
37    /// The print itself.
38    pub print: PrintRecord,
39    /// The printer, when a snapshot could be taken.
40    #[serde(default, skip_serializing_if = "Option::is_none")]
41    pub printer: Option<PrinterSnapshot>,
42    /// The job, when a snapshot could be taken.
43    #[serde(default, skip_serializing_if = "Option::is_none")]
44    pub job: Option<JobSnapshot>,
45    /// The manifest, when the print has one.
46    #[serde(default, skip_serializing_if = "Option::is_none")]
47    pub manifest: Option<JobManifest>,
48    /// The limits in force, so that the agent can see them before it asks.
49    pub bounds: EffectiveBounds,
50    /// The interventions still active.
51    pub interventions: Vec<Intervention>,
52    /// A bounded list of this print's events, newest first.
53    pub recent_events: Vec<EventRecord>,
54    /// The most recent image, when there is one.
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub latest_image: Option<ImageRef>,
57    /// The failure detector's health, and since when it has been so.
58    #[serde(default)]
59    pub detector: DetectorHealth,
60    /// What the slicer planned at the job's current file position, read from
61    /// the print's own G-code: absent when the file could not be read, or the
62    /// job is not this print's.
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub slicer: Option<SlicerPlan>,
65}
66
67impl Sample for PrintContext {
68    fn sample_full() -> Self {
69        Self {
70            print: PrintRecord::sample_full(),
71            printer: Some(PrinterSnapshot::sample_full()),
72            job: Some(JobSnapshot::sample_full()),
73            manifest: Some(JobManifest::sample_full()),
74            bounds: EffectiveBounds::sample_full(),
75            interventions: vec![Intervention::sample_full()],
76            recent_events: vec![EventRecord::sample_full()],
77            latest_image: Some(ImageRef::sample_full()),
78            detector: DetectorHealth::sample_full(),
79            slicer: Some(SlicerPlan::sample_full()),
80        }
81    }
82
83    fn sample_minimal() -> Self {
84        Self {
85            print: PrintRecord::sample_minimal(),
86            printer: None,
87            job: None,
88            manifest: None,
89            bounds: EffectiveBounds::sample_full(),
90            interventions: vec![],
91            recent_events: vec![],
92            latest_image: None,
93            detector: DetectorHealth::sample_minimal(),
94            slicer: None,
95        }
96    }
97}
98
99/// The payload fields a context's recent events leave out: the printer and job
100/// snapshots an observation took, which the context states once as they are
101/// now; the agent's own assessment, which its conversation already holds; and
102/// the bookkeeping no supervision decision reads.
103const UNREAD_PAYLOAD_FIELDS: [&str; 8] = [
104    "printer",
105    "job",
106    "assessment",
107    "interval_s",
108    "session_name",
109    "harness_identity",
110    "delivered",
111    "waited_s",
112];
113
114/// What a supervision turn reads about one print: [`PrintContext`] with each
115/// fact stated once, as it is now, and nothing no supervision decision reads.
116///
117/// Left out of it, each because no step of the skill, no check and no recorded
118/// case decides anything by it: the print's file, provider and times; the
119/// printer's and the job's own states (the print states it once); every heater's
120/// offset, the chamber and the time they were read; the printer's reported
121/// feedrate, flowrate and fan (the slicer's plan states the flow and fan in
122/// force, and no step reads the feedrate); the job's file, size, progress, time
123/// and position (the plan states where the print is); the manifest (its limits
124/// are the bounds); and the detector's health.
125///
126/// The printer and the job are stated here and nowhere in the events; each
127/// event is what happened, when, and what it changed; and asked `since` an
128/// event, only the events newer than it are carried, so a turn that has read
129/// the rest is not handed them again. `newest_event` is what the next read
130/// asks `since`.
131#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
132#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
133#[schemars(crate = "printobserver_types::schemars")]
134pub struct AgentContext {
135    /// The print.
136    pub print: AgentPrint,
137    /// The printer's heaters now, when they could be read.
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    pub printer: Option<AgentPrinter>,
140    /// The error the job stopped on, when it stopped on one.
141    #[serde(default, skip_serializing_if = "Option::is_none")]
142    pub job_error: Option<JobError>,
143    /// The limits in force, so that the agent can see them before it asks.
144    pub bounds: EffectiveBounds,
145    /// The interventions still active.
146    pub interventions: Vec<Intervention>,
147    /// This print's events newer than the one asked `since`, or its recent
148    /// ones when none was named, newest first.
149    pub recent_events: Vec<AgentEvent>,
150    /// The most recent image, whose path is answered beside the context and
151    /// whose record states its digest.
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub latest_image: Option<ImageRef>,
154    /// The newest event of this print's, which a later read asks `since`:
155    /// absent only when the print has none.
156    #[serde(default, skip_serializing_if = "Option::is_none")]
157    pub newest_event: Option<EventId>,
158    /// What the slicer planned at the job's current file position.
159    #[serde(default, skip_serializing_if = "Option::is_none")]
160    pub slicer: Option<SlicerPlan>,
161}
162
163/// The print a context is about.
164#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
165#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
166#[schemars(crate = "printobserver_types::schemars")]
167pub struct AgentPrint {
168    /// Its identifier.
169    pub id: PrintId,
170    /// What the printer was last found doing with it, or the state it ended in.
171    pub state: PrinterState,
172    /// Why it ended, once it has.
173    #[serde(default, skip_serializing_if = "Option::is_none")]
174    pub end_reason: Option<String>,
175}
176
177/// The printer's heaters as they are now.
178#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
179#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
180#[schemars(crate = "printobserver_types::schemars")]
181pub struct AgentPrinter {
182    /// Each tool's heater, in order.
183    #[serde(default, skip_serializing_if = "Vec::is_empty")]
184    pub tools: Vec<AgentHeater>,
185    /// The bed's heater, when it has one.
186    #[serde(default, skip_serializing_if = "Option::is_none")]
187    pub bed: Option<AgentHeater>,
188}
189
190/// One heater, in degrees Celsius: each reading absent when the printer did not
191/// report it, or reported one outside what a heater can read.
192#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
193#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
194#[schemars(crate = "printobserver_types::schemars")]
195pub struct AgentHeater {
196    /// The temperature it is at.
197    #[serde(default, skip_serializing_if = "Option::is_none")]
198    pub actual_c: Option<f64>,
199    /// The temperature it is driving towards.
200    #[serde(default, skip_serializing_if = "Option::is_none")]
201    pub target_c: Option<f64>,
202}
203
204/// One event of the print's, as a turn reads it: what happened, when, and the
205/// facts it changed.
206#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
207#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
208#[schemars(crate = "printobserver_types::schemars")]
209pub struct AgentEvent {
210    /// Its identifier, which a later read asks `since`.
211    pub id: EventId,
212    /// What kind of event it is.
213    pub kind: EventKind,
214    /// When it was received.
215    pub received_at: Timestamp,
216    /// What it carried, less the snapshots the context states once, the
217    /// agent's own assessment and the bookkeeping no decision reads.
218    #[serde(default, skip_serializing_if = "is_empty_payload")]
219    pub payload: Value,
220}
221
222/// Whether a payload says nothing.
223fn is_empty_payload(payload: &Value) -> bool {
224    match payload {
225        Value::Null => true,
226        Value::Object(fields) => fields.is_empty(),
227        _ => false,
228    }
229}
230
231/// The events a context read asked `since` one carries: that event, and the
232/// print's events newer than it, newest first.
233#[derive(Debug, Clone, Copy)]
234pub struct Since<'events> {
235    /// The event named.
236    pub event: EventId,
237    /// Every event of the print's newer than it, newest first.
238    pub newer: &'events [EventRecord],
239}
240
241impl PrintContext {
242    /// What a supervision turn reads of this context: its recent events, or
243    /// those `since` names when it names any.
244    #[must_use]
245    pub fn for_agent(&self, since: Option<Since<'_>>) -> AgentContext {
246        let heater = |heater: &HeaterSnapshot| AgentHeater {
247            actual_c: in_range(heater.actual_c.as_ref()),
248            target_c: in_range(heater.target_c.as_ref()),
249        };
250        let (events, newest_event) = match since {
251            Some(since) => (
252                since.newer,
253                Some(since.newer.first().map_or(since.event, |newest| newest.id)),
254            ),
255            None => (
256                self.recent_events.as_slice(),
257                self.recent_events.first().map(|newest| newest.id),
258            ),
259        };
260        AgentContext {
261            print: AgentPrint {
262                id: self.print.id,
263                state: self.print.state.clone(),
264                end_reason: self.print.end_reason.clone(),
265            },
266            printer: self.printer.as_ref().map(|printer| AgentPrinter {
267                tools: printer.tools.iter().map(heater).collect(),
268                bed: printer.bed.as_ref().map(heater),
269            }),
270            job_error: self.job.as_ref().and_then(|job| job.error.clone()),
271            bounds: self.bounds.clone(),
272            interventions: self.interventions.clone(),
273            recent_events: events.iter().map(agent_event).collect(),
274            latest_image: self.latest_image.clone(),
275            newest_event,
276            slicer: self.slicer.clone(),
277        }
278    }
279}
280
281/// The events newer than `since`, newest first, when `events` — newest first —
282/// holds it.
283#[must_use]
284pub fn newer_than(events: &[EventRecord], since: EventId) -> Option<&[EventRecord]> {
285    events
286        .iter()
287        .position(|event| event.id == since)
288        .map(|at| &events[..at])
289}
290
291/// A reading in range, as its value alone.
292fn in_range(reported: Option<&Reported<f64>>) -> Option<f64> {
293    reported
294        .filter(|reported| !reported.out_of_range())
295        .map(Reported::value)
296}
297
298/// One event, as a turn reads it.
299fn agent_event(event: &EventRecord) -> AgentEvent {
300    let mut payload = event.body.payload.clone();
301    if let Value::Object(fields) = &mut payload {
302        for unread in UNREAD_PAYLOAD_FIELDS {
303            fields.remove(unread);
304        }
305    }
306    AgentEvent {
307        id: event.id,
308        kind: event.kind().clone(),
309        received_at: event.received_at,
310        payload,
311    }
312}
313
314impl Sample for AgentContext {
315    fn sample_full() -> Self {
316        PrintContext::sample_full().for_agent(None)
317    }
318
319    fn sample_minimal() -> Self {
320        PrintContext::sample_minimal().for_agent(None)
321    }
322}