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`]), and the two event kinds a session's opening and closing are
8//! written down under.
9//!
10//! May depend on: `printobserver-types` only. A port that named an
11//! implementation would stop being a port.
12//!
13//! # Opening a session is not a call of its own
14//!
15//! Opening or continuing is [`SupervisorPort::run_turn`]'s own doing, and the
16//! [`SessionPhase`] it answers is what says which happened. A separate open
17//! call would let a caller open a session it then never took a turn in.
18//!
19//! # Why the methods answer a boxed future
20//!
21//! Every method is asynchronous, and the trait is dyn-compatible and shareable
22//! across threads, because the supervision core holds every port behind
23//! `Arc<dyn Port>`. An `async fn` in a trait is not dyn-compatible, so each
24//! method answers a [`BoxFuture`] instead.
25
26pub mod assessment;
27pub mod session;
28
29use core::future::Future;
30use core::pin::Pin;
31use std::path::PathBuf;
32
33use printobserver_types::contract::Sample;
34use printobserver_types::schemars::JsonSchema;
35use printobserver_types::serde::{Deserialize, Serialize};
36use printobserver_types::{EventPayload, EventRecord, PrintId};
37
38pub use assessment::{AgentAssessment, Confidence};
39pub use session::{SessionPhase, SupervisionSession};
40
41/// A future this port's methods answer with, in the one shape a trait object
42/// can carry.
43pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
44
45/// What one supervision turn is asked to consider.
46#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
47#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
48#[schemars(crate = "printobserver_types::schemars")]
49pub struct TurnRequest {
50    /// The print the turn is about.
51    pub print_id: PrintId,
52    /// The event that prompted the turn.
53    pub event: EventRecord,
54    /// The absolute path of the image to look at, when there is one.
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub image_path: Option<PathBuf>,
57    /// The command the turn runs to read the print's context.
58    pub context_command: String,
59}
60
61/// What one supervision turn answered with.
62#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
63#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
64#[schemars(crate = "printobserver_types::schemars")]
65pub struct TurnOutcome {
66    /// The session the turn ran in.
67    pub session: SupervisionSession,
68    /// Whether this turn opened that session or continued it.
69    pub phase: SessionPhase,
70    /// The agent's written record of the turn.
71    pub assessment: AgentAssessment,
72}
73
74/// A supervision session was opened.
75#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
76#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
77#[schemars(crate = "printobserver_types::schemars")]
78pub struct SupervisionSessionOpenedPayload {
79    /// The session's own name in the harness.
80    pub session_name: String,
81    /// The identity the harness ran it under.
82    pub harness_identity: String,
83}
84
85impl EventPayload for SupervisionSessionOpenedPayload {
86    const KIND: &'static str = "supervision_session_opened";
87}
88
89impl Sample for SupervisionSessionOpenedPayload {
90    fn sample_full() -> Self {
91        Self {
92            session_name: "print-0191f0a0".to_owned(),
93            harness_identity: "printobserver-supervisor".to_owned(),
94        }
95    }
96}
97
98/// A supervision session was closed.
99#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
100#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
101#[schemars(crate = "printobserver_types::schemars")]
102pub struct SupervisionSessionClosedPayload {
103    /// The session's own name in the harness.
104    pub session_name: String,
105    /// Why it was closed.
106    pub close_reason: String,
107}
108
109impl EventPayload for SupervisionSessionClosedPayload {
110    const KIND: &'static str = "supervision_session_closed";
111}
112
113impl Sample for SupervisionSessionClosedPayload {
114    fn sample_full() -> Self {
115        Self {
116            session_name: "print-0191f0a0".to_owned(),
117            close_reason: "the print ended".to_owned(),
118        }
119    }
120}
121
122/// Why a supervision turn did not produce an assessment.
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub enum SupervisorError {
125    /// The agent answered something that failed validation.
126    InvalidAnswer {
127        /// What was wrong with the answer.
128        detail: String,
129    },
130    /// The harness refused the identity the turn ran under.
131    IdentityRefused {
132        /// What the harness said about it.
133        detail: String,
134    },
135    /// The harness could not be reached, or would not run a turn.
136    Unavailable {
137        /// What went wrong.
138        detail: String,
139    },
140    /// The turn took too long.
141    TimedOut,
142}
143
144impl core::fmt::Display for SupervisorError {
145    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
146        match self {
147            Self::InvalidAnswer { detail } => {
148                write!(formatter, "the agent's answer failed validation: {detail}")
149            }
150            Self::IdentityRefused { detail } => {
151                write!(formatter, "the harness refused the identity: {detail}")
152            }
153            Self::Unavailable { detail } => {
154                write!(formatter, "the harness is unavailable: {detail}")
155            }
156            Self::TimedOut => formatter.write_str("the turn took too long"),
157        }
158    }
159}
160
161impl core::error::Error for SupervisorError {}
162
163/// The port the supervising agent is reached through.
164///
165/// Every method is asynchronous, the trait is dyn-compatible, and it is
166/// shareable across threads, because the supervision core holds it behind
167/// `Arc<dyn SupervisorPort>`.
168pub trait SupervisorPort: Send + Sync {
169    /// Run one supervision turn, opening the session if it is not open.
170    fn run_turn(&self, request: TurnRequest)
171    -> BoxFuture<'_, Result<TurnOutcome, SupervisorError>>;
172
173    /// Close the session watching one print.
174    fn close_session(
175        &self,
176        print_id: PrintId,
177        close_reason: String,
178    ) -> BoxFuture<'_, Result<(), SupervisorError>>;
179}