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};
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct ProviderPrint {
pub id: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub file_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub started_at: Option<Timestamp>,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct WebAddress(String);
impl WebAddress {
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()))
}
#[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)
}
}
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
}
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 == '-')
})
}
#[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 {
pub warning: bool,
pub paused_the_print: bool,
pub provider_printer_id: i64,
}
#[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 {
FilamentChange,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct NormalizedAlert {
pub source: EventSource,
pub received_at: Timestamp,
#[serde(flatten)]
pub body: EventBody,
pub raw: RawBytes,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub image_url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub print: Option<ProviderPrint>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub detection: Option<Detection>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub signal: Option<PrinterSignal>,
}
impl NormalizedAlert {
#[must_use]
pub const fn kind(&self) -> &EventKind {
&self.body.kind
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct MalformedExternalEventPayload {
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(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct FetchedImage {
pub bytes: RawBytes,
pub content_type: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FrameFault {
Blank {
detail: String,
},
Undecodable {
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}")
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VisionError {
Malformed {
detail: String,
raw: RawBytes,
},
TimedOut,
TooLarge {
limit: i64,
},
UnacceptableContentType {
content_type: String,
},
Unreachable {
detail: String,
},
NotConfigured {
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::Unreachable { detail } => {
write!(formatter, "the source is unreachable: {detail}")
}
Self::NotConfigured { detail } => {
write!(
formatter,
"the provider is not configured for this: {detail}"
)
}
}
}
}
impl core::error::Error for VisionError {}
pub trait VisionPort: Send + Sync {
fn normalize(
&self,
body: RawBytes,
content_type: Option<String>,
) -> BoxFuture<'_, Result<NormalizedAlert, VisionError>>;
fn fetch_image(&self, source_url: String) -> BoxFuture<'_, Result<FetchedImage, VisionError>>;
fn clear_detection(&self, detection: Detection) -> BoxFuture<'_, Result<(), VisionError>>;
fn judge_frame(&self, image: FetchedImage) -> BoxFuture<'_, Result<FetchedImage, FrameFault>> {
Box::pin(async move { Ok(image) })
}
}