use core::fmt;
use crate::frame::{Compression, FrameKind};
pub const ERROR_VALUE_PREVIEW_LEN: usize = 48;
#[must_use]
pub fn preview(value: &str) -> String {
let mut out = String::with_capacity(ERROR_VALUE_PREVIEW_LEN + 3);
for (count, ch) in value.chars().enumerate() {
if count == ERROR_VALUE_PREVIEW_LEN {
out.push('…');
return out;
}
out.push(ch);
}
out
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum IdKind {
Node,
Data,
Operator,
Machine,
Param,
TypeUrn,
Name,
}
impl IdKind {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Node => "node id",
Self::Data => "data id",
Self::Operator => "operator id",
Self::Machine => "machine name",
Self::Param => "parameter key",
Self::TypeUrn => "type urn",
Self::Name => "name",
}
}
}
impl fmt::Display for IdKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum IdError {
#[error("{kind} must not be empty")]
Empty {
kind: IdKind,
},
#[error("{kind} is {len} bytes, over the {max}-byte limit")]
TooLong {
kind: IdKind,
len: usize,
max: usize,
},
#[error("{kind} `{value}` contains the invalid character {ch:?} at byte {index}")]
InvalidChar {
kind: IdKind,
value: String,
ch: char,
index: usize,
},
#[error("{kind} `{value}` is malformed: {reason}")]
Malformed {
kind: IdKind,
value: String,
reason: &'static str,
},
}
impl IdError {
#[must_use]
pub const fn kind(&self) -> IdKind {
match self {
Self::Empty { kind }
| Self::TooLong { kind, .. }
| Self::InvalidChar { kind, .. }
| Self::Malformed { kind, .. } => *kind,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum AuthTokenError {
#[error("auth token must be exactly {expected} hex characters, found {found}")]
BadLength {
expected: usize,
found: usize,
},
#[error("auth token contains the non-lowercase-hex character {ch:?} at position {index}")]
NotLowercaseHex {
ch: char,
index: usize,
},
#[error("auth token generation failed: {reason}")]
RandomnessUnavailable {
reason: String,
},
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum WireError {
#[error("frame magic mismatch: expected {expected:02x?}, found {found:02x?}")]
BadMagic {
expected: [u8; 2],
found: [u8; 2],
},
#[error("unsupported frame layout version {found} (this build speaks version {supported})")]
UnsupportedFrameVersion {
found: u8,
supported: u8,
},
#[error("unknown frame kind discriminant {found}")]
UnknownKind {
found: u16,
},
#[error("frame flags 0x{bits:02x} set reserved bits 0x{reserved:02x}")]
ReservedFlags {
bits: u8,
reserved: u8,
},
#[error("frame flags select both lz4 and zstd compression")]
ConflictingCompression,
#[error("payload is {compression}-compressed; decompress it before decoding")]
CompressedPayload {
compression: Compression,
},
#[error("frame carries no crc32c trailer, which this connection requires")]
MissingCrc,
#[error("frame payload of {len} bytes exceeds the maximum of {max} bytes")]
FrameTooLarge {
len: usize,
max: usize,
},
#[error("frame truncated: needed {expected} bytes, found {found}")]
Truncated {
expected: usize,
found: usize,
},
#[error("crc32c mismatch: frame carries {expected:#010x}, computed {computed:#010x}")]
CrcMismatch {
expected: u32,
computed: u32,
},
#[error("{trailing} trailing byte(s) after a complete payload of {consumed} byte(s)")]
TrailingBytes {
consumed: usize,
trailing: usize,
},
#[error(
"size hint mismatch: encode_size_hint() promised {hint} bytes, encoding wrote {written}"
)]
SizeHintMismatch {
hint: usize,
written: usize,
},
#[error("expected a {expected} frame, found {found}")]
KindMismatch {
expected: FrameKind,
found: FrameKind,
},
#[error("payload codec error: {0}")]
Codec(#[from] oxicode::error::Error),
#[error("i/o error: {0}")]
Io(#[from] std::io::Error),
#[error("invalid identifier: {0}")]
Id(#[from] IdError),
#[error("invalid auth token: {0}")]
Auth(#[from] AuthTokenError),
}
impl WireError {
#[must_use]
pub const fn is_protocol_violation(&self) -> bool {
!matches!(self, Self::Io(_) | Self::SizeHintMismatch { .. })
}
#[must_use]
pub const fn is_incomplete(&self) -> bool {
matches!(self, Self::Truncated { .. })
}
}
pub type WireResult<T> = Result<T, WireError>;
pub(crate) fn codec_invalid(message: impl Into<String>) -> oxicode::error::Error {
oxicode::error::Error::OwnedCustom {
message: message.into(),
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
#[test]
fn preview_passes_short_values_through() {
assert_eq!(preview(""), "");
assert_eq!(preview("camera/frames"), "camera/frames");
}
#[test]
fn preview_truncates_long_values_on_char_boundaries() {
let long = "ん".repeat(200);
let short = preview(&long);
assert_eq!(short.chars().count(), ERROR_VALUE_PREVIEW_LEN + 1);
assert!(short.ends_with('…'));
assert!(
short
.chars()
.take(ERROR_VALUE_PREVIEW_LEN)
.all(|c| c == 'ん')
);
}
#[test]
fn preview_at_exact_boundary_does_not_add_ellipsis() {
let exact = "a".repeat(ERROR_VALUE_PREVIEW_LEN);
assert_eq!(preview(&exact), exact);
}
#[test]
fn id_kind_display_matches_as_str() {
for kind in [
IdKind::Node,
IdKind::Data,
IdKind::Operator,
IdKind::Machine,
IdKind::Param,
IdKind::TypeUrn,
IdKind::Name,
] {
assert_eq!(kind.to_string(), kind.as_str());
}
}
#[test]
fn id_error_reports_its_kind() {
assert_eq!(IdError::Empty { kind: IdKind::Data }.kind(), IdKind::Data);
assert_eq!(
IdError::TooLong {
kind: IdKind::Param,
len: 9,
max: 8,
}
.kind(),
IdKind::Param
);
assert_eq!(
IdError::InvalidChar {
kind: IdKind::Node,
value: "a b".to_owned(),
ch: ' ',
index: 1,
}
.kind(),
IdKind::Node
);
assert_eq!(
IdError::Malformed {
kind: IdKind::Machine,
value: "x".to_owned(),
reason: "nope",
}
.kind(),
IdKind::Machine
);
}
#[test]
fn protocol_violations_are_distinguished_from_io() {
assert!(WireError::ConflictingCompression.is_protocol_violation());
assert!(
WireError::CrcMismatch {
expected: 1,
computed: 2
}
.is_protocol_violation()
);
assert!(
!WireError::Io(std::io::Error::from(std::io::ErrorKind::BrokenPipe))
.is_protocol_violation()
);
assert!(
!WireError::SizeHintMismatch {
hint: 1,
written: 2
}
.is_protocol_violation()
);
}
#[test]
fn incomplete_is_only_truncation() {
assert!(
WireError::Truncated {
expected: 10,
found: 3
}
.is_incomplete()
);
assert!(!WireError::ConflictingCompression.is_incomplete());
}
#[test]
fn errors_render_useful_messages() {
let err = WireError::BadMagic {
expected: *b"AS",
found: *b"XY",
};
let text = err.to_string();
assert!(text.contains("magic"), "{text}");
let err = WireError::FrameTooLarge { len: 100, max: 64 };
assert!(err.to_string().contains("64"));
let err = AuthTokenError::BadLength {
expected: 64,
found: 8,
};
assert!(err.to_string().contains("64"));
}
#[test]
fn wire_error_stays_small_enough_for_result_returns() {
assert!(
core::mem::size_of::<WireError>() <= 128,
"WireError grew to {} bytes",
core::mem::size_of::<WireError>()
);
}
#[test]
fn codec_invalid_carries_the_message() {
let err = codec_invalid("bad node id");
match err {
oxicode::error::Error::OwnedCustom { message } => assert_eq!(message, "bad node id"),
other => panic!("unexpected error: {other:?}"),
}
}
}