printobserver-vision-api 0.15.5

The vision port for printobserver.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! `printobserver-vision-api`.
//!
//! Owns: the port external observations arrive through — the trait for
//! normalizing a received body into an event under the adapter's own kind, for
//! retrieving the image one names, and for telling the provider one of its
//! detections was handled — the shapes those methods carry, that
//! port's own error type, and the one event kind this port itself declares:
//! [`MalformedExternalEventPayload`], a body no adapter could read, written
//! down.
//!
//! May depend on: `printobserver-types` only. A port that named an
//! implementation would stop being a port.
//!
//! # This port is normalization, retrieval and acknowledgement only
//!
//! Ingress transport belongs to the server: nothing here listens, routes or
//! authenticates. A body arrives here already received, and what leaves is
//! either a [`NormalizedAlert`] or a [`VisionError`] saying why one could not
//! be made. The one thing this port sends the provider is
//! [`VisionPort::clear_detection`]: a detector that paused a print and is never
//! told the pause was dealt with may stay silent about that print for the rest
//! of it.
//!
//! # This port is provider-neutral
//!
//! A [`NormalizedAlert`] carries an [`EventBody`] under whatever kind the
//! adapter declares, and beside it the one thing the supervision domain reads
//! off an alert: [`ProviderPrint`], the provider's own identifier for the print
//! the alert is about. The supervision core correlates on that and never on a
//! provider's payload by kind, which is what lets a second provider's adapter
//! land without the core hearing of it.
//!
//! # Why the methods answer a boxed future
//!
//! Every method is asynchronous, and the trait is dyn-compatible and shareable
//! across threads, because the supervision core holds every port behind
//! `Arc<dyn Port>`. An `async fn` in a trait is not dyn-compatible, so each
//! method answers a [`BoxFuture`] instead.

use core::future::Future;
use core::pin::Pin;

use printobserver_types::contract::Sample;
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};
use printobserver_types::{EventBody, EventKind, EventPayload, EventSource, RawBytes, Timestamp};

/// A future this port's methods answer with, in the one shape a trait object
/// can carry.
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

/// The provider's own identifier for the print an alert is about.
///
/// Held in the provider's representation — a 64-bit integer, which is what
/// every provider this system has met uses — and named for what it is rather
/// than for the provider, so that the supervision domain correlates on it
/// without knowing whose it is.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct ProviderPrint {
    /// The provider's own identifier for the print.
    pub id: i64,
    /// The file the provider named, when it named one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub file_name: Option<String>,
    /// When the provider says the print started, when it said.
    ///
    /// What tells this print's job from a later job of the same file that the
    /// supervisor found before any alert about it arrived.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub started_at: Option<Timestamp>,
}

/// An `http` or `https` address an image or a provider's API is reached at,
/// as an operator wrote it down and this port has ruled on it.
///
/// There is no other way to hold one than [`WebAddress::new`], so a
/// configuration carrying one carries an address naming a host over HTTP —
/// never text that only begins like one, such as `http://?x` or `http://[`.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct WebAddress(String);

impl WebAddress {
    /// The address this text names.
    ///
    /// # Errors
    ///
    /// Answers why the text is not such an address, in words that never quote
    /// it: the text may be a secret pasted into the wrong line.
    pub fn new(text: &str) -> Result<Self, &'static str> {
        let trimmed = text.trim();
        let lowered = trimmed.to_ascii_lowercase();
        let Some(rest) = ["http://", "https://"]
            .iter()
            .find_map(|scheme| lowered.strip_prefix(scheme))
        else {
            return Err("it must be an http:// or https:// URL");
        };
        if rest
            .chars()
            .any(|letter| letter.is_whitespace() || letter.is_control())
        {
            return Err("it carries a space or a control character, which no URL does");
        }
        let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
        if !names_a_host(authority) {
            return Err("it names no host, or names one no URL can");
        }
        Ok(Self(trimmed.to_owned()))
    }

    /// The address, as it was written down.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl core::fmt::Display for WebAddress {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter.write_str(&self.0)
    }
}

