Skip to main content

printobserver_vision_api/
lib.rs

1//! `printobserver-vision-api`.
2//!
3//! Owns: the port external observations arrive through — the trait for
4//! normalizing a received body into an event under the adapter's own kind, for
5//! retrieving the image one names, and for telling the provider one of its
6//! detections was handled — the shapes those methods carry, that
7//! port's own error type, and the one event kind this port itself declares:
8//! [`MalformedExternalEventPayload`], a body no adapter could read, written
9//! down.
10//!
11//! May depend on: `printobserver-types` only. A port that named an
12//! implementation would stop being a port.
13//!
14//! # This port is normalization, retrieval and acknowledgement only
15//!
16//! Ingress transport belongs to the server: nothing here listens, routes or
17//! authenticates. A body arrives here already received, and what leaves is
18//! either a [`NormalizedAlert`] or a [`VisionError`] saying why one could not
19//! be made. The one thing this port sends the provider is
20//! [`VisionPort::clear_detection`]: a detector that paused a print and is never
21//! told the pause was dealt with may stay silent about that print for the rest
22//! of it.
23//!
24//! # This port is provider-neutral
25//!
26//! A [`NormalizedAlert`] carries an [`EventBody`] under whatever kind the
27//! adapter declares, and beside it the one thing the supervision domain reads
28//! off an alert: [`ProviderPrint`], the provider's own identifier for the print
29//! the alert is about. The supervision core correlates on that and never on a
30//! provider's payload by kind, which is what lets a second provider's adapter
31//! land without the core hearing of it.
32//!
33//! # Why the methods answer a boxed future
34//!
35//! Every method is asynchronous, and the trait is dyn-compatible and shareable
36//! across threads, because the supervision core holds every port behind
37//! `Arc<dyn Port>`. An `async fn` in a trait is not dyn-compatible, so each
38//! method answers a [`BoxFuture`] instead.
39
40use core::future::Future;
41use core::pin::Pin;
42
43use printobserver_types::contract::Sample;
44use printobserver_types::schemars::JsonSchema;
45use printobserver_types::serde::{Deserialize, Serialize};
46use printobserver_types::{EventBody, EventKind, EventPayload, EventSource, RawBytes, Timestamp};
47
48/// A future this port's methods answer with, in the one shape a trait object
49/// can carry.
50pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
51
52/// The provider's own identifier for the print an alert is about.
53///
54/// Held in the provider's representation — a 64-bit integer, which is what
55/// every provider this system has met uses — and named for what it is rather
56/// than for the provider, so that the supervision domain correlates on it
57/// without knowing whose it is.
58#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
59#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
60#[schemars(crate = "printobserver_types::schemars")]
61pub struct ProviderPrint {
62    /// The provider's own identifier for the print.
63    pub id: i64,
64    /// The file the provider named, when it named one.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub file_name: Option<String>,
67    /// When the provider says the print started, when it said.
68    ///
69    /// What tells this print's job from a later job of the same file that the
70    /// supervisor found before any alert about it arrived.
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub started_at: Option<Timestamp>,
73}
74
75/// An `http` or `https` address an image or a provider's API is reached at,
76/// as an operator wrote it down and this port has ruled on it.
77///
78/// There is no other way to hold one than [`WebAddress::new`], so a
79/// configuration carrying one carries an address naming a host over HTTP —
80/// never text that only begins like one, such as `http://?x` or `http://[`.
81#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
82pub struct WebAddress(String);
83
84impl WebAddress {
85    /// The address this text names.
86    ///
87    /// # Errors
88    ///
89    /// Answers why the text is not such an address, in words that never quote
90    /// it: the text may be a secret pasted into the wrong line.
91    pub fn new(text: &str) -> Result<Self, &'static str> {
92        let trimmed = text.trim();
93        let lowered = trimmed.to_ascii_lowercase();
94        let Some(rest) = ["http://", "https://"]
95            .iter()
96            .find_map(|scheme| lowered.strip_prefix(scheme))
97        else {
98            return Err("it must be an http:// or https:// URL");
99        };
100        if rest
101            .chars()
102            .any(|letter| letter.is_whitespace() || letter.is_control())
103        {
104            return Err("it carries a space or a control character, which no URL does");
105        }
106        let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
107        if !names_a_host(authority) {
108            return Err("it names no host, or names one no URL can");
109        }
110        Ok(Self(trimmed.to_owned()))
111    }
112
113    /// The address, as it was written down.
114    #[must_use]
115    pub fn as_str(&self) -> &str {
116        &self.0
117    }
118}
119
120impl core::fmt::Display for WebAddress {
121    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
122        formatter.write_str(&self.0)
123    }
124}
125
126/// Whether one URL's authority is a host, and a port when it carries one.
127///
128/// A host is an IPv6 address in brackets, which is parsed as one, or a name of
129/// dot-separated labels — each of letters, digits and hyphens, neither
130/// beginning nor ending with a hyphen — which an IPv4 address also is. A port
131/// is a colon and a number no greater than 65535. A user before an `@` is no
132/// part of an address this system is configured with.
133fn names_a_host(authority: &str) -> bool {
134    let (host_ok, port) = if let Some(bracketed) = authority.strip_prefix('[') {
135        let Some((inside, after)) = bracketed.split_once(']') else {
136            return false;
137        };
138        let port = if after.is_empty() {
139            None
140        } else if let Some(port) = after.strip_prefix(':') {
141            Some(port)
142        } else {
143            return false;
144        };
145        (inside.parse::<std::net::Ipv6Addr>().is_ok(), port)
146    } else {
147        let (host, port) = match authority.rsplit_once(':') {
148            Some((host, port)) => (host, Some(port)),
149            None => (authority, None),
150        };
151        (is_a_host_name(host), port)
152    };
153    let port_ok = port.is_none_or(|digits| {
154        !digits.is_empty()
155            && digits.chars().all(|digit| digit.is_ascii_digit())
156            && digits.parse::<u16>().is_ok()
157    });
158    host_ok && port_ok
159}
160
161/// Whether one host is a name of dot-separated labels, each of letters,
162/// digits and hyphens, neither beginning nor ending with a hyphen — or, when
163/// its last label is a number, an IPv4 address, as a URL reads such a host.
164fn is_a_host_name(host: &str) -> bool {
165    let numeric = host
166        .rsplit('.')
167        .next()
168        .is_some_and(|last| !last.is_empty() && last.chars().all(|digit| digit.is_ascii_digit()));
169    if numeric {
170        return host.parse::<std::net::Ipv4Addr>().is_ok();
171    }
172    !host.is_empty()
173        && host.split('.').all(|label| {
174            !label.is_empty()
175                && label.len() <= 63
176                && !label.starts_with('-')
177                && !label.ends_with('-')
178                && label
179                    .chars()
180                    .all(|letter| letter.is_ascii_alphanumeric() || letter == '-')
181        })
182}
183
184/// What a provider's failure detector did about a print, when an alert is one
185/// of its detections.
186///
187/// Named for what it is rather than for the provider, like [`ProviderPrint`]:
188/// whether the detector only warned, whether it paused the print itself, and
189/// the provider's own identifier for the printer, which is what telling it the
190/// detection was handled is addressed to.
191#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
192#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
193#[schemars(crate = "printobserver_types::schemars")]
194pub struct Detection {
195    /// Whether the detector called it a warning rather than a failure.
196    pub warning: bool,
197    /// Whether the detector paused the print itself before alerting.
198    pub paused_the_print: bool,
199    /// The provider's own identifier for the printer the detection is about.
200    pub provider_printer_id: i64,
201}
202
203/// Something an alert says the printer itself signalled, beside what the
204/// detector saw.
205///
206/// Named for what the printer did rather than for the provider that relayed
207/// it, like [`Detection`], so the supervision domain acts on it without knowing
208/// whose alert carried it.
209#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
210#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
211#[schemars(crate = "printobserver_types::schemars")]
212pub enum PrinterSignal {
213    /// The printer asked for its filament to be changed.
214    FilamentChange,
215}
216
217/// One external body, read into an event under the adapter's own kind.
218///
219/// `kind` and `payload` are the [`EventBody`] flattened into this shape, so an
220/// alert's wire form is the pair the store holds. `print` is what the
221/// supervision domain correlates on; an alert about no print carries none.
222#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
223#[serde(crate = "printobserver_types::serde")]
224#[schemars(crate = "printobserver_types::schemars")]
225pub struct NormalizedAlert {
226    /// Where it came from.
227    pub source: EventSource,
228    /// When it was received.
229    pub received_at: Timestamp,
230    /// The kind and the payload, flattened into this shape's own fields.
231    #[serde(flatten)]
232    pub body: EventBody,
233    /// The bytes exactly as received.
234    pub raw: RawBytes,
235    /// The image this alert names, when it names one.
236    #[serde(default, skip_serializing_if = "Option::is_none")]
237    pub image_url: Option<String>,
238    /// The provider's own identifier for the print this alert is about, and
239    /// the file it named, when the alert is about a print at all.
240    #[serde(default, skip_serializing_if = "Option::is_none")]
241    pub print: Option<ProviderPrint>,
242    /// What the provider's detector did, when this alert is one of its
243    /// detections.
244    #[serde(default, skip_serializing_if = "Option::is_none")]
245    pub detection: Option<Detection>,
246    /// What the printer itself signalled, when the alert relays a signal.
247    #[serde(default, skip_serializing_if = "Option::is_none")]
248    pub signal: Option<PrinterSignal>,
249}
250
251impl NormalizedAlert {
252    /// Which event this is.
253    #[must_use]
254    pub const fn kind(&self) -> &EventKind {
255        &self.body.kind
256    }
257}
258
259// The written-down form of `VisionError::Malformed`, which is why this port
260// declares it rather than any one adapter. Said here rather than in the
261// description, which is the contract's and travels into every client.
262/// An external body arrived that could not be read.
263///
264/// This kind always carries its `raw` bytes, and it exists so that an alert
265/// this system cannot read is written down rather than dropped.
266#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
267#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
268#[schemars(crate = "printobserver_types::schemars")]
269pub struct MalformedExternalEventPayload {
270    /// One line saying why the body could not be read.
271    pub detail: String,
272}
273
274impl EventPayload for MalformedExternalEventPayload {
275    const KIND: &'static str = "malformed_external_event";
276}
277
278impl Sample for MalformedExternalEventPayload {
279    fn sample_full() -> Self {
280        Self {
281            detail: "the body is not JSON: expected value at line 1 column 1".to_owned(),
282        }
283    }
284}
285
286/// One image, as it was retrieved.
287#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
288#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
289#[schemars(crate = "printobserver_types::schemars")]
290pub struct FetchedImage {
291    /// The image's bytes, exactly as served.
292    pub bytes: RawBytes,
293    /// The content type it was served as.
294    pub content_type: String,
295}
296
297/// Why a body could not be read, or an image could not be retrieved.
298#[derive(Debug, Clone, PartialEq, Eq)]
299pub enum VisionError {
300    /// The body could not be read, and here it is.
301    Malformed {
302        /// One line saying why it could not be read.
303        detail: String,
304        /// The bytes exactly as received, so that the body is not lost.
305        raw: RawBytes,
306    },
307    /// The source took too long.
308    TimedOut,
309    /// What arrived is larger than this port will read.
310    TooLarge {
311        /// The limit, in bytes.
312        limit: i64,
313    },
314    /// What arrived is a content type this port does not accept.
315    UnacceptableContentType {
316        /// The content type that arrived.
317        content_type: String,
318    },
319    /// The source could not be reached at all.
320    Unreachable {
321        /// What went wrong reaching it.
322        detail: String,
323    },
324    /// The adapter was given nothing to reach the provider with for this.
325    NotConfigured {
326        /// What is missing, naming the configuration it would be read from.
327        detail: String,
328    },
329}
330
331impl core::fmt::Display for VisionError {
332    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
333        match self {
334            Self::Malformed { detail, raw } => {
335                write!(formatter, "the body could not be read ({detail}); {raw}")
336            }
337            Self::TimedOut => formatter.write_str("the source took too long"),
338            Self::TooLarge { limit } => {
339                write!(
340                    formatter,
341                    "what arrived is larger than the {limit} byte limit"
342                )
343            }
344            Self::UnacceptableContentType { content_type } => {
345                write!(
346                    formatter,
347                    "{content_type} is not a content type this port accepts"
348                )
349            }
350            Self::Unreachable { detail } => {
351                write!(formatter, "the source is unreachable: {detail}")
352            }
353            Self::NotConfigured { detail } => {
354                write!(
355                    formatter,
356                    "the provider is not configured for this: {detail}"
357                )
358            }
359        }
360    }
361}
362
363impl core::error::Error for VisionError {}
364
365/// The port external observations arrive through.
366///
367/// Every method is asynchronous, the trait is dyn-compatible, and it is
368/// shareable across threads, because the supervision core holds it behind
369/// `Arc<dyn VisionPort>`.
370pub trait VisionPort: Send + Sync {
371    /// Read a received body into an event under this adapter's own kind.
372    fn normalize(
373        &self,
374        body: RawBytes,
375        content_type: Option<String>,
376    ) -> BoxFuture<'_, Result<NormalizedAlert, VisionError>>;
377
378    /// Retrieve the image a source URL names.
379    fn fetch_image(&self, source_url: String) -> BoxFuture<'_, Result<FetchedImage, VisionError>>;
380
381    /// Tell the provider one of its detections has been handled.
382    ///
383    /// A detector that paused a print and was never told the pause was dealt
384    /// with may stay silent about that print for the rest of it; this is what
385    /// re-arms it once the print has been adjusted and resumed.
386    fn clear_detection(&self, detection: Detection) -> BoxFuture<'_, Result<(), VisionError>>;
387}