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};
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    /// What the supervisor knew about the moment the turn began.
64    #[serde(default)]
65    pub situation: TurnSituation,
66}
67
68/// What the supervisor knew about the moment one turn began, beside its event.
69///
70/// Facts rather than instructions: whether the print is paused, and whether
71/// the detector paused it itself, are exactly what decides whether an agent's
72/// adjustment would be applied to a moving print or held until it moves again.
73/// Every field is written out, a fact nobody knows as `null`, so that the
74/// prompt it fills has one shape whatever was known.
75#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
76#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
77#[schemars(crate = "printobserver_types::schemars")]
78pub struct TurnSituation {
79    /// The printer's state when the turn began, in the printer contract's own
80    /// vocabulary — a state it does not name as `{"unknown": "<the printer's
81    /// word>"}` — null when the printer could not be read.
82    #[serde(default)]
83    pub printer_state: Option<PrinterState>,
84    /// Whether the detector only warned, null when the event is not one of its
85    /// detections.
86    #[serde(default)]
87    pub detector_warned: Option<bool>,
88    /// Whether the detector paused the print itself, null when the event is
89    /// not one of its detections.
90    #[serde(default)]
91    pub detector_paused_the_print: Option<bool>,
92    /// Events for this print that arrived while its previous turn was running
93    /// and that turn never took, oldest first. The turn's own event is the
94    /// newest of them, and is not repeated here.
95    #[serde(default)]
96    pub arrived_while_busy: Vec<EventRecord>,
97    /// What the printer watch noticed that prompted this turn — how the print
98    /// ended, what the printer did on its own after it, that the camera gave
99    /// no usable frame, that the failure detector stopped answering — in
100    /// words beginning with the event's kind; null when the turn was prompted
101    /// by anything else.
102    #[serde(default)]
103    pub noticed: Option<String>,
104    /// When the frame an alert brought was captured, which its source says or the
105    /// moment it answered; absent when the event says so itself or has no frame.
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub frame_captured_at: Option<Timestamp>,
108}
109
110impl Sample for TurnSituation {
111    fn sample_full() -> Self {
112        Self {
113            printer_state: Some(PrinterState::Paused),
114            detector_warned: Some(false),
115            detector_paused_the_print: Some(true),
116            arrived_while_busy: vec![EventRecord::sample_full()],
117            noticed: Some(
118                "print_ended: the print ended interrupted, the printer reporting Offline \
119                 (the print reached Offline)"
120                    .to_owned(),
121            ),
122            frame_captured_at: Some(Timestamp::sample_full()),
123        }
124    }
125
126    fn sample_minimal() -> Self {
127        Self::default()
128    }
129}
130
131/// What one supervision turn answered with.
132#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
133#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
134#[schemars(crate = "printobserver_types::schemars")]
135pub struct TurnOutcome {
136    /// The session the turn ran in.
137    pub session: SupervisionSession,
138    /// Whether this turn opened that session or continued it.
139    pub phase: SessionPhase,
140    /// The agent's written record of the turn.
141    pub assessment: AgentAssessment,
142}
143
144/// A supervision session was opened.
145#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
146#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
147#[schemars(crate = "printobserver_types::schemars")]
148pub struct SupervisionSessionOpenedPayload {
149    /// The session's own name in the harness.
150    pub session_name: String,
151    /// The identity the harness ran it under.
152    pub harness_identity: String,
153}
154
155impl EventPayload for SupervisionSessionOpenedPayload {
156    const KIND: &'static str = "supervision_session_opened";
157}
158
159impl Sample for SupervisionSessionOpenedPayload {
160    fn sample_full() -> Self {
161        Self {
162            session_name: "print-0191f0a0".to_owned(),
163            harness_identity: "printobserver-supervisor".to_owned(),
164        }
165    }
166}
167
168/// A supervision session was closed.
169#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
170#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
171#[schemars(crate = "printobserver_types::schemars")]
172pub struct SupervisionSessionClosedPayload {
173    /// The session's own name in the harness.
174    pub session_name: String,
175    /// Why it was closed.
176    pub close_reason: String,
177}
178
179impl EventPayload for SupervisionSessionClosedPayload {
180    const KIND: &'static str = "supervision_session_closed";
181}
182
183impl Sample for SupervisionSessionClosedPayload {
184    fn sample_full() -> Self {
185        Self {
186            session_name: "print-0191f0a0".to_owned(),
187            close_reason: "the print ended".to_owned(),
188        }
189    }
190}
191
192/// Why a supervision turn did not produce an assessment.
193#[derive(Debug, Clone, PartialEq, Eq)]
194pub enum SupervisorError {
195    /// The agent answered something that failed validation.
196    InvalidAnswer {
197        /// What was wrong with the answer.
198        detail: String,
199    },
200    /// The harness refused the identity the turn ran under.
201    IdentityRefused {
202        /// What the harness said about it.
203        detail: String,
204    },
205    /// The harness could not be reached, or would not run a turn.
206    Unavailable {
207        /// What went wrong.
208        detail: String,
209    },
210    /// The turn took too long.
211    TimedOut,
212}
213
214impl core::fmt::Display for SupervisorError {
215    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
216        match self {
217            Self::InvalidAnswer { detail } => {
218                write!(formatter, "the agent's answer failed validation: {detail}")
219            }
220            Self::IdentityRefused { detail } => {
221                write!(formatter, "the harness refused the identity: {detail}")
222            }
223            Self::Unavailable { detail } => {
224                write!(formatter, "the harness is unavailable: {detail}")
225            }
226            Self::TimedOut => formatter.write_str("the turn took too long"),
227        }
228    }
229}
230
231impl core::error::Error for SupervisorError {}
232
233/// The port the supervising agent is reached through.
234///
235/// Every method is asynchronous, the trait is dyn-compatible, and it is
236/// shareable across threads, because the supervision core holds it behind
237/// `Arc<dyn SupervisorPort>`.
238pub trait SupervisorPort: Send + Sync {
239    /// Run one supervision turn, opening the session if it is not open.
240    ///
241    /// `access` issues each run of the turn the credential it authenticates
242    /// to the server with; see [`access`].
243    fn run_turn(
244        &self,
245        request: TurnRequest,
246        access: Arc<dyn TurnAccess>,
247    ) -> BoxFuture<'_, Result<TurnOutcome, SupervisorError>>;
248
249    /// Close the session watching one print.
250    fn close_session(
251        &self,
252        print_id: PrintId,
253        close_reason: String,
254    ) -> BoxFuture<'_, Result<(), SupervisorError>>;
255}