/// Whether one URL's authority is a host, and a port when it carries one.
///
/// A host is an IPv6 address in brackets, which is parsed as one, or a name of
/// dot-separated labels — each of letters, digits and hyphens, neither
/// beginning nor ending with a hyphen — which an IPv4 address also is. A port
/// is a colon and a number no greater than 65535. A user before an `@` is no
/// part of an address this system is configured with.
fn names_a_host(authority: &str) -> bool {
    let (host_ok, port) = if let Some(bracketed) = authority.strip_prefix('[') {
        let Some((inside, after)) = bracketed.split_once(']') else {
            return false;
        };
        let port = if after.is_empty() {
            None
        } else if let Some(port) = after.strip_prefix(':') {
            Some(port)
        } else {
            return false;
        };
        (inside.parse::<std::net::Ipv6Addr>().is_ok(), port)
    } else {
        let (host, port) = match authority.rsplit_once(':') {
            Some((host, port)) => (host, Some(port)),
            None => (authority, None),
        };
        (is_a_host_name(host), port)
    };
    let port_ok = port.is_none_or(|digits| {
        !digits.is_empty()
            && digits.chars().all(|digit| digit.is_ascii_digit())
            && digits.parse::<u16>().is_ok()
    });
    host_ok && port_ok
}

/// Whether one host is a name of dot-separated labels, each of letters,
/// digits and hyphens, neither beginning nor ending with a hyphen — or, when
/// its last label is a number, an IPv4 address, as a URL reads such a host.
fn is_a_host_name(host: &str) -> bool {
    let numeric = host
        .rsplit('.')
        .next()
        .is_some_and(|last| !last.is_empty() && last.chars().all(|digit| digit.is_ascii_digit()));
    if numeric {
        return host.parse::<std::net::Ipv4Addr>().is_ok();
    }
    !host.is_empty()
        && host.split('.').all(|label| {
            !label.is_empty()
                && label.len() <= 63
                && !label.starts_with('-')
                && !label.ends_with('-')
                && label
                    .chars()
                    .all(|letter| letter.is_ascii_alphanumeric() || letter == '-')
        })
}

/// What a provider's failure detector did about a print, when an alert is one
/// of its detections.
///
/// Named for what it is rather than for the provider, like [`ProviderPrint`]:
/// whether the detector only warned, whether it paused the print itself, and
/// the provider's own identifier for the printer, which is what telling it the
/// detection was handled is addressed to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct Detection {
    /// Whether the detector called it a warning rather than a failure.
    pub warning: bool,
    /// Whether the detector paused the print itself before alerting.
    pub paused_the_print: bool,
    /// The provider's own identifier for the printer the detection is about.
    pub provider_printer_id: i64,
}

/// Something an alert says the printer itself signalled, beside what the
/// detector saw.
///
/// Named for what the printer did rather than for the provider that relayed
/// it, like [`Detection`], so the supervision domain acts on it without knowing
/// whose alert carried it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
#[schemars(crate = "printobserver_types::schemars")]
pub enum PrinterSignal {
    /// The printer asked for its filament to be changed.
    FilamentChange,
}

/// One external body, read into an event under the adapter's own kind.
///
/// `kind` and `payload` are the [`EventBody`] flattened into this shape, so an
/// alert's wire form is the pair the store holds. `print` is what the
/// supervision domain correlates on; an alert about no print carries none.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct NormalizedAlert {
    /// Where it came from.
    pub source: EventSource,
    /// When it was received.
    pub received_at: Timestamp,
    /// The kind and the payload, flattened into this shape's own fields.
    #[serde(flatten)]
    pub body: EventBody,
    /// The bytes exactly as received.
    pub raw: RawBytes,
    /// The image this alert names, when it names one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub image_url: Option<String>,
    /// The provider's own identifier for the print this alert is about, and
    /// the file it named, when the alert is about a print at all.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub print: Option<ProviderPrint>,
    /// What the provider's detector did, when this alert is one of its
    /// detections.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub detection: Option<Detection>,
    /// What the printer itself signalled, when the alert relays a signal.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signal: Option<PrinterSignal>,
}

