use alloc::string::{String, ToString};
use alloc::vec::Vec;
use crate::tlv_builders::{value_u16, BuildError};
use crate::{type_code, Opt, Tlv};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u16)]
pub enum ErrCode {
FrameTruncated = 0x0001,
FrameInvalid = 0x0002,
FrameCrcFail = 0x0003,
TlvNestingTooDeep = 0x0010,
PathNotFound = 0x0020,
PathInvalid = 0x0021,
PathInUse = 0x0022,
SchemaTypeMismatch = 0x0030,
SchemaNotFound = 0x0031,
FlowBackpressure = 0x0040,
FlowTimeout = 0x0041,
FlowAddressShiftGap = 0x0042,
AccessDenied = 0x0050,
TransportDown = 0x0060,
VersionMismatch = 0x0070,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
Warn,
Error,
Critical,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Disposition {
Transient,
Permanent,
Fatal,
}
const REGISTRY: [(ErrCode, u16, &str, Severity, Disposition); 15] = [
(
ErrCode::FrameTruncated,
0x0001,
"tr::frame::truncated",
Severity::Error,
Disposition::Transient,
),
(
ErrCode::FrameInvalid,
0x0002,
"tr::frame::invalid",
Severity::Error,
Disposition::Permanent,
),
(
ErrCode::FrameCrcFail,
0x0003,
"tr::frame::crc_fail",
Severity::Error,
Disposition::Transient,
),
(
ErrCode::TlvNestingTooDeep,
0x0010,
"tr::tlv::nesting_too_deep",
Severity::Error,
Disposition::Permanent,
),
(
ErrCode::PathNotFound,
0x0020,
"tr::path::not_found",
Severity::Warn,
Disposition::Permanent,
),
(
ErrCode::PathInvalid,
0x0021,
"tr::path::invalid",
Severity::Warn,
Disposition::Permanent,
),
(
ErrCode::PathInUse,
0x0022,
"tr::path::in_use",
Severity::Warn,
Disposition::Permanent,
),
(
ErrCode::SchemaTypeMismatch,
0x0030,
"tr::schema::type_mismatch",
Severity::Error,
Disposition::Permanent,
),
(
ErrCode::SchemaNotFound,
0x0031,
"tr::schema::not_found",
Severity::Warn,
Disposition::Permanent,
),
(
ErrCode::FlowBackpressure,
0x0040,
"tr::flow::backpressure",
Severity::Warn,
Disposition::Transient,
),
(
ErrCode::FlowTimeout,
0x0041,
"tr::flow::timeout",
Severity::Warn,
Disposition::Transient,
),
(
ErrCode::FlowAddressShiftGap,
0x0042,
"tr::flow::address_shift_gap",
Severity::Error,
Disposition::Permanent,
),
(
ErrCode::AccessDenied,
0x0050,
"tr::access::denied",
Severity::Error,
Disposition::Permanent,
),
(
ErrCode::TransportDown,
0x0060,
"tr::transport::down",
Severity::Error,
Disposition::Transient,
),
(
ErrCode::VersionMismatch,
0x0070,
"tr::version::mismatch",
Severity::Critical,
Disposition::Fatal,
),
];
impl ErrCode {
pub const fn code(self) -> u16 {
self as u16
}
pub fn from_code(code: u16) -> Option<ErrCode> {
REGISTRY.iter().find(|e| e.1 == code).map(|e| e.0)
}
pub fn from_path(path: &str) -> Option<ErrCode> {
REGISTRY.iter().find(|e| e.2 == path).map(|e| e.0)
}
pub fn path(self) -> &'static str {
REGISTRY[self.index()].2
}
pub fn severity(self) -> Severity {
REGISTRY[self.index()].3
}
pub fn disposition(self) -> Disposition {
REGISTRY[self.index()].4
}
fn index(self) -> usize {
REGISTRY.iter().position(|e| e.0 == self).unwrap_or(0)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ErrorId {
Code(u16),
Path(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedError {
pub id: ErrorId,
pub description: Option<String>,
}
impl ParsedError {
pub fn err_code(&self) -> Option<ErrCode> {
match &self.id {
ErrorId::Code(c) => ErrCode::from_code(*c),
ErrorId::Path(p) => ErrCode::from_path(p),
}
}
}
pub fn error_code(code: ErrCode, description: Option<&str>) -> Tlv {
error_with_id_value(value_u16(code.code()), description)
}
pub fn error_raw_code(code: u16, description: Option<&str>) -> Tlv {
error_with_id_value(value_u16(code), description)
}
pub fn error_string(path: &str, description: Option<&str>) -> Tlv {
let id = Tlv {
type_code: type_code::NAME,
opt: Opt::default(),
payload: path.as_bytes().to_vec(),
children: Vec::new(),
trailer: None,
};
error_with_id_value(id, description)
}
fn error_with_id_value(id: Tlv, description: Option<&str>) -> Tlv {
let mut children = alloc::vec![id];
if let Some(text) = description {
children.push(Tlv {
type_code: type_code::DESCRIPTION,
opt: Opt::default(),
payload: text.as_bytes().to_vec(),
children: Vec::new(),
trailer: None,
});
}
Tlv {
type_code: type_code::ERROR,
opt: Opt::structured(),
payload: Vec::new(),
children,
trailer: None,
}
}
pub fn parse_error(tlv: &Tlv) -> Result<ParsedError, BuildError> {
if tlv.type_code != type_code::ERROR {
return Err(BuildError::TypeMismatch);
}
let first = tlv.children.first().ok_or(BuildError::TypeMismatch)?;
let id = match first.type_code {
type_code::VALUE => {
if first.payload.len() < 2 {
return Err(BuildError::TypeMismatch);
}
ErrorId::Code(first.payload[0] as u16 | ((first.payload[1] as u16) << 8))
}
type_code::NAME => ErrorId::Path(first.payload_str()?.to_string()),
_ => return Err(BuildError::TypeMismatch),
};
let description = tlv
.children
.iter()
.find(|c| c.type_code == type_code::DESCRIPTION)
.map(|c| c.payload_str().map(|s| s.to_string()))
.transpose()?;
Ok(ParsedError { id, description })
}
pub fn status_ok() -> Tlv {
Tlv {
type_code: type_code::STATUS,
opt: Opt::default(),
payload: Vec::new(),
children: Vec::new(),
trailer: None,
}
}
pub fn status_with_errors(errors: &[Tlv]) -> Tlv {
Tlv {
type_code: type_code::STATUS,
opt: Opt::structured(),
payload: Vec::new(),
children: errors.to_vec(),
trailer: None,
}
}
pub fn status_errors(tlv: &Tlv) -> Result<Vec<ParsedError>, BuildError> {
if tlv.type_code != type_code::STATUS {
return Err(BuildError::TypeMismatch);
}
tlv.children
.iter()
.filter(|c| c.type_code == type_code::ERROR)
.map(parse_error)
.collect()
}