use serde_json::{Map, Value};
use thiserror::Error;
use crate::wire::{self, Form, Header, Refusal, Stamp, Tag};
pub const CODES: [&str; 8] = [
"invalid_request",
"not_found",
"unavailable",
"forbidden",
"fanout_forbidden",
"busy",
"internal",
"app",
];
pub const CAUSES: [&str; 3] = ["build", "config", "capability"];
pub const JSON: &str = "application/json";
pub const CBOR: &str = "application/cbor";
pub const PROTOBUF: &str = "application/protobuf;zk2.core.v1.Error";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Code {
InvalidRequest,
NotFound,
Unavailable,
Forbidden,
FanoutForbidden,
Busy,
Internal,
App,
}
impl Code {
pub const ALL: [Code; 8] = [
Code::InvalidRequest,
Code::NotFound,
Code::Unavailable,
Code::Forbidden,
Code::FanoutForbidden,
Code::Busy,
Code::Internal,
Code::App,
];
#[must_use]
pub const fn number(self) -> u8 {
self as u8
}
#[must_use]
pub const fn from_number(n: u8) -> Option<Code> {
if n < 8 {
Some(Code::ALL[n as usize])
} else {
None
}
}
#[must_use]
pub const fn as_str(self) -> &'static str {
CODES[self as usize]
}
#[must_use]
pub fn from_name(name: &str) -> Option<Code> {
Code::ALL.into_iter().find(|c| c.as_str() == name)
}
}
impl std::fmt::Display for Code {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Cause {
Build,
Config,
Capability,
}
impl Cause {
pub const ALL: [Cause; 3] = [Cause::Build, Cause::Config, Cause::Capability];
#[must_use]
pub const fn number(self) -> u8 {
self as u8 + 1
}
#[must_use]
pub const fn as_str(self) -> &'static str {
CAUSES[self as usize]
}
#[must_use]
pub fn from_name(name: &str) -> Option<Cause> {
Cause::ALL.into_iter().find(|c| c.as_str() == name)
}
}
impl std::fmt::Display for Cause {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ErrorByte {
pub code: Code,
pub cause: Option<Cause>,
pub detail: bool,
pub message: bool,
}
impl ErrorByte {
pub fn read(byte: u8) -> Result<ErrorByte, Refusal> {
let b = ErrorByte {
code: Code::ALL[usize::from(byte >> 5)],
cause: match (byte >> 3) & 0b11 {
0 => None,
n => Some(Cause::ALL[usize::from(n - 1)]),
},
detail: byte & 0b100 != 0,
message: byte & 0b10 != 0,
};
b.check()?;
if byte & 1 != 0 {
return Err(Refusal::Extension);
}
Ok(b)
}
pub fn check(self) -> Result<(), Refusal> {
if self.cause.is_some() != (self.code == Code::Unavailable) {
return Err(Refusal::Cause {
code: self.code,
cause: self.cause,
});
}
if self.detail && self.code != Code::App {
return Err(Refusal::Detail(self.code));
}
Ok(())
}
#[must_use]
pub const fn byte(self) -> u8 {
let cause = match self.cause {
Some(c) => c.number(),
None => 0,
};
(self.code.number() << 5)
| (cause << 3)
| ((self.detail as u8) << 2)
| ((self.message as u8) << 1)
}
}
pub const MESSAGE_MAX: usize = 255;
#[must_use]
pub fn cut(message: &str) -> &str {
&message[..message.floor_char_boundary(MESSAGE_MAX)]
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ErrorForm<'a> {
pub tag: Tag,
pub stamp: Stamp,
pub code: Code,
pub cause: Option<Cause>,
pub message: Option<&'a str>,
pub detail: Option<&'a [u8]>,
}
impl<'a> ErrorForm<'a> {
#[must_use]
pub const fn new(tag: Tag, stamp: Stamp, code: Code, cause: Option<Cause>) -> ErrorForm<'a> {
ErrorForm {
tag,
stamp,
code,
cause,
message: None,
detail: None,
}
}
#[must_use]
pub const fn header(&self) -> Header {
Header {
form: Form::Error,
wide: self.stamp.run.is_wide(),
tag: self.tag,
}
}
#[must_use]
pub const fn error_byte(&self) -> ErrorByte {
ErrorByte {
code: self.code,
cause: self.cause,
detail: self.detail.is_some(),
message: self.message.is_some(),
}
}
pub(crate) fn after_stamp(
tag: Tag,
stamp: Stamp,
rest: &'a [u8],
) -> Result<ErrorForm<'a>, Refusal> {
let (&byte, rest) = rest
.split_first()
.ok_or(Refusal::Short { need: 1, have: 0 })?;
let b = ErrorByte::read(byte)?;
let (message, rest) = if b.message {
let (&len, rest) = rest
.split_first()
.ok_or(Refusal::MessageShort { need: 1, have: 0 })?;
let len = usize::from(len);
if rest.len() < len {
return Err(Refusal::MessageShort {
need: len,
have: rest.len(),
});
}
let (text, rest) = rest.split_at(len);
let text = std::str::from_utf8(text).map_err(|_| Refusal::Utf8)?;
(Some(text), rest)
} else {
(None, rest)
};
let detail = if b.detail {
Some(rest)
} else if rest.is_empty() {
None
} else {
return Err(Refusal::Trailing(rest.len()));
};
Ok(ErrorForm {
tag,
stamp,
code: b.code,
cause: b.cause,
message,
detail,
})
}
pub fn read(encoding: &str, payload: &'a [u8]) -> Result<ErrorForm<'a>, FormRefusal> {
if encoding != wire::ENCODING {
return Err(FormRefusal::Encoding(encoding.to_owned()));
}
wire::read_reply_err(payload).map_err(FormRefusal::Form)
}
pub fn write(&self) -> Result<Vec<u8>, Refusal> {
let b = self.error_byte();
b.check()?;
let message = self.message.map(cut);
let detail = self.detail.unwrap_or_default();
let mut out = Vec::with_capacity(
self.stamp.envelope_bytes() + 2 + message.map_or(0, str::len) + detail.len(),
);
out.push(self.header().byte());
self.stamp.write_to(&mut out);
out.push(b.byte());
if let Some(m) = message {
out.push(u8::try_from(m.len()).expect("a cut message fits a byte"));
out.extend_from_slice(m.as_bytes());
}
out.extend_from_slice(detail);
Ok(out)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum FormRefusal {
#[error("a reply error under {0:?}, which carries no error form")]
Encoding(String),
#[error(transparent)]
Form(Refusal),
}
impl FormRefusal {
#[must_use]
pub const fn token(&self) -> &'static str {
match self {
FormRefusal::Encoding(_) => "encoding",
FormRefusal::Form(r) => r.token(),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum ErrorReading<'a> {
Form(ErrorForm<'a>),
Envelope(Result<Envelope, EnvelopeError>),
Transport(Option<Refusal>),
}
#[must_use]
pub fn read_error<'a>(encoding: &str, payload: &'a [u8]) -> ErrorReading<'a> {
match ErrorForm::read(encoding, payload) {
Ok(form) => ErrorReading::Form(form),
Err(FormRefusal::Form(r)) => ErrorReading::Transport(Some(r)),
Err(FormRefusal::Encoding(_)) if [JSON, CBOR, PROTOBUF].contains(&encoding) => {
ErrorReading::Envelope(decode(encoding, payload))
}
Err(FormRefusal::Encoding(_)) => ErrorReading::Transport(None),
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Envelope {
pub code: String,
pub message: String,
pub cause: Option<String>,
pub detail: Option<Detail>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Detail {
Value(Value),
Bytes(Vec<u8>),
}
impl Detail {
#[must_use]
pub fn raw(bytes: &[u8]) -> Self {
use base64::Engine as _;
Self::Value(Value::String(
base64::engine::general_purpose::STANDARD.encode(bytes),
))
}
#[must_use]
pub fn raw_bytes(&self) -> Option<Vec<u8>> {
use base64::Engine as _;
match self {
Self::Value(Value::String(s)) => {
base64::engine::general_purpose::STANDARD.decode(s).ok()
}
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum EnvelopeError {
#[error("unknown envelope encoding {0:?}")]
Encoding(String),
#[error("malformed envelope: {0}")]
Decode(String),
#[error("unknown error code {0:?}")]
Code(String),
#[error("cause: {0}")]
Cause(String),
#[error("detail: {0}")]
Detail(String),
}
impl EnvelopeError {
#[must_use]
pub fn tag(&self) -> &'static str {
match self {
Self::Encoding(_) => "encoding",
Self::Decode(_) => "decode",
Self::Code(_) => "code",
Self::Cause(_) => "cause",
Self::Detail(_) => "detail",
}
}
}
#[derive(Clone, PartialEq, prost::Message)]
struct ErrorPb {
#[prost(string, tag = "1")]
code: String,
#[prost(string, tag = "2")]
message: String,
#[prost(string, optional, tag = "3")]
cause: Option<String>,
#[prost(bytes = "vec", optional, tag = "4")]
detail: Option<Vec<u8>>,
}
pub fn decode(encoding: &str, bytes: &[u8]) -> Result<Envelope, EnvelopeError> {
let env = match encoding {
JSON => {
let text =
std::str::from_utf8(bytes).map_err(|e| EnvelopeError::Decode(e.to_string()))?;
let v = crate::strict::parse_json(text)
.map_err(|e| EnvelopeError::Decode(e.to_string()))?;
from_value(v)?
}
CBOR => {
let mut rest = bytes;
let item: ciborium::Value = ciborium::from_reader(&mut rest)
.map_err(|e| EnvelopeError::Decode(e.to_string()))?;
if !rest.is_empty() {
return Err(EnvelopeError::Decode(format!(
"{} bytes after the CBOR item",
rest.len()
)));
}
from_value(cbor_to_json(item)?)?
}
PROTOBUF => {
let pb = <ErrorPb as prost::Message>::decode(bytes)
.map_err(|e| EnvelopeError::Decode(e.to_string()))?;
Envelope {
code: pb.code,
message: pb.message,
cause: pb.cause,
detail: pb.detail.map(Detail::Bytes),
}
}
other => return Err(EnvelopeError::Encoding(other.to_owned())),
};
check(&env)?;
Ok(env)
}
#[must_use]
pub fn encode(env: &Envelope, encoding: &str) -> Option<Vec<u8>> {
match encoding {
JSON | CBOR => {
let mut m = Map::new();
m.insert("code".into(), env.code.clone().into());
m.insert("message".into(), env.message.clone().into());
if let Some(c) = &env.cause {
m.insert("cause".into(), c.clone().into());
}
match &env.detail {
Some(Detail::Value(v)) => {
m.insert("detail".into(), v.clone());
}
Some(Detail::Bytes(_)) => return None,
None => {}
}
let v = Value::Object(m);
if encoding == JSON {
serde_json::to_vec(&v).ok()
} else {
let mut out = Vec::new();
ciborium::into_writer(&v, &mut out).ok()?;
Some(out)
}
}
PROTOBUF => {
let detail = match &env.detail {
Some(Detail::Bytes(b)) => Some(b.clone()),
Some(Detail::Value(_)) => return None,
None => None,
};
let pb = ErrorPb {
code: env.code.clone(),
message: env.message.clone(),
cause: env.cause.clone(),
detail,
};
Some(prost::Message::encode_to_vec(&pb))
}
_ => None,
}
}
fn from_value(v: Value) -> Result<Envelope, EnvelopeError> {
let Value::Object(mut m) = v else {
return Err(EnvelopeError::Decode("not an object".into()));
};
if let Some(k) = m
.keys()
.find(|k| !matches!(k.as_str(), "code" | "message" | "cause" | "detail"))
{
return Err(EnvelopeError::Decode(format!("unknown member {k:?}")));
}
let text = |m: &mut Map<String, Value>, k: &str| -> Result<String, EnvelopeError> {
match m.remove(k) {
Some(Value::String(s)) => Ok(s),
Some(_) => Err(EnvelopeError::Decode(format!("`{k}` is not a string"))),
None => Err(EnvelopeError::Decode(format!("no `{k}`"))),
}
};
let code = text(&mut m, "code")?;
let message = text(&mut m, "message")?;
let cause = match m.remove("cause") {
None | Some(Value::Null) => None,
Some(Value::String(s)) => Some(s),
Some(_) => return Err(EnvelopeError::Decode("`cause` is not a string".into())),
};
let detail = match m.remove("detail") {
None | Some(Value::Null) => None,
Some(v) => Some(Detail::Value(v)),
};
Ok(Envelope {
code,
message,
cause,
detail,
})
}
fn check(env: &Envelope) -> Result<(), EnvelopeError> {
if !CODES.contains(&env.code.as_str()) {
return Err(EnvelopeError::Code(env.code.clone()));
}
match (&env.cause, env.code == "unavailable") {
(None, true) => return Err(EnvelopeError::Cause("`unavailable` without a cause".into())),
(Some(c), true) if !CAUSES.contains(&c.as_str()) => {
return Err(EnvelopeError::Cause(format!(
"{c:?} is not build, config or capability"
)));
}
(Some(_), false) => {
return Err(EnvelopeError::Cause(format!("a cause on {:?}", env.code)));
}
_ => {}
}
if env.detail.is_some() && env.code != "app" {
return Err(EnvelopeError::Detail(format!("a detail on {:?}", env.code)));
}
Ok(())
}
fn cbor_to_json(v: ciborium::Value) -> Result<Value, EnvelopeError> {
use ciborium::Value as C;
Ok(match v {
C::Null => Value::Null,
C::Bool(b) => Value::Bool(b),
C::Integer(i) => {
let n = i128::from(i);
i64::try_from(n)
.map(Value::from)
.or_else(|_| u64::try_from(n).map(Value::from))
.map_err(|_| EnvelopeError::Decode("integer out of range".into()))?
}
C::Float(f) => serde_json::Number::from_f64(f)
.map(Value::Number)
.ok_or_else(|| EnvelopeError::Decode("non-finite float".into()))?,
C::Text(s) => Value::String(s),
C::Bytes(b) => {
use base64::Engine as _;
Value::String(base64::engine::general_purpose::STANDARD.encode(b))
}
C::Array(a) => Value::Array(a.into_iter().map(cbor_to_json).collect::<Result<_, _>>()?),
C::Map(m) => {
let mut out = Map::new();
for (k, v) in m {
let C::Text(k) = k else {
return Err(EnvelopeError::Decode("a map key is not text".into()));
};
if out.insert(k, cbor_to_json(v)?).is_some() {
return Err(EnvelopeError::Decode("a duplicate map key".into()));
}
}
Value::Object(out)
}
C::Tag(_, inner) => cbor_to_json(*inner)?,
_ => return Err(EnvelopeError::Decode("an unsupported CBOR item".into())),
})
}
#[cfg(test)]
mod tests {
use super::*;
fn hex(h: &str) -> Vec<u8> {
(0..h.len())
.step_by(2)
.map(|i| u8::from_str_radix(&h[i..i + 2], 16).unwrap())
.collect()
}
fn app_with(item: &str) -> Vec<u8> {
hex(&format!(
"a364636f646563617070676d65737361676561786664657461696c{item}"
))
}
#[test]
fn cbor_items_map_to_json() {
let detail = |item: &str| decode(CBOR, &app_with(item)).map(|e| e.detail);
assert_eq!(
detail("420102"),
Ok(Some(Detail::Value(Value::String("AQI=".into()))))
);
assert_eq!(detail("f7"), Ok(None));
assert_eq!(
detail("c11a00000001"),
Ok(Some(Detail::Value(Value::from(1))))
);
}
#[test]
fn cbor_integers_are_64_bit_signed_or_unsigned() {
let detail = |item: &str| decode(CBOR, &app_with(item)).map(|e| e.detail);
let value = |v: Value| Ok(Some(Detail::Value(v)));
assert_eq!(detail("1bffffffffffffffff"), value(Value::from(u64::MAX)));
assert_eq!(
detail("1b8000000000000000"),
value(Value::from(1_u64 << 63))
);
assert_eq!(detail("3b7fffffffffffffff"), value(Value::from(i64::MIN)));
for below in ["3b8000000000000000", "3bffffffffffffffff"] {
assert_eq!(
decode(CBOR, &app_with(below)).map_err(|e| e.tag()),
Err("decode"),
"{below}"
);
}
let env = Envelope {
code: "app".into(),
message: "x".into(),
cause: None,
detail: Some(Detail::Value(Value::from(u64::MAX))),
};
let bytes = encode(&env, CBOR).unwrap();
assert_eq!(decode(CBOR, &bytes), Ok(env));
}
#[test]
fn trailing_bytes_are_malformed() {
let mut bytes = hex("a264636f646563617070676d6573736167656178");
assert!(decode(CBOR, &bytes).is_ok());
bytes.push(0);
assert_eq!(decode(CBOR, &bytes).map_err(|e| e.tag()), Err("decode"));
}
#[test]
fn a_raw_detail_is_base64_text() {
let d = Detail::raw(&[0xff, 0xd8, 0xff, 0xe0]);
assert_eq!(d, Detail::Value(Value::String("/9j/4A==".into())));
assert_eq!(d.raw_bytes(), Some(vec![0xff, 0xd8, 0xff, 0xe0]));
let env = Envelope {
code: "app".into(),
message: "camera fault".into(),
cause: None,
detail: Some(d),
};
let bytes = encode(&env, JSON).unwrap();
assert_eq!(decode(JSON, &bytes), Ok(env));
assert_eq!(
Detail::Value(Value::String("/9j/4A".into())).raw_bytes(),
None
);
assert_eq!(Detail::Bytes(vec![1]).raw_bytes(), None);
}
#[test]
fn the_error_bytes_worked_in_the_text() {
let read = |b| ErrorByte::read(b).map(|e| (e.code, e.cause, e.detail, e.message));
assert_eq!(read(0xa0), Ok((Code::Busy, None, false, false)));
assert_eq!(
read(0x50),
Ok((Code::Unavailable, Some(Cause::Config), false, false))
);
assert_eq!(read(0xe4), Ok((Code::App, None, true, false)));
for code in Code::ALL {
assert_eq!(Code::from_number(code.number()), Some(code));
assert_eq!(Code::from_name(code.as_str()), Some(code));
}
assert_eq!(Code::from_number(8), None);
}
#[test]
fn a_long_message_is_cut_at_a_character() {
let fits = "a".repeat(MESSAGE_MAX);
assert_eq!(cut(&fits), fits);
let over = format!("{}é", "a".repeat(254));
assert_eq!(cut(&over), &over[..254]);
assert_eq!(cut(""), "");
}
#[test]
fn encodings_match_exactly() {
for enc in [
"application/json;charset=utf-8",
"application/protobuf",
"application/protobuf;other.Error",
] {
assert_eq!(decode(enc, b"{}").map_err(|e| e.tag()), Err("encoding"));
}
}
#[test]
fn a_reply_error_is_read_by_its_encoding_first() {
let busy = hex("600001000007a0");
let ErrorReading::Form(f) = read_error(wire::ENCODING, &busy) else {
panic!("an error form")
};
assert_eq!(
(f.code, f.cause, f.message, f.detail),
(Code::Busy, None, None, None)
);
assert_eq!(f.stamp.seq.get(), 7);
assert_eq!(
read_error(wire::ENCODING, b"Timeout"),
ErrorReading::Transport(Some(Refusal::WrongSample {
form: Form::Value,
sample: wire::SampleKind::ReplyErr
}))
);
let ErrorReading::Transport(Some(r)) = read_error(wire::ENCODING, &hex("600001000007a8"))
else {
panic!("a cause on busy")
};
assert_eq!(r.token(), "cause");
assert_eq!(
read_error(JSON, br#"{"code":"busy","message":""}"#),
ErrorReading::Envelope(Ok(Envelope {
code: "busy".into(),
message: String::new(),
cause: None,
detail: None
}))
);
assert!(matches!(
read_error(JSON, b"{"),
ErrorReading::Envelope(Err(EnvelopeError::Decode(_)))
));
for other in ["zenoh/string", "zenoh/bytes;x", "text/plain"] {
assert_eq!(
read_error(other, &busy),
ErrorReading::Transport(None),
"{other}"
);
}
}
}