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