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 this system's own event vocabulary and for
5//! retrieving the image one names, the two shapes those methods carry, and that
6//! port's own error type.
7//!
8//! May depend on: `printobserver-types` only. A port that named an
9//! implementation would stop being a port.
10//!
11//! # This port is normalization and retrieval only
12//!
13//! Ingress transport belongs to the server: nothing here listens, routes or
14//! authenticates. A body arrives here already received, and what leaves is
15//! either a [`NormalizedAlert`] in this system's own vocabulary or a
16//! [`VisionError`] saying why one could not be made.
17//!
18//! # Why the methods answer a boxed future
19//!
20//! Every method is asynchronous, and the trait is dyn-compatible and shareable
21//! across threads, because the supervision core holds all four ports behind
22//! `Arc<dyn Port>`. An `async fn` in a trait is not dyn-compatible, so each
23//! method answers a [`BoxFuture`] instead.
24
25use core::future::Future;
26use core::pin::Pin;
27
28use printobserver_types::schemars::JsonSchema;
29use printobserver_types::serde::{Deserialize, Serialize};
30use printobserver_types::{EventKind, EventPayload, EventSource, RawBytes, Timestamp};
31
32/// A future this port's methods answer with, in the one shape a trait object
33/// can carry.
34pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
35
36/// One external body, read into this system's own event vocabulary.
37///
38/// `kind` and `payload` are the one closed pair
39/// [`EventPayload`](printobserver_types::EventPayload) declares, so a
40/// normalization naming one kind while carrying another's payload is
41/// unrepresentable here as it is in the store.
42#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
43#[serde(crate = "printobserver_types::serde")]
44#[schemars(crate = "printobserver_types::schemars")]
45pub struct NormalizedAlert {
46    /// Where it came from.
47    pub source: EventSource,
48    /// When it was received.
49    pub received_at: Timestamp,
50    /// The kind and the payload, which are one closed pair.
51    #[serde(flatten)]
52    pub payload: EventPayload,
53    /// The bytes exactly as received.
54    pub raw: RawBytes,
55    /// The image this alert names, when it names one.
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub image_url: Option<String>,
58}
59
60impl NormalizedAlert {
61    /// Which event this is, read off the payload it carries.
62    #[must_use]
63    pub const fn kind(&self) -> EventKind {
64        self.payload.kind()
65    }
66}
67
68/// One image, as it was retrieved.
69#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
70#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
71#[schemars(crate = "printobserver_types::schemars")]
72pub struct FetchedImage {
73    /// The image's bytes, exactly as served.
74    pub bytes: RawBytes,
75    /// The content type it was served as.
76    pub content_type: String,
77}
78
79/// Why a body could not be read, or an image could not be retrieved.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub enum VisionError {
82    /// The body could not be read, and here it is.
83    Malformed {
84        /// One line saying why it could not be read.
85        detail: String,
86        /// The bytes exactly as received, so that the body is not lost.
87        raw: RawBytes,
88    },
89    /// The source took too long.
90    TimedOut,
91    /// What arrived is larger than this port will read.
92    TooLarge {
93        /// The limit, in bytes.
94        limit: i64,
95    },
96    /// What arrived is a content type this port does not accept.
97    UnacceptableContentType {
98        /// The content type that arrived.
99        content_type: String,
100    },
101    /// The source could not be reached at all.
102    Unreachable {
103        /// What went wrong reaching it.
104        detail: String,
105    },
106}
107
108impl core::fmt::Display for VisionError {
109    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
110        match self {
111            Self::Malformed { detail, raw } => {
112                write!(formatter, "the body could not be read ({detail}); {raw}")
113            }
114            Self::TimedOut => formatter.write_str("the source took too long"),
115            Self::TooLarge { limit } => {
116                write!(
117                    formatter,
118                    "what arrived is larger than the {limit} byte limit"
119                )
120            }
121            Self::UnacceptableContentType { content_type } => {
122                write!(
123                    formatter,
124                    "{content_type} is not a content type this port accepts"
125                )
126            }
127            Self::Unreachable { detail } => {
128                write!(formatter, "the source is unreachable: {detail}")
129            }
130        }
131    }
132}
133
134impl core::error::Error for VisionError {}
135
136/// The port external observations arrive through.
137///
138/// Every method is asynchronous, the trait is dyn-compatible, and it is
139/// shareable across threads, because the supervision core holds it behind
140/// `Arc<dyn VisionPort>`.
141pub trait VisionPort: Send + Sync {
142    /// Read a received body into this system's own event vocabulary.
143    fn normalize(
144        &self,
145        body: RawBytes,
146        content_type: Option<String>,
147    ) -> BoxFuture<'_, Result<NormalizedAlert, VisionError>>;
148
149    /// Retrieve the image a source URL names.
150    fn fetch_image(&self, source_url: String) -> BoxFuture<'_, Result<FetchedImage, VisionError>>;
151}