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};
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}
98
99impl Sample for TurnSituation {
100    fn sample_full() -> Self {
101        Self {
102            printer_state: Some(PrinterState::Paused),
103            detector_warned: Some(false),
104            detector_paused_the_print: Some(true),
105            arrived_while_busy: vec![EventRecord::sample_full()],
106        }
107    }
108
109    fn sample_minimal() -> Self {
110        Self::default()
111    }
112}
113
114/// What one supervision turn answered with.
115#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
116#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
117#[schemars(crate = "printobserver_types::schemars")]
118pub struct TurnOutcome {
119    /// The session the turn ran in.
120    pub session: SupervisionSession,
121    /// Whether this turn opened that session or continued it.
122    pub phase: SessionPhase,
123    /// The agent's written record of the turn.
124    pub assessment: AgentAssessment,
125}
126
127/// A supervision session was opened.
128#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
129#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
130#[schemars(crate = "printobserver_types::schemars")]
131pub struct SupervisionSessionOpenedPayload {
132    /// The session's own name in the harness.
133    pub session_name: String,
134    /// The identity the harness ran it under.
135    pub harness_identity: String,
136}
137
138impl EventPayload for SupervisionSessionOpenedPayload {
139    const KIND: &'static str = "supervision_session_opened";
140}
141
142impl Sample for SupervisionSessionOpenedPayload {
143    fn sample_full() -> Self {
144        Self {
145            session_name: "print-0191f0a0".to_owned(),
146            harness_identity: "printobserver-supervisor".to_owned(),
147        }
148    }
149}
150
151/// A supervision session was closed.
152#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
153#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
154#[schemars(crate = "printobserver_types::schemars")]
155pub struct SupervisionSessionClosedPayload {
156    /// The session's own name in the harness.
157    pub session_name: String,
158    /// Why it was closed.
159    pub close_reason: String,
160}
161
162impl EventPayload for SupervisionSessionClosedPayload {
163    const KIND: &'static str = "supervision_session_closed";
164}
165
166impl Sample for SupervisionSessionClosedPayload {
167    fn sample_full() -> Self {
168        Self {
169            session_name: "print-0191f0a0".to_owned(),
170            close_reason: "the print ended".to_owned(),
171        }
172    }
173}
174
175/// Why a supervision turn did not produce an assessment.
176#[derive(Debug, Clone, PartialEq, Eq)]
177pub enum SupervisorError {
178    /// The agent answered something that failed validation.
179    InvalidAnswer {
180        /// What was wrong with the answer.
181        detail: String,
182    },
183    /// The harness refused the identity the turn ran under.
184    IdentityRefused {
185        /// What the harness said about it.
186        detail: String,
187    },
188    /// The harness could not be reached, or would not run a turn.
189    Unavailable {
190        /// What went wrong.
191        detail: String,
192    },
193    /// The turn took too long.
194    TimedOut,
195}
196
197impl core::fmt::Display for SupervisorError {
198    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
199        match self {
200            Self::InvalidAnswer { detail } => {
201                write!(formatter, "the agent's answer failed validation: {detail}")
202            }
203            Self::IdentityRefused { detail } => {
204                write!(formatter, "the harness refused the identity: {detail}")
205            }
206            Self::Unavailable { detail } => {
207                write!(formatter, "the harness is unavailable: {detail}")
208            }
209            Self::TimedOut => formatter.write_str("the turn took too long"),
210        }
211    }
212}
213
214impl core::error::Error for SupervisorError {}
215
216/// The port the supervising agent is reached through.
217///
218/// Every method is asynchronous, the trait is dyn-compatible, and it is
219/// shareable across threads, because the supervision core holds it behind
220/// `Arc<dyn SupervisorPort>`.
221pub trait SupervisorPort: Send + Sync {
222    /// Run one supervision turn, opening the session if it is not open.
223    ///
224    /// `access` issues each run of the turn the credential it authenticates
225    /// to the server with; see [`access`].
226    fn run_turn(
227        &self,
228        request: TurnRequest,
229        access: Arc<dyn TurnAccess>,
230    ) -> BoxFuture<'_, Result<TurnOutcome, SupervisorError>>;
231
232    /// Close the session watching one print.
233    fn close_session(
234        &self,
235        print_id: PrintId,
236        close_reason: String,
237    ) -> BoxFuture<'_, Result<(), SupervisorError>>;
238}