impl NormalizedAlert {
    /// Which event this is.
    #[must_use]
    pub const fn kind(&self) -> &EventKind {
        &self.body.kind
    }
}

// The written-down form of `VisionError::Malformed`, which is why this port
// declares it rather than any one adapter. Said here rather than in the
// description, which is the contract's and travels into every client.
/// An external body arrived that could not be read.
///
/// This kind always carries its `raw` bytes, and it exists so that an alert
/// this system cannot read is written down rather than dropped.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct MalformedExternalEventPayload {
    /// One line saying why the body could not be read.
    pub detail: String,
}

impl EventPayload for MalformedExternalEventPayload {
    const KIND: &'static str = "malformed_external_event";
}

impl Sample for MalformedExternalEventPayload {
    fn sample_full() -> Self {
        Self {
            detail: "the body is not JSON: expected value at line 1 column 1".to_owned(),
        }
    }
}

/// One image, as it was retrieved.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct FetchedImage {
    /// The image's bytes, exactly as served.
    pub bytes: RawBytes,
    /// The content type it was served as.
    pub content_type: String,
    /// When its source says it was taken, when its source says: a frame a camera
    /// held over from earlier is not a frame of now.
    pub captured_at: Option<Timestamp>,
}

/// Why a retrieved frame is not one to hand anybody as a picture of the
/// print.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FrameFault {
    /// It decoded, and it is near-uniform: a camera showing nothing.
    Blank {
        /// What was measured, in words.
        detail: String,
    },
    /// It is not a whole image: a strict decode refused it.
    Undecodable {
        /// Why the decode refused it, in words.
        detail: String,
    },
}

impl core::fmt::Display for FrameFault {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Blank { detail } => write!(formatter, "the frame is blank: {detail}"),
            Self::Undecodable { detail } => {
                write!(formatter, "the frame does not decode: {detail}")
            }
        }
    }
}

/// Why a body could not be read, or an image could not be retrieved.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VisionError {
    /// The body could not be read, and here it is.
    Malformed {
        /// One line saying why it could not be read.
        detail: String,
        /// The bytes exactly as received, so that the body is not lost.
        raw: RawBytes,
    },
    /// The source took too long.
    TimedOut,
    /// What arrived is larger than this port will read.
    TooLarge {
        /// The limit, in bytes.
        limit: i64,
    },
    /// What arrived is a content type this port does not accept.
    UnacceptableContentType {
        /// The content type that arrived.
        content_type: String,
    },
    /// The source answered, with a status other than success.
    ///
    /// Carried apart from [`VisionError::Unreachable`], because what a caller
    /// does next depends on what was answered: a camera answering `500` is a
    /// camera that may answer the next request, and one answering `404` was
    /// asked for something it does not have.
    Status {
        /// What was asked and what it answered, in words.
        detail: String,
        /// The HTTP status code it answered.
        status: u16,
        /// The start of the body it answered with, as text: at most
        /// [`STATUS_EXCERPT_MAX_BYTES`] of it, read by [`body_excerpt`].
        excerpt: String,
    },
    /// The source could not be reached at all.
    Unreachable {
        /// What went wrong reaching it.
        detail: String,
    },
    /// The adapter was given nothing to reach the provider with for this.
    NotConfigured {
        /// What is missing, naming the configuration it would be read from.
        detail: String,
    },
}

impl core::fmt::Display for VisionError {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Malformed { detail, raw } => {
                write!(formatter, "the body could not be read ({detail}); {raw}")
            }
            Self::TimedOut => formatter.write_str("the source took too long"),
            Self::TooLarge { limit } => {
                write!(
                    formatter,
                    "what arrived is larger than the {limit} byte limit"
                )
            }
            Self::UnacceptableContentType { content_type } => {
                write!(
                    formatter,
                    "{content_type} is not a content type this port accepts"
                )
            }
            Self::Status {
                detail, excerpt, ..
            } => {
                if excerpt.is_empty() {
                    write!(formatter, "the source refused the request: {detail}")
                } else {
                    write!(
                        formatter,
                        "the source refused the request: {detail}, saying `{excerpt}`"
                    )
                }
            }
            Self::Unreachable { detail } => {
                write!(formatter, "the source is unreachable: {detail}")
            }
            Self::NotConfigured { detail } => {
                write!(
                    formatter,
                    "the provider is not configured for this: {detail}"
                )
            }
        }
    }
}

impl VisionError {
    /// Whether the source answered a server error, `500` to `599`: the one
    /// answer a fetch may be asked again for, because it says the source is
    /// there and could not answer this time.
    #[must_use]
    pub const fn is_server_error(&self) -> bool {
        matches!(self, Self::Status { status, .. } if *status >= 500 && *status <= 599)
    }
}

impl core::error::Error for VisionError {}

/// The most bytes of a refusing answer's body a [`VisionError::Status`]
/// carries.
///
/// Enough for the line a camera server answers a failure with — go2rtc's
/// `exit status 69` among them — and little enough that a server answering a
/// whole page of HTML costs a history record nothing.
pub const STATUS_EXCERPT_MAX_BYTES: usize = 256;

/// The start of a refusing answer's body, as the text a
/// [`VisionError::Status`] carries.
///
/// At most [`STATUS_EXCERPT_MAX_BYTES`] of the bytes are read; bytes that are
/// not UTF-8 are replaced rather than dropped, every control character is a
/// space, and the text is trimmed — and then cut back to the last whole
/// character within [`STATUS_EXCERPT_MAX_BYTES`], because a replaced byte is
/// three bytes of text. A body of nothing is an excerpt of nothing.
#[must_use]
pub fn body_excerpt(bytes: &[u8]) -> String {
    let taken = &bytes[..bytes.len().min(STATUS_EXCERPT_MAX_BYTES)];
    let text = match core::str::from_utf8(taken) {
        Ok(text) => text.to_owned(),
        // A cut through a character leaves an incomplete sequence at the end,
        // which is dropped; anything else that is not UTF-8 is replaced.
        Err(error) if error.error_len().is_none() => {
            String::from_utf8_lossy(&taken[..error.valid_up_to()]).into_owned()
        }
        Err(_) => String::from_utf8_lossy(taken).into_owned(),
    };
    let mut excerpt: String = text
        .chars()
        .map(|letter| if letter.is_control() { ' ' } else { letter })
        .collect::<String>()
        .trim()
        .to_owned();
    if excerpt.len() > STATUS_EXCERPT_MAX_BYTES {
        let mut end = STATUS_EXCERPT_MAX_BYTES;
        while !excerpt.is_char_boundary(end) {
            end -= 1;
        }
        excerpt.truncate(end);
        excerpt.truncate(excerpt.trim_end().len());
    }
    excerpt
}

/// The port external observations arrive through.
///
/// Every method is asynchronous, the trait is dyn-compatible, and it is
/// shareable across threads, because the supervision core holds it behind
/// `Arc<dyn VisionPort>`.
pub trait VisionPort: Send + Sync {
    /// Read a received body into an event under this adapter's own kind.
    fn normalize(
        &self,
        body: RawBytes,
        content_type: Option<String>,
    ) -> BoxFuture<'_, Result<NormalizedAlert, VisionError>>;

    /// Retrieve the image a source URL names.
    fn fetch_image(&self, source_url: String) -> BoxFuture<'_, Result<FetchedImage, VisionError>>;

    /// Tell the provider one of its detections has been handled.
    ///
    /// A detector that paused a print and was never told the pause was dealt
    /// with may stay silent about that print for the rest of it; this is what
    /// re-arms it once the print has been adjusted and resumed.
    fn clear_detection(&self, detection: Detection) -> BoxFuture<'_, Result<(), VisionError>>;

    /// Judge one retrieved frame as a picture of the print, answering it back
    /// when it is one and why not otherwise.
    ///
    /// An implementation that does not judge frames answers every one back,
    /// which is what one that does not override this does.
    fn judge_frame(&self, image: FetchedImage) -> BoxFuture<'_, Result<FetchedImage, FrameFault>> {
        Box::pin(async move { Ok(image) })
    }
}