use std::fmt;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum ClmError {
#[error("Storage error [{0:?}]: {1}")]
Storage(StorageErrorCode, String),
#[error("CPN VM error [{0:?}]: {1}")]
Cpn(CpnErrorCode, String),
#[error("Authentication error [{0:?}]: {1}")]
Auth(AuthErrorCode, String),
#[error("Transport error [{0:?}]: {1}")]
Transport(TransportErrorCode, String),
#[error("Evaluator error [{0:?}]: {1}")]
Evaluator(EvaluatorErrorCode, String),
#[error("Manifest error [{0:?}]: {1}")]
Manifest(ManifestErrorCode, String),
#[error("Crypto error [{0:?}]: {1}")]
Crypto(CryptoErrorCode, String),
#[error("CRDT error [{0:?}]: {1}")]
Crdt(CrdtErrorCode, String),
#[error("Evaluation error: {0}")]
Evaluation(String),
#[error("YAML parse error: {0}")]
YamlParse(#[from] serde_yaml::Error),
#[error("JSON error: {0}")]
Json(#[from] serde_json::Error),
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
#[cfg(any(feature = "native", feature = "db"))]
#[error("Database error: {0}")]
Database(#[from] rusqlite::Error),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[repr(u32)]
pub enum StorageErrorCode {
CardNotFound = 1001,
CorruptedContent = 1002,
DatabaseUnavailable = 1003,
TransactionFailed = 1004,
SavepointFailed = 1005,
InvalidSchemaVersion = 1006,
QueryFailed = 1007,
}
impl fmt::Display for StorageErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}({})", self, *self as u32)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[repr(u32)]
pub enum CpnErrorCode {
Deadlock = 2001,
InvariantViolation = 2002,
InvalidTransition = 2003,
UnboundVariable = 2004,
TokenMismatch = 2005,
StateExplosion = 2006,
}
impl fmt::Display for CpnErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}({})", self, *self as u32)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[repr(u32)]
pub enum AuthErrorCode {
InvalidDid = 3001,
SignatureVerificationFailed = 3002,
ExpiredToken = 3003,
Unauthorized = 3004,
KeyGenerationFailed = 3005,
MalformedCredential = 3006,
}
impl fmt::Display for AuthErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}({})", self, *self as u32)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[repr(u32)]
pub enum TransportErrorCode {
ConnectionRefused = 4001,
HandshakeFailed = 4002,
Timeout = 4003,
TlsError = 4004,
ChannelClosed = 4005,
ProtocolViolation = 4006,
}
impl fmt::Display for TransportErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}({})", self, *self as u32)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[repr(u32)]
pub enum EvaluatorErrorCode {
KernelPanic = 5001,
DispatchNotFound = 5002,
InvalidArguments = 5003,
FiberFailure = 5004,
PostconditionFailed = 5005,
PreconditionFailed = 5006,
SubprocessError = 5007,
}
impl fmt::Display for EvaluatorErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}({})", self, *self as u32)
}
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub enum FiberError {
DomainViolation(String),
CodomainViolation(String),
UnitViolation(String),
BottomExecution(String),
}
impl fmt::Display for FiberError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
FiberError::DomainViolation(s) => write!(f, "PTR Domain Violation: {}", s),
FiberError::CodomainViolation(s) => write!(f, "PTR Codomain Violation: {}", s),
FiberError::UnitViolation(s) => write!(f, "PTR Unit Law Violation: {}", s),
FiberError::BottomExecution(s) => write!(f, "PTR Bottom Execution (⊥): {}", s),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[repr(u32)]
pub enum ManifestErrorCode {
ParseFailed = 6001,
MissingField = 6002,
HashMismatch = 6003,
CycleDetected = 6004,
InvalidVersion = 6005,
}
impl fmt::Display for ManifestErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}({})", self, *self as u32)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[repr(u32)]
pub enum CryptoErrorCode {
KeyDerivationFailed = 7001,
DecryptionFailed = 7002,
InvalidCiphertext = 7003,
EntropyExhausted = 7004,
KeyEncodingFailed = 7005,
}
impl fmt::Display for CryptoErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}({})", self, *self as u32)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[repr(u32)]
pub enum CrdtErrorCode {
ClockDrift = 8001,
ConcurrentConflict = 8002,
MergeFailed = 8003,
StateDivergence = 8004,
}
impl fmt::Display for CrdtErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}({})", self, *self as u32)
}
}
impl ClmError {
pub fn storage(code: StorageErrorCode, msg: impl Into<String>) -> Self {
ClmError::Storage(code, msg.into())
}
pub fn cpn(code: CpnErrorCode, msg: impl Into<String>) -> Self {
ClmError::Cpn(code, msg.into())
}
pub fn auth(code: AuthErrorCode, msg: impl Into<String>) -> Self {
ClmError::Auth(code, msg.into())
}
pub fn transport(code: TransportErrorCode, msg: impl Into<String>) -> Self {
ClmError::Transport(code, msg.into())
}
pub fn evaluator(code: EvaluatorErrorCode, msg: impl Into<String>) -> Self {
ClmError::Evaluator(code, msg.into())
}
pub fn fiber(err: FiberError) -> Self {
ClmError::Evaluator(EvaluatorErrorCode::FiberFailure, err.to_string())
}
pub fn manifest(code: ManifestErrorCode, msg: impl Into<String>) -> Self {
ClmError::Manifest(code, msg.into())
}
pub fn crypto(code: CryptoErrorCode, msg: impl Into<String>) -> Self {
ClmError::Crypto(code, msg.into())
}
pub fn crdt(code: CrdtErrorCode, msg: impl Into<String>) -> Self {
ClmError::Crdt(code, msg.into())
}
pub fn code(&self) -> u32 {
match self {
ClmError::Storage(code, _) => *code as u32,
ClmError::Cpn(code, _) => *code as u32,
ClmError::Auth(code, _) => *code as u32,
ClmError::Transport(code, _) => *code as u32,
ClmError::Evaluator(code, _) => *code as u32,
ClmError::Manifest(code, _) => *code as u32,
ClmError::Crypto(code, _) => *code as u32,
ClmError::Crdt(code, _) => *code as u32,
ClmError::Evaluation(_) => 5000,
ClmError::YamlParse(_) => 6000,
ClmError::Json(_) => 6010,
ClmError::Io(_) => 9000,
#[cfg(any(feature = "native", feature = "db"))]
ClmError::Database(_) => 1000,
}
}
pub fn domain(&self) -> &'static str {
match self {
ClmError::Storage(..) => "STORAGE",
ClmError::Cpn(..) => "CPN",
ClmError::Auth(..) => "AUTH",
ClmError::Transport(..) => "TRANSPORT",
ClmError::Evaluator(..) | ClmError::Evaluation(..) => "EVALUATOR",
ClmError::Manifest(..) | ClmError::YamlParse(..) | ClmError::Json(..) => "MANIFEST",
ClmError::Crypto(..) => "CRYPTO",
ClmError::Crdt(..) => "CRDT",
ClmError::Io(..) => "IO",
#[cfg(any(feature = "native", feature = "db"))]
ClmError::Database(..) => "STORAGE",
}
}
pub fn to_exit_code(&self) -> i32 {
match self {
ClmError::Evaluator(EvaluatorErrorCode::KernelPanic, _) => 101,
ClmError::Evaluator(..) | ClmError::Evaluation(..) => 1,
ClmError::Auth(..) => 2,
ClmError::Storage(..) => 3,
ClmError::Transport(..) => 4,
ClmError::Cpn(..) => 5,
ClmError::Manifest(..) => 6,
_ => 1,
}
}
pub fn to_payload(&self) -> serde_json::Value {
serde_json::json!({
"code": self.code(),
"domain": self.domain(),
"message": self.to_string(),
"data": {
"exit_code": self.to_exit_code(),
}
})
}
}
impl From<String> for ClmError {
fn from(err: String) -> Self {
ClmError::Evaluation(err)
}
}
impl From<&str> for ClmError {
fn from(err: &str) -> Self {
ClmError::Evaluation(err.to_string())
}
}
#[allow(dead_code)]
pub trait ResultExt<T> {
fn context<C: fmt::Display>(self, context: C) -> Result<T>;
fn with_context<C: fmt::Display, F: FnOnce() -> C>(self, f: F) -> Result<T>;
}
impl<T, E> ResultExt<T> for std::result::Result<T, E>
where
E: Into<ClmError>,
{
fn context<C: fmt::Display>(self, context: C) -> Result<T> {
self.map_err(|e| {
let clm_err = e.into();
ClmError::Evaluation(format!("{}: {}", context, clm_err))
})
}
fn with_context<C: fmt::Display, F: FnOnce() -> C>(self, f: F) -> Result<T> {
self.map_err(|e| {
let clm_err = e.into();
ClmError::Evaluation(format!("{}: {}", f(), clm_err))
})
}
}
pub type Result<T> = std::result::Result<T, ClmError>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_error_code_and_domain() {
let err = ClmError::storage(StorageErrorCode::CardNotFound, "Card not found: 0000");
assert_eq!(err.code(), 1001);
assert_eq!(err.domain(), "STORAGE");
assert_eq!(err.to_exit_code(), 3);
}
#[test]
fn test_fiber_error_construction() {
let fiber_err = FiberError::DomainViolation("Input out of range [0, 1]".into());
let err = ClmError::fiber(fiber_err);
assert_eq!(err.code(), 5004);
assert_eq!(err.domain(), "EVALUATOR");
assert!(err.to_string().contains("PTR Domain Violation"));
}
#[test]
fn test_satori_payload_serialization() {
let err = ClmError::auth(AuthErrorCode::Unauthorized, "Missing bearer token");
let payload = err.to_payload();
assert_eq!(payload["code"], 3004);
assert_eq!(payload["domain"], "AUTH");
assert_eq!(payload["data"]["exit_code"], 2);
}
#[test]
fn test_result_ext_context() {
let res: std::result::Result<(), &str> = Err("underlying failure");
let wrapped = res.context("Step 1 failed");
assert!(wrapped.is_err());
assert_eq!(
wrapped.unwrap_err().to_string(),
"Evaluation error: Step 1 failed: Evaluation error: underlying failure"
);
}
}