printobserver_supervisor_api/lib.rs
1//! `printobserver-supervisor-api`.
2//!
3//! Owns: the port the supervising agent is reached through — the trait for
4//! running one supervision turn and for closing a session, the two shapes those
5//! methods carry, that port's own error type, the assessment vocabulary a turn
6//! answers with ([`assessment`]), which image a check was shown and why
7//! ([`image`]), the session a turn opens or continues
8//! ([`session`]), the credential each run of a turn is issued ([`access`]),
9//! and the two event kinds a session's opening and closing are written down
10//! under.
11//!
12//! May depend on: `printobserver-types` only. A port that named an
13//! implementation would stop being a port.
14//!
15//! # Opening a session is not a call of its own
16//!
17//! Opening or continuing is [`SupervisorPort::run_turn`]'s own doing, and the
18//! [`SessionPhase`] it answers is what says which happened. A separate open
19//! call would let a caller open a session it then never took a turn in.
20//!
21//! # Why the methods answer a boxed future
22//!
23//! Every method is asynchronous, and the trait is dyn-compatible and shareable
24//! across threads, because the supervision core holds every port behind
25//! `Arc<dyn Port>`. An `async fn` in a trait is not dyn-compatible, so each
26//! method answers a [`BoxFuture`] instead.
27
28pub mod access;
29pub mod assessment;
30pub mod image;
31pub mod session;
32
33use core::future::Future;
34use core::pin::Pin;
35use std::path::PathBuf;
36use std::sync::Arc;
37
38use printobserver_types::contract::Sample;
39use printobserver_types::schemars::JsonSchema;
40use printobserver_types::serde::{Deserialize, Serialize};
41use printobserver_types::{EventPayload, EventRecord, PrintId, PrinterState, Timestamp};
42
43pub use access::{CREDENTIAL_ENV, SERVER_ENV, TurnAccess, TurnPass, TurnSession};
44pub use assessment::{AgentAssessment, Confidence, Disposition};
45pub use image::{ImageFallback, ImageKind, WholeFrameReasonCode};
46pub use session::{SessionPhase, SupervisionSession};
47
48/// A future this port's methods answer with, in the one shape a trait object
49/// can carry.
50pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
51
52/// What one supervision turn is asked to consider.
53#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
54#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
55#[schemars(crate = "printobserver_types::schemars")]
56pub struct TurnRequest {
57 /// The print the turn is about.
58 pub print_id: PrintId,
59 /// The event that prompted the turn.
60 pub event: EventRecord,
61 /// The absolute path of the image to look at, when there is one.
62 #[serde(default, skip_serializing_if = "Option::is_none")]
63 pub image_path: Option<PathBuf>,
64 /// The command the turn runs to read the print's context.
65 pub context_command: String,
66 /// The print's context as the context command answered it when the turn
67 /// began, its events cut to those since the agent last answered: what the
68 /// turn decides from without running a command. Absent when no context
69 /// could be read.
70 ///
71 /// A document rather than the context's own type, because that type is the
72 /// supervision core's, which this port may not depend on: the core builds
73 /// it from its own context answer and nothing else.
74 #[serde(default, skip_serializing_if = "Option::is_none")]
75 pub facts: Option<
76 printobserver_types::serde_json::Map<String, printobserver_types::serde_json::Value>,
77 >,
78 /// What the supervisor knew about the moment the turn began.
79 #[serde(default)]
80 pub situation: TurnSituation,
81}
82
83/// What the supervisor knew about the moment one turn began, beside its event.
84///
85/// Facts rather than instructions: whether the print is paused, and whether
86/// the detector paused it itself, are exactly what decides whether an agent's
87/// adjustment would be applied to a moving print or held until it moves again.
88/// Every field is written out, a fact nobody knows as `null`, so that the
89/// prompt it fills has one shape whatever was known.
90#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
91#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
92#[schemars(crate = "printobserver_types::schemars")]
93pub struct TurnSituation {
94 /// The printer's state when the turn began, in the printer contract's own
95 /// vocabulary — a state it does not name as `{"unknown": "<the printer's
96 /// word>"}` — null when the printer could not be read.
97 #[serde(default)]
98 pub printer_state: Option<PrinterState>,
99 /// Whether the detector only warned, null when the event is not one of its
100 /// detections.
101 #[serde(default)]
102 pub detector_warned: Option<bool>,
103 /// Whether the detector paused the print itself, null when the event is
104 /// not one of its detections.
105 #[serde(default)]
106 pub detector_paused_the_print: Option<bool>,
107 /// Events for this print that arrived while its previous turn was running
108 /// and that turn never took, oldest first. The turn's own event is the
109 /// newest of them, and is not repeated here.
110 #[serde(default)]
111 pub arrived_while_busy: Vec<EventRecord>,
112 /// What the printer watch noticed that prompted this turn — how the print
113 /// ended, what the printer did on its own after it, that the camera gave
114 /// no usable frame, that the failure detector stopped answering — in
115 /// words beginning with the event's kind; null when the turn was prompted
116 /// by anything else.
117 #[serde(default)]
118 pub noticed: Option<String>,
119 /// When the frame an alert brought was captured, which its source says or the
120 /// moment it answered; absent when the event says so itself or has no frame.
121 #[serde(default, skip_serializing_if = "Option::is_none")]
122 pub frame_captured_at: Option<Timestamp>,
123 /// What the image attached to the prompt is, and why it is that one, in
124 /// one line; absent when no image is attached or what made it says
125 /// nothing.
126 #[serde(default, skip_serializing_if = "Option::is_none")]
127 pub image: Option<String>,
128 /// Which image is attached to the prompt; absent when none is.
129 #[serde(default, skip_serializing_if = "Option::is_none")]
130 pub image_kind: Option<ImageKind>,
131 /// Why the attached image is the whole frame; absent for the three-panel
132 /// image, when no image is attached, or when what made it gave no reason.
133 #[serde(default, skip_serializing_if = "Option::is_none")]
134 pub image_fallback: Option<ImageFallback>,
135}
136
137impl Sample for TurnSituation {
138 fn sample_full() -> Self {
139 Self {
140 printer_state: Some(PrinterState::Paused),
141 detector_warned: Some(false),
142 detector_paused_the_print: Some(true),
143 arrived_while_busy: vec![EventRecord::sample_full()],
144 noticed: Some(
145 "print_ended: the print ended interrupted, the printer reporting Offline \
146 (the print reached Offline)"
147 .to_owned(),
148 ),
149 frame_captured_at: Some(Timestamp::sample_full()),
150 image: Some(
151 "the three-panel check image: this layer's planned toolpath on the frame, \
152 a close-up of the part being printed, and the previous check's frame"
153 .to_owned(),
154 ),
155 image_kind: Some(ImageKind::WholeFrame),
156 image_fallback: Some(ImageFallback::sample_full()),
157 }
158 }
159
160 fn sample_minimal() -> Self {
161 Self::default()
162 }
163}
164
165/// What one supervision turn answered with.
166#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
167#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
168#[schemars(crate = "printobserver_types::schemars")]
169pub struct TurnOutcome {
170 /// The session the turn ran in.
171 pub session: SupervisionSession,
172 /// Whether this turn opened that session or continued it.
173 pub phase: SessionPhase,
174 /// The agent's written record of the turn.
175 pub assessment: AgentAssessment,
176}
177
178/// A supervision session was opened.
179#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
180#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
181#[schemars(crate = "printobserver_types::schemars")]
182pub struct SupervisionSessionOpenedPayload {
183 /// The session's own name in the harness.
184 pub session_name: String,
185 /// The identity the harness ran it under.
186 pub harness_identity: String,
187}
188
189impl EventPayload for SupervisionSessionOpenedPayload {
190 const KIND: &'static str = "supervision_session_opened";
191}
192
193impl Sample for SupervisionSessionOpenedPayload {
194 fn sample_full() -> Self {
195 Self {
196 session_name: "print-0191f0a0".to_owned(),
197 harness_identity: "printobserver-supervisor".to_owned(),
198 }
199 }
200}
201
202/// A supervision session was closed.
203#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
204#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
205#[schemars(crate = "printobserver_types::schemars")]
206pub struct SupervisionSessionClosedPayload {
207 /// The session's own name in the harness.
208 pub session_name: String,
209 /// Why it was closed.
210 pub close_reason: String,
211}
212
213impl EventPayload for SupervisionSessionClosedPayload {
214 const KIND: &'static str = "supervision_session_closed";
215}
216
217impl Sample for SupervisionSessionClosedPayload {
218 fn sample_full() -> Self {
219 Self {
220 session_name: "print-0191f0a0".to_owned(),
221 close_reason: "the print ended".to_owned(),
222 }
223 }
224}
225
226/// Why a supervision turn did not produce an assessment.
227#[derive(Debug, Clone, PartialEq, Eq)]
228pub enum SupervisorError {
229 /// The agent answered something that failed validation.
230 InvalidAnswer {
231 /// What was wrong with the answer.
232 detail: String,
233 },
234 /// The harness refused the identity the turn ran under.
235 IdentityRefused {
236 /// What the harness said about it.
237 detail: String,
238 },
239 /// The harness could not be reached, or would not run a turn.
240 Unavailable {
241 /// What went wrong.
242 detail: String,
243 },
244 /// The turn took too long.
245 TimedOut,
246}
247
248impl core::fmt::Display for SupervisorError {
249 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
250 match self {
251 Self::InvalidAnswer { detail } => {
252 write!(formatter, "the agent's answer failed validation: {detail}")
253 }
254 Self::IdentityRefused { detail } => {
255 write!(formatter, "the harness refused the identity: {detail}")
256 }
257 Self::Unavailable { detail } => {
258 write!(formatter, "the harness is unavailable: {detail}")
259 }
260 Self::TimedOut => formatter.write_str("the turn took too long"),
261 }
262 }
263}
264
265impl core::error::Error for SupervisorError {}
266
267/// The port the supervising agent is reached through.
268///
269/// Every method is asynchronous, the trait is dyn-compatible, and it is
270/// shareable across threads, because the supervision core holds it behind
271/// `Arc<dyn SupervisorPort>`.
272pub trait SupervisorPort: Send + Sync {
273 /// Run one supervision turn, opening the session if it is not open.
274 ///
275 /// `access` issues each run of the turn the credential it authenticates
276 /// to the server with; see [`access`].
277 fn run_turn(
278 &self,
279 request: TurnRequest,
280 access: Arc<dyn TurnAccess>,
281 ) -> BoxFuture<'_, Result<TurnOutcome, SupervisorError>>;
282
283 /// Close the session watching one print.
284 fn close_session(
285 &self,
286 print_id: PrintId,
287 close_reason: String,
288 ) -> BoxFuture<'_, Result<(), SupervisorError>>;
289
290 /// Answer once no idle work of this port on one print's session is under
291 /// way: at once when there is none, and otherwise when it ends.
292 ///
293 /// What the periodic observation awaits before it claims the print, so a
294 /// scheduled check does not cancel a compaction of the session it is about
295 /// to continue; every other event's turn starts at once. A port does all
296 /// its work inside a turn unless it says otherwise, which is why this
297 /// answers at once by default.
298 ///
299 /// # Errors
300 ///
301 /// None this default answers; a port whose wait could not be taken answers
302 /// [`SupervisorError::Unavailable`], and the check runs regardless.
303 fn idle_work_ended(&self, print_id: PrintId) -> BoxFuture<'_, Result<(), SupervisorError>> {
304 let _ = print_id;
305 Box::pin(core::future::ready(Ok(())))
306 }
307}