1use std::fmt;
2
3#[derive(Clone, Copy, PartialEq, Eq, Hash)]
5pub struct Hash([u8; 32]);
6
7impl Hash {
8 pub fn from_bytes(bytes: &[u8; 32]) -> Self {
10 Hash(*bytes)
11 }
12
13 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#[derive(Debug)]
79pub enum AreevError {
80 NotFound(Hash),
81 Format(String),
82 Validation(String),
83 Serialization(String),
84 ToolRenderUnsupported(String),
85 Storage(String),
86 StoreBusy(String),
89 SupersessionConflict(Hash),
90 CryptoError(String),
91 AccumulateRetryExhausted,
92 AccumulateInternal(String),
93 AccumulateBackpressureRejected,
94 Internal(String),
95 AuthzDenied(String),
97 AuthzUnknownPrincipal(String),
99 AuthzConfigInvalid(String),
101 AuthzTokenUnrecognized,
104}
105
106impl AreevError {
107 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 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 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 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 #[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 #[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}