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    /// When its source says it was taken, when its source says: a frame a camera
296    /// held over from earlier is not a frame of now.
297    pub captured_at: Option<Timestamp>,
298}
299
300/// Why a retrieved frame is not one to hand anybody as a picture of the
301/// print.
302#[derive(Debug, Clone, PartialEq, Eq)]
303pub enum FrameFault {
304    /// It decoded, and it is near-uniform: a camera showing nothing.
305    Blank {
306        /// What was measured, in words.
307        detail: String,
308    },
309    /// It is not a whole image: a strict decode refused it.
310    Undecodable {
311        /// Why the decode refused it, in words.
312        detail: String,
313    },
314}
315
316impl core::fmt::Display for FrameFault {
317    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
318        match self {
319            Self::Blank { detail } => write!(formatter, "the frame is blank: {detail}"),
320            Self::Undecodable { detail } => {
321                write!(formatter, "the frame does not decode: {detail}")
322            }
323        }
324    }
325}
326
327/// Why a body could not be read, or an image could not be retrieved.
328#[derive(Debug, Clone, PartialEq, Eq)]
329pub enum VisionError {
330    /// The body could not be read, and here it is.
331    Malformed {
332        /// One line saying why it could not be read.
333        detail: String,
334        /// The bytes exactly as received, so that the body is not lost.
335        raw: RawBytes,
336    },
337    /// The source took too long.
338    TimedOut,
339    /// What arrived is larger than this port will read.
340    TooLarge {
341        /// The limit, in bytes.
342        limit: i64,
343    },
344    /// What arrived is a content type this port does not accept.
345    UnacceptableContentType {
346        /// The content type that arrived.
347        content_type: String,
348    },
349    /// The source answered, with a status other than success.
350    ///
351    /// Carried apart from [`VisionError::Unreachable`], because what a caller
352    /// does next depends on what was answered: a camera answering `500` is a
353    /// camera that may answer the next request, and one answering `404` was
354    /// asked for something it does not have.
355    Status {
356        /// What was asked and what it answered, in words.
357        detail: String,
358        /// The HTTP status code it answered.
359        status: u16,
360        /// The start of the body it answered with, as text: at most
361        /// [`STATUS_EXCERPT_MAX_BYTES`] of it, read by [`body_excerpt`].
362        excerpt: String,
363    },
364    /// The source could not be reached at all.
365    Unreachable {
366        /// What went wrong reaching it.
367        detail: String,
368    },
369    /// The adapter was given nothing to reach the provider with for this.
370    NotConfigured {
371        /// What is missing, naming the configuration it would be read from.
372        detail: String,
373    },
374}
375
376impl core::fmt::Display for VisionError {
377    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
378        match self {
379            Self::Malformed { detail, raw } => {
380                write!(formatter, "the body could not be read ({detail}); {raw}")
381            }
382            Self::TimedOut => formatter.write_str("the source took too long"),
383            Self::TooLarge { limit } => {
384                write!(
385                    formatter,
386                    "what arrived is larger than the {limit} byte limit"
387                )
388            }
389            Self::UnacceptableContentType { content_type } => {
390                write!(
391                    formatter,
392                    "{content_type} is not a content type this port accepts"
393                )
394            }
395            Self::Status {
396                detail, excerpt, ..
397            } => {
398                if excerpt.is_empty() {
399                    write!(formatter, "the source refused the request: {detail}")
400                } else {
401                    write!(
402                        formatter,
403                        "the source refused the request: {detail}, saying `{excerpt}`"
404                    )
405                }
406            }
407            Self::Unreachable { detail } => {
408                write!(formatter, "the source is unreachable: {detail}")
409            }
410            Self::NotConfigured { detail } => {
411                write!(
412                    formatter,
413                    "the provider is not configured for this: {detail}"
414                )
415            }
416        }
417    }
418}
419
420impl VisionError {
421    /// Whether the source answered a server error, `500` to `599`: the one
422    /// answer a fetch may be asked again for, because it says the source is
423    /// there and could not answer this time.
424    #[must_use]
425    pub const fn is_server_error(&self) -> bool {
426        matches!(self, Self::Status { status, .. } if *status >= 500 && *status <= 599)
427    }
428}
429
430impl core::error::Error for VisionError {}
431
432/// The most bytes of a refusing answer's body a [`VisionError::Status`]
433/// carries.
434///
435/// Enough for the line a camera server answers a failure with — go2rtc's
436/// `exit status 69` among them — and little enough that a server answering a
437/// whole page of HTML costs a history record nothing.
438pub const STATUS_EXCERPT_MAX_BYTES: usize = 256;
439
440/// The start of a refusing answer's body, as the text a
441/// [`VisionError::Status`] carries.
442///
443/// At most [`STATUS_EXCERPT_MAX_BYTES`] of the bytes are read; bytes that are
444/// not UTF-8 are replaced rather than dropped, every control character is a
445/// space, and the text is trimmed — and then cut back to the last whole
446/// character within [`STATUS_EXCERPT_MAX_BYTES`], because a replaced byte is
447/// three bytes of text. A body of nothing is an excerpt of nothing.
448#[must_use]
449pub fn body_excerpt(bytes: &[u8]) -> String {
450    let taken = &bytes[..bytes.len().min(STATUS_EXCERPT_MAX_BYTES)];
451    let text = match core::str::from_utf8(taken) {
452        Ok(text) => text.to_owned(),
453        // A cut through a character leaves an incomplete sequence at the end,
454        // which is dropped; anything else that is not UTF-8 is replaced.
455        Err(error) if error.error_len().is_none() => {
456            String::from_utf8_lossy(&taken[..error.valid_up_to()]).into_owned()
457        }
458        Err(_) => String::from_utf8_lossy(taken).into_owned(),
459    };
460    let mut excerpt: String = text
461        .chars()
462        .map(|letter| if letter.is_control() { ' ' } else { letter })
463        .collect::<String>()
464        .trim()
465        .to_owned();
466    if excerpt.len() > STATUS_EXCERPT_MAX_BYTES {
467        let mut end = STATUS_EXCERPT_MAX_BYTES;
468        while !excerpt.is_char_boundary(end) {
469            end -= 1;
470        }
471        excerpt.truncate(end);
472        excerpt.truncate(excerpt.trim_end().len());
473    }
474    excerpt
475}
476
477/// The port external observations arrive through.
478///
479/// Every method is asynchronous, the trait is dyn-compatible, and it is
480/// shareable across threads, because the supervision core holds it behind
481/// `Arc<dyn VisionPort>`.
482pub trait VisionPort: Send + Sync {
483    /// Read a received body into an event under this adapter's own kind.
484    fn normalize(
485        &self,
486        body: RawBytes,
487        content_type: Option<String>,
488    ) -> BoxFuture<'_, Result<NormalizedAlert, VisionError>>;
489
490    /// Retrieve the image a source URL names.
491    fn fetch_image(&self, source_url: String) -> BoxFuture<'_, Result<FetchedImage, VisionError>>;
492
493    /// Tell the provider one of its detections has been handled.
494    ///
495    /// A detector that paused a print and was never told the pause was dealt
496    /// with may stay silent about that print for the rest of it; this is what
497    /// re-arms it once the print has been adjusted and resumed.
498    fn clear_detection(&self, detection: Detection) -> BoxFuture<'_, Result<(), VisionError>>;
499
500    /// Judge one retrieved frame as a picture of the print, answering it back
501    /// when it is one and why not otherwise.
502    ///
503    /// An implementation that does not judge frames answers every one back,
504    /// which is what one that does not override this does.
505    fn judge_frame(&self, image: FetchedImage) -> BoxFuture<'_, Result<FetchedImage, FrameFault>> {
506        Box::pin(async move { Ok(image) })
507    }
508}