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