Skip to main content

areev_core/
error.rs

1use std::fmt;
2
3/// Content-addressed SHA-256 hash (32 bytes, displayed as lowercase hex).
4#[derive(Clone, Copy, PartialEq, Eq, Hash)]
5pub struct Hash([u8; 32]);
6
7impl Hash {
8    /// Create a hash from a fixed-size 32-byte array (compile-time safe).
9    pub fn from_bytes(bytes: &[u8; 32]) -> Self {
10        Hash(*bytes)
11    }
12
13    /// Create a hash from a variable-length byte slice (fallible).
14    pub fn try_from_bytes(bytes: &[u8]) -> Result<Self> {
15        if bytes.len() < 32 {
16            return Err(AreevError::Format(format!(
17                "hash requires 32 bytes, got {}",
18                bytes.len()
19            )));
20        }
21        let mut arr = [0u8; 32];
22        arr.copy_from_slice(&bytes[..32]);
23        Ok(Hash(arr))
24    }
25
26    pub fn from_hex(hex_str: &str) -> Result<Self> {
27        let bytes = hex::decode(hex_str)
28            .map_err(|e| AreevError::Format(format!("invalid hex hash: {}", e)))?;
29        if bytes.len() != 32 {
30            return Err(AreevError::Format(format!(
31                "hash must be 32 bytes, got {}",
32                bytes.len()
33            )));
34        }
35        Ok(Self::from_bytes(&bytes.try_into().unwrap()))
36    }
37
38    pub fn as_bytes(&self) -> &[u8; 32] {
39        &self.0
40    }
41
42    pub fn to_hex(&self) -> String {
43        hex::encode(self.0)
44    }
45}
46
47impl fmt::Debug for Hash {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        write!(f, "Hash({})", &self.to_hex()[..16])
50    }
51}
52
53impl fmt::Display for Hash {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        write!(f, "{}", self.to_hex())
56    }
57}
58
59impl serde::Serialize for Hash {
60    fn serialize<S: serde::Serializer>(
61        &self,
62        serializer: S,
63    ) -> std::result::Result<S::Ok, S::Error> {
64        serializer.serialize_str(&self.to_hex())
65    }
66}
67
68impl<'de> serde::Deserialize<'de> for Hash {
69    fn deserialize<D: serde::Deserializer<'de>>(
70        deserializer: D,
71    ) -> std::result::Result<Self, D::Error> {
72        let s = String::deserialize(deserializer)?;
73        Hash::from_hex(&s).map_err(serde::de::Error::custom)
74    }
75}
76
77/// All errors in areev-core.
78#[derive(Debug)]
79pub enum AreevError {
80    NotFound(Hash),
81    Format(String),
82    Validation(String),
83    Serialization(String),
84    ToolRenderUnsupported(String),
85    Storage(String),
86    /// Another writer holds this memory (single-writer-per-memory is
87    /// enforced, not advisory, on backends that can arbitrate it).
88    StoreBusy(String),
89    SupersessionConflict(Hash),
90    CryptoError(String),
91    AccumulateRetryExhausted,
92    AccumulateInternal(String),
93    AccumulateBackpressureRejected,
94    Internal(String),
95    /// A verb the session's grants don't cover (`authz::AuthzSet::check`).
96    AuthzDenied(String),
97    /// A principal name no credential authenticates.
98    AuthzUnknownPrincipal(String),
99    /// The credential map failed to load or validate (fail closed).
100    AuthzConfigInvalid(String),
101    /// A presented bearer token matched no credential. Deliberately carries
102    /// no payload: a refused secret must never reach a log line.
103    AuthzTokenUnrecognized,
104}
105
106impl AreevError {
107    /// Stable machine-readable error code in `DOMAIN-Ennn` form (see the
108    /// repo-root `ERROR_CODES.md` registry). Every `Display` string begins
109    /// with this code, so a user who reports the leading token points us at
110    /// the exact variant and subsystem. **Codes are append-only debugging
111    /// handles — never renumber or reuse an existing one.**
112    pub fn code(&self) -> &'static str {
113        match self {
114            Self::NotFound(_) => "MEM-E001",
115            Self::SupersessionConflict(_) => "MEM-E002",
116            Self::ToolRenderUnsupported(_) => "MEM-E110",
117            Self::Format(_) => "FMT-E001",
118            Self::Serialization(_) => "FMT-E002",
119            Self::Validation(_) => "VAL-E001",
120            Self::Storage(_) => "STO-E001",
121            Self::StoreBusy(_) => "STO-E002",
122            Self::CryptoError(_) => "CRY-E001",
123            // These originate in CAL ACCUMULATE semantics and bubble up
124            // through the store, so they keep their CAL-domain codes.
125            Self::AccumulateRetryExhausted => "CAL-E083",
126            Self::AccumulateInternal(_) => "CAL-E084",
127            Self::AccumulateBackpressureRejected => "CAL-E085",
128            Self::Internal(_) => "SYS-E001",
129            Self::AuthzDenied(_) => "AUT-E001",
130            Self::AuthzUnknownPrincipal(_) => "AUT-E002",
131            Self::AuthzConfigInvalid(_) => "AUT-E003",
132            Self::AuthzTokenUnrecognized => "AUT-E004",
133        }
134    }
135}
136
137impl std::fmt::Display for AreevError {
138    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139        // Invariant: every arm's message starts with `self.code()` — pinned by
140        // `code_prefixes_every_display` in the tests below.
141        match self {
142            Self::NotFound(h) => write!(f, "MEM-E001: grain not found: {h}"),
143            Self::SupersessionConflict(h) => write!(f, "MEM-E002: already superseded: {h}"),
144            Self::ToolRenderUnsupported(m) => write!(f, "MEM-E110: tool render unsupported: {m}"),
145            Self::Format(m) => write!(f, "FMT-E001: format error: {m}"),
146            Self::Serialization(m) => write!(f, "FMT-E002: serialization error: {m}"),
147            Self::Validation(m) => write!(f, "VAL-E001: validation error: {m}"),
148            Self::Storage(m) => write!(f, "STO-E001: storage error: {m}"),
149            Self::StoreBusy(m) => write!(f, "STO-E002: store busy: {m}"),
150            Self::CryptoError(m) => write!(f, "CRY-E001: crypto error: {m}"),
151            Self::AccumulateRetryExhausted => write!(f, "CAL-E083: ACCUMULATE retry budget exhausted"),
152            Self::AccumulateInternal(m) => write!(f, "CAL-E084: ACCUMULATE internal failure: {m}"),
153            Self::AccumulateBackpressureRejected => write!(f, "CAL-E085: ACCUMULATE backpressure: inflight cap exceeded"),
154            Self::Internal(m) => write!(f, "SYS-E001: internal error: {m}"),
155            Self::AuthzDenied(m) => write!(f, "AUT-E001: authorization denied: {m}"),
156            Self::AuthzUnknownPrincipal(p) => write!(f, "AUT-E002: unknown principal: {p}"),
157            Self::AuthzConfigInvalid(m) => write!(f, "AUT-E003: {m}"),
158            Self::AuthzTokenUnrecognized => write!(f, "AUT-E004: token not recognized"),
159        }
160    }
161}
162
163impl std::error::Error for AreevError {}
164
165pub type Result<T> = std::result::Result<T, AreevError>;
166
167#[cfg(test)]
168mod error_code_tests {
169    use super::*;
170
171    /// One representative instance of every variant — extend when adding one.
172    fn all_variants() -> Vec<AreevError> {
173        let h = Hash::from_bytes(&[0u8; 32]);
174        vec![
175            AreevError::NotFound(h),
176            AreevError::SupersessionConflict(h),
177            AreevError::ToolRenderUnsupported("x".into()),
178            AreevError::Format("x".into()),
179            AreevError::Serialization("x".into()),
180            AreevError::Validation("x".into()),
181            AreevError::Storage("x".into()),
182            AreevError::StoreBusy("x".into()),
183            AreevError::CryptoError("x".into()),
184            AreevError::AccumulateRetryExhausted,
185            AreevError::AccumulateInternal("x".into()),
186            AreevError::AccumulateBackpressureRejected,
187            AreevError::Internal("x".into()),
188            AreevError::AuthzDenied("x".into()),
189            AreevError::AuthzUnknownPrincipal("x".into()),
190            AreevError::AuthzConfigInvalid("x".into()),
191            AreevError::AuthzTokenUnrecognized,
192        ]
193    }
194
195    /// The reported code must be the leading token of the message, so a user
196    /// pasting either gives us the same handle.
197    #[test]
198    fn code_prefixes_every_display() {
199        for e in all_variants() {
200            let msg = e.to_string();
201            let code = e.code();
202            assert!(
203                msg.starts_with(&format!("{code}: ")),
204                "`{msg}` must start with its code `{code}`"
205            );
206        }
207    }
208
209    /// Every code matches the `DOMAIN-Ennn` standard (see ERROR_CODES.md):
210    /// a 3-letter uppercase domain, `-E`, then digits.
211    #[test]
212    fn codes_follow_the_repo_standard() {
213        for e in all_variants() {
214            let c = e.code();
215            let (domain, num) = c.split_once("-E").unwrap_or_else(|| panic!("bad code: {c}"));
216            assert_eq!(domain.len(), 3, "{c}: domain must be 3 letters");
217            assert!(domain.chars().all(|ch| ch.is_ascii_uppercase()), "{c}: domain uppercase");
218            assert!(!num.is_empty() && num.chars().all(|ch| ch.is_ascii_digit()), "{c}: numeric suffix");
219        }
220    }
221}