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 and
5//! for retrieving the image one names, the shapes those methods carry, that
6//! port's own error type, and the one event kind this port itself declares:
7//! [`MalformedExternalEventPayload`], a body no adapter could read, written
8//! down.
9//!
10//! May depend on: `printobserver-types` only. A port that named an
11//! implementation would stop being a port.
12//!
13//! # This port is normalization and retrieval only
14//!
15//! Ingress transport belongs to the server: nothing here listens, routes or
16//! authenticates. A body arrives here already received, and what leaves is
17//! either a [`NormalizedAlert`] or a [`VisionError`] saying why one could not
18//! be made.
19//!
20//! # This port is provider-neutral
21//!
22//! A [`NormalizedAlert`] carries an [`EventBody`] under whatever kind the
23//! adapter declares, and beside it the one thing the supervision domain reads
24//! off an alert: [`ProviderPrint`], the provider's own identifier for the print
25//! the alert is about. The supervision core correlates on that and never on a
26//! provider's payload by kind, which is what lets a second provider's adapter
27//! land without the core hearing of it.
28//!
29//! # Why the methods answer a boxed future
30//!
31//! Every method is asynchronous, and the trait is dyn-compatible and shareable
32//! across threads, because the supervision core holds every port behind
33//! `Arc<dyn Port>`. An `async fn` in a trait is not dyn-compatible, so each
34//! method answers a [`BoxFuture`] instead.
35
36use core::future::Future;
37use core::pin::Pin;
38
39use printobserver_types::contract::Sample;
40use printobserver_types::schemars::JsonSchema;
41use printobserver_types::serde::{Deserialize, Serialize};
42use printobserver_types::{EventBody, EventKind, EventPayload, EventSource, RawBytes, Timestamp};
43
44/// A future this port's methods answer with, in the one shape a trait object
45/// can carry.
46pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
47
48/// The provider's own identifier for the print an alert is about.
49///
50/// Held in the provider's representation — a 64-bit integer, which is what
51/// every provider this system has met uses — and named for what it is rather
52/// than for the provider, so that the supervision domain correlates on it
53/// without knowing whose it is.
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
55#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
56#[schemars(crate = "printobserver_types::schemars")]
57pub struct ProviderPrint {
58 /// The provider's own identifier for the print.
59 pub id: i64,
60 /// The file the provider named, when it named one.
61 #[serde(default, skip_serializing_if = "Option::is_none")]
62 pub file_name: Option<String>,
63}
64
65/// One external body, read into an event under the adapter's own kind.
66///
67/// `kind` and `payload` are the [`EventBody`] flattened into this shape, so an
68/// alert's wire form is the pair the store holds. `print` is what the
69/// supervision domain correlates on; an alert about no print carries none.
70#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
71#[serde(crate = "printobserver_types::serde")]
72#[schemars(crate = "printobserver_types::schemars")]
73pub struct NormalizedAlert {
74 /// Where it came from.
75 pub source: EventSource,
76 /// When it was received.
77 pub received_at: Timestamp,
78 /// The kind and the payload, flattened into this shape's own fields.
79 #[serde(flatten)]
80 pub body: EventBody,
81 /// The bytes exactly as received.
82 pub raw: RawBytes,
83 /// The image this alert names, when it names one.
84 #[serde(default, skip_serializing_if = "Option::is_none")]
85 pub image_url: Option<String>,
86 /// The provider's own identifier for the print this alert is about, and
87 /// the file it named, when the alert is about a print at all.
88 #[serde(default, skip_serializing_if = "Option::is_none")]
89 pub print: Option<ProviderPrint>,
90}
91
92impl NormalizedAlert {
93 /// Which event this is.
94 #[must_use]
95 pub const fn kind(&self) -> &EventKind {
96 &self.body.kind
97 }
98}
99
100// The written-down form of `VisionError::Malformed`, which is why this port
101// declares it rather than any one adapter. Said here rather than in the
102// description, which is the contract's and travels into every client.
103/// An external body arrived that could not be read.
104///
105/// This kind always carries its `raw` bytes, and it exists so that an alert
106/// this system cannot read is written down rather than dropped.
107#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
108#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
109#[schemars(crate = "printobserver_types::schemars")]
110pub struct MalformedExternalEventPayload {
111 /// One line saying why the body could not be read.
112 pub detail: String,
113}
114
115impl EventPayload for MalformedExternalEventPayload {
116 const KIND: &'static str = "malformed_external_event";
117}
118
119impl Sample for MalformedExternalEventPayload {
120 fn sample_full() -> Self {
121 Self {
122 detail: "the body is not JSON: expected value at line 1 column 1".to_owned(),
123 }
124 }
125}
126
127/// One image, as it was retrieved.
128#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
129#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
130#[schemars(crate = "printobserver_types::schemars")]
131pub struct FetchedImage {
132 /// The image's bytes, exactly as served.
133 pub bytes: RawBytes,
134 /// The content type it was served as.
135 pub content_type: String,
136}
137
138/// Why a body could not be read, or an image could not be retrieved.
139#[derive(Debug, Clone, PartialEq, Eq)]
140pub enum VisionError {
141 /// The body could not be read, and here it is.
142 Malformed {
143 /// One line saying why it could not be read.
144 detail: String,
145 /// The bytes exactly as received, so that the body is not lost.
146 raw: RawBytes,
147 },
148 /// The source took too long.
149 TimedOut,
150 /// What arrived is larger than this port will read.
151 TooLarge {
152 /// The limit, in bytes.
153 limit: i64,
154 },
155 /// What arrived is a content type this port does not accept.
156 UnacceptableContentType {
157 /// The content type that arrived.
158 content_type: String,
159 },
160 /// The source could not be reached at all.
161 Unreachable {
162 /// What went wrong reaching it.
163 detail: String,
164 },
165}
166
167impl core::fmt::Display for VisionError {
168 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
169 match self {
170 Self::Malformed { detail, raw } => {
171 write!(formatter, "the body could not be read ({detail}); {raw}")
172 }
173 Self::TimedOut => formatter.write_str("the source took too long"),
174 Self::TooLarge { limit } => {
175 write!(
176 formatter,
177 "what arrived is larger than the {limit} byte limit"
178 )
179 }
180 Self::UnacceptableContentType { content_type } => {
181 write!(
182 formatter,
183 "{content_type} is not a content type this port accepts"
184 )
185 }
186 Self::Unreachable { detail } => {
187 write!(formatter, "the source is unreachable: {detail}")
188 }
189 }
190 }
191}
192
193impl core::error::Error for VisionError {}
194
195/// The port external observations arrive through.
196///
197/// Every method is asynchronous, the trait is dyn-compatible, and it is
198/// shareable across threads, because the supervision core holds it behind
199/// `Arc<dyn VisionPort>`.
200pub trait VisionPort: Send + Sync {
201 /// Read a received body into an event under this adapter's own kind.
202 fn normalize(
203 &self,
204 body: RawBytes,
205 content_type: Option<String>,
206 ) -> BoxFuture<'_, Result<NormalizedAlert, VisionError>>;
207
208 /// Retrieve the image a source URL names.
209 fn fetch_image(&self, source_url: String) -> BoxFuture<'_, Result<FetchedImage, VisionError>>;
210}