Skip to main content

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