Skip to main content

khive_types/
khive_error.rs

1//! Unified cross-crate error model: `KhiveError`, `ErrorKind`, `ErrorCode`, `Details`, `RetryHint`.
2
3extern crate alloc;
4use alloc::borrow::Cow;
5use alloc::string::String;
6use core::fmt;
7
8#[cfg(feature = "serde")]
9use alloc::string::ToString;
10
11#[cfg(feature = "serde")]
12use serde::{Deserialize, Serialize};
13
14// ---- ErrorKind ----
15
16/// Semantic error category — maps to HTTP status codes.
17///
18/// | Variant | HTTP |
19/// |---------|------|
20/// | `NotFound` | 404 |
21/// | `InvalidInput` | 400 |
22/// | `Unauthorized` | 403 |
23/// | `Conflict` | 409 |
24/// | `Unavailable` | 503 |
25/// | `Internal` | 500 |
26///
27/// Closed taxonomy. New variants are a source-breaking change and require an ADR.
28#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
29#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
30#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
31pub enum ErrorKind {
32    NotFound,
33    InvalidInput,
34    Unauthorized,
35    Conflict,
36    Unavailable,
37    Internal,
38}
39
40impl ErrorKind {
41    /// HTTP status code for this kind.
42    pub fn http_status(self) -> u16 {
43        match self {
44            Self::NotFound => 404,
45            Self::InvalidInput => 400,
46            Self::Unauthorized => 403,
47            Self::Conflict => 409,
48            Self::Unavailable => 503,
49            Self::Internal => 500,
50        }
51    }
52
53    /// Snake-case string representation (stable across versions).
54    pub fn as_str(self) -> &'static str {
55        match self {
56            Self::NotFound => "not_found",
57            Self::InvalidInput => "invalid_input",
58            Self::Unauthorized => "unauthorized",
59            Self::Conflict => "conflict",
60            Self::Unavailable => "unavailable",
61            Self::Internal => "internal",
62        }
63    }
64}
65
66impl fmt::Display for ErrorKind {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        f.write_str(self.as_str())
69    }
70}
71
72// ---- ErrorDomain ----
73
74/// Domain that owns the error code namespace.
75///
76/// Only the OSS-relevant domains are exposed; internal-only domains
77/// (auth, billing, etc.) are not included.
78///
79/// Closed taxonomy. New variants are a source-breaking change and require an ADR.
80#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
81#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
82#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
83pub enum ErrorDomain {
84    Db,
85    Query,
86    Runtime,
87    Types,
88}
89
90impl ErrorDomain {
91    /// Return the lowercase string name for this domain.
92    pub fn as_str(self) -> &'static str {
93        match self {
94            Self::Db => "db",
95            Self::Query => "query",
96            Self::Runtime => "runtime",
97            Self::Types => "types",
98        }
99    }
100}
101
102impl fmt::Display for ErrorDomain {
103    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104        f.write_str(self.as_str())
105    }
106}
107
108// ---- ErrorCode ----
109
110/// Domain-scoped numeric error code.
111///
112/// Wire shape: `"domain:N"` (e.g., `"db:1"`, `"runtime:10"`).
113#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
114pub struct ErrorCode {
115    domain: ErrorDomain,
116    code: u32,
117}
118
119impl ErrorCode {
120    /// Create a new error code in the given domain.
121    pub fn new(domain: ErrorDomain, code: u32) -> Self {
122        Self { domain, code }
123    }
124
125    /// Return the domain that owns this error code.
126    pub fn domain(self) -> ErrorDomain {
127        self.domain
128    }
129
130    /// Return the numeric code within the domain.
131    pub fn code(self) -> u32 {
132        self.code
133    }
134}
135
136impl fmt::Display for ErrorCode {
137    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138        write!(f, "{}:{}", self.domain, self.code)
139    }
140}
141
142#[cfg(feature = "serde")]
143impl Serialize for ErrorCode {
144    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
145        s.serialize_str(&self.to_string())
146    }
147}
148
149#[cfg(feature = "serde")]
150impl<'de> Deserialize<'de> for ErrorCode {
151    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
152        let s = alloc::string::String::deserialize(d)?;
153        let (domain_str, code_str) = s
154            .split_once(':')
155            .ok_or_else(|| serde::de::Error::custom("expected 'domain:N'"))?;
156        let domain = match domain_str {
157            "db" => ErrorDomain::Db,
158            "query" => ErrorDomain::Query,
159            "runtime" => ErrorDomain::Runtime,
160            "types" => ErrorDomain::Types,
161            other => {
162                return Err(serde::de::Error::custom(alloc::format!(
163                    "unknown domain: {other}"
164                )))
165            }
166        };
167        let code: u32 = code_str.parse().map_err(serde::de::Error::custom)?;
168        Ok(ErrorCode::new(domain, code))
169    }
170}
171
172// ---- RetryHint ----
173
174/// Guidance to callers on whether retrying the operation makes sense.
175#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
176#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
177#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
178pub enum RetryHint {
179    /// Do not retry — the same request will fail again.
180    NoRetry,
181    /// Retry may succeed (transient failure).
182    Retryable,
183}
184
185// ---- Details ----
186
187/// Reserved key inserted in place of the 8th slot when a `Details` source
188/// (constructor input or a deserialized wire map) supplies more than 8 pairs.
189/// Its value is the count of dropped pairs, so truncation is observable
190/// instead of silently discarding data (RUNTIME-AUD-002 / #487 follow-up).
191pub const DETAILS_TRUNCATED_KEY: &str = "details_truncated";
192
193/// Bounded key/value metadata attached to a `KhiveError` (max 8 pairs).
194///
195/// Stored as `Cow<'static, str>` pairs: zero-alloc for static string literals
196/// (the common construction path) and owned strings on deserialization (no
197/// memory leak). Both paths are `no_std` + `alloc` compatible.
198///
199/// When the source supplies more than 8 pairs, the wire shape stays bounded
200/// at 8 entries, but the truncation is observable: the first 7 pairs are
201/// retained and the 8th slot becomes [`DETAILS_TRUNCATED_KEY`] mapped to the
202/// dropped-pair count. [`DETAILS_TRUNCATED_KEY`] is a *reserved* key: a
203/// client-supplied pair using that name is never retained as an ordinary
204/// entry (PR #549) — it is stripped and folded into the
205/// drop count instead, so a client can neither fake truncation on a small
206/// map nor shadow the real indicator on an oversized one. The drop count
207/// itself is tracked in an internal, non-serialized field
208/// ([`Details::dropped_count`]) rather than parsed back out of the entry
209/// list, so a same-shaped client map can't spoof it either.
210#[derive(Clone, Debug, PartialEq, Eq)]
211pub struct Details {
212    entries: alloc::vec::Vec<(Cow<'static, str>, Cow<'static, str>)>,
213    /// Internal truncation flag — `Some(dropped_count)` when this instance
214    /// was built by dropping pairs (8-entry overflow and/or a reserved-key
215    /// collision), `None` otherwise. Not serialized directly; the wire
216    /// shape communicates truncation via the [`DETAILS_TRUNCATED_KEY`]
217    /// entry, this field is the trusted, non-spoofable read side.
218    dropped: Option<usize>,
219}
220
221impl Details {
222    /// Build `Details` from an iterable of `(&'static str, &'static str)` pairs.
223    ///
224    /// Up to 8 pairs are kept as-is. When more than 8 are supplied, the first
225    /// 7 client pairs are kept and the 8th slot is replaced with
226    /// [`DETAILS_TRUNCATED_KEY`] carrying the dropped-pair count, so the
227    /// truncation is observable rather than silent. A client-supplied pair
228    /// named [`DETAILS_TRUNCATED_KEY`] is always treated as reserved: it is
229    /// dropped (never stored as an ordinary entry) and counted, even when
230    /// the remaining pairs fit within the 8-entry bound.
231    pub fn new<I>(pairs: I) -> Self
232    where
233        I: IntoIterator<Item = (&'static str, &'static str)>,
234    {
235        let all: alloc::vec::Vec<(&'static str, &'static str)> = pairs.into_iter().collect();
236        Self::from_owned(
237            all.into_iter()
238                .map(|(k, v)| (Cow::Borrowed(k), Cow::Borrowed(v))),
239        )
240    }
241
242    /// Build `Details` from static keys paired with owned, dynamically
243    /// computed values — e.g. a UUID or other runtime-generated string that
244    /// cannot be expressed as `&'static str`. Same bounding/truncation rules
245    /// as [`Details::new`].
246    pub fn new_owned<I>(pairs: I) -> Self
247    where
248        I: IntoIterator<Item = (&'static str, String)>,
249    {
250        Self::from_owned(
251            pairs
252                .into_iter()
253                .map(|(k, v)| (Cow::Borrowed(k), Cow::Owned(v))),
254        )
255    }
256
257    /// Shared bounding/truncation logic for the constructor: partition the
258    /// source into ordinary pairs and reserved-key collisions, then hand
259    /// off to [`Details::build`] for the bound + indicator logic.
260    fn from_owned<I>(pairs: I) -> Self
261    where
262        I: IntoIterator<Item = (Cow<'static, str>, Cow<'static, str>)>,
263    {
264        let mut ordinary: alloc::vec::Vec<(Cow<'static, str>, Cow<'static, str>)> =
265            alloc::vec::Vec::new();
266        let mut total_ordinary: usize = 0;
267        let mut collisions: usize = 0;
268        for (k, v) in pairs {
269            if k.as_ref() == DETAILS_TRUNCATED_KEY {
270                collisions += 1;
271            } else {
272                total_ordinary += 1;
273                if ordinary.len() < 8 {
274                    ordinary.push((k, v));
275                }
276            }
277        }
278        Self::build(ordinary, total_ordinary, collisions)
279    }
280
281    /// Bounding/truncation core. See
282    /// crates/khive-types/docs/api/error-taxonomy.md#detailsbuild--boundingtruncation-algorithm
283    fn build(
284        ordinary: alloc::vec::Vec<(Cow<'static, str>, Cow<'static, str>)>,
285        total_ordinary: usize,
286        collisions: usize,
287    ) -> Self {
288        if total_ordinary <= 8 && collisions == 0 {
289            return Self {
290                entries: ordinary,
291                dropped: None,
292            };
293        }
294        let keep = total_ordinary.min(7);
295        let dropped = (total_ordinary - keep) + collisions;
296        let mut entries: alloc::vec::Vec<_> = ordinary.into_iter().take(keep).collect();
297        entries.push((
298            Cow::Borrowed(DETAILS_TRUNCATED_KEY),
299            Cow::Owned(alloc::format!("{dropped}")),
300        ));
301        Self {
302            entries,
303            dropped: Some(dropped),
304        }
305    }
306
307    /// Look up a value by key.
308    pub fn get(&self, key: &str) -> Option<&str> {
309        self.entries
310            .iter()
311            .find(|(k, _)| k.as_ref() == key)
312            .map(|(_, v)| v.as_ref())
313    }
314
315    /// Iterate over (key, value) pairs.
316    pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> + '_ {
317        self.entries.iter().map(|(k, v)| (k.as_ref(), v.as_ref()))
318    }
319
320    /// Number of pairs dropped due to the 8-entry bound and/or a
321    /// reserved-key collision, if any were.
322    ///
323    /// Returns `None` when nothing was dropped. Returns
324    /// `Some(dropped_count)` otherwise, read from the internal truncation
325    /// flag set at construction/deserialization time — never re-parsed from
326    /// the entry list, so a client-supplied `details_truncated` pair can't
327    /// spoof this value.
328    pub fn dropped_count(&self) -> Option<usize> {
329        self.dropped
330    }
331}
332
333#[cfg(feature = "serde")]
334impl Serialize for Details {
335    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
336        use serde::ser::SerializeMap;
337        let mut map = s.serialize_map(Some(self.entries.len()))?;
338        for (k, v) in &self.entries {
339            map.serialize_entry(k.as_ref(), v.as_ref())?;
340        }
341        map.end()
342    }
343}
344
345#[cfg(feature = "serde")]
346impl<'de> Deserialize<'de> for Details {
347    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
348        use serde::de::{MapAccess, Visitor};
349
350        struct DetailsVisitor;
351
352        impl<'de> Visitor<'de> for DetailsVisitor {
353            type Value = Details;
354
355            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
356                f.write_str("a map of string key-value pairs")
357            }
358
359            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Details, A::Error> {
360                // Drains to completion regardless of size (fixes #487: early-exit
361                // at 8 entries left trailing map bytes unconsumed). Detects a
362                // round-tripped self-truncated map vs. a client-supplied
363                // DETAILS_TRUNCATED_KEY collision — see
364                // crates/khive-types/docs/api/error-taxonomy.md#details-deserialization--round-trip-detection-of-self-truncated-maps
365                let mut ordinary: alloc::vec::Vec<(Cow<'static, str>, Cow<'static, str>)> =
366                    alloc::vec::Vec::new();
367                let mut total_ordinary: usize = 0;
368                let mut reserved_count: usize = 0;
369                let mut reserved_is_trailing = false;
370                let mut reserved_follows_seven = false;
371                let mut last_reserved_value: Option<String> = None;
372                while let Some((k, v)) = map.next_entry::<String, String>()? {
373                    if k == DETAILS_TRUNCATED_KEY {
374                        reserved_count += 1;
375                        reserved_is_trailing = true;
376                        reserved_follows_seven = total_ordinary == 7;
377                        last_reserved_value = Some(v);
378                    } else {
379                        reserved_is_trailing = false;
380                        total_ordinary += 1;
381                        if ordinary.len() < 8 {
382                            ordinary.push((Cow::Owned(k), Cow::Owned(v)));
383                        }
384                    }
385                }
386                if reserved_count == 1 && reserved_is_trailing && reserved_follows_seven {
387                    if let Some(dropped) =
388                        last_reserved_value.as_deref().and_then(|s| s.parse().ok())
389                    {
390                        let mut entries = ordinary;
391                        entries.push((
392                            Cow::Borrowed(DETAILS_TRUNCATED_KEY),
393                            Cow::Owned(alloc::format!("{dropped}")),
394                        ));
395                        return Ok(Details {
396                            entries,
397                            dropped: Some(dropped),
398                        });
399                    }
400                }
401                Ok(Details::build(ordinary, total_ordinary, reserved_count))
402            }
403        }
404
405        d.deserialize_map(DetailsVisitor)
406    }
407}
408
409// ---- KhiveError ----
410
411/// Unified error type for the khive runtime.
412///
413/// # Wire shape (serde)
414///
415/// ```json
416/// {
417///   "kind": "not_found",
418///   "message": "entity not found: abc123",
419///   "code": "runtime:10",
420///   "details": { "resource": "entity", "id": "abc123" }
421/// }
422/// ```
423///
424/// `code` and `details` are `null` when absent.
425#[derive(Clone, Debug)]
426#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
427pub struct KhiveError {
428    kind: ErrorKind,
429    message: String,
430    code: Option<ErrorCode>,
431    details: Option<Details>,
432}
433
434impl KhiveError {
435    // ---- constructors ----
436
437    /// Create a `NotFound` error for a missing resource identified by `id`.
438    pub fn not_found(resource: impl fmt::Display, id: impl fmt::Display) -> Self {
439        Self {
440            kind: ErrorKind::NotFound,
441            message: alloc::format!("{resource} not found: {id}"),
442            code: None,
443            details: None,
444        }
445    }
446
447    /// Create an `InvalidInput` error with the given message.
448    pub fn invalid_input(message: impl Into<String>) -> Self {
449        Self {
450            kind: ErrorKind::InvalidInput,
451            message: alloc::format!("invalid input: {}", message.into()),
452            code: None,
453            details: None,
454        }
455    }
456
457    /// Create an `Unauthorized` error with the given message.
458    pub fn unauthorized(message: impl Into<String>) -> Self {
459        Self {
460            kind: ErrorKind::Unauthorized,
461            message: alloc::format!("unauthorized: {}", message.into()),
462            code: None,
463            details: None,
464        }
465    }
466
467    /// Create a `Conflict` error with the given message.
468    pub fn conflict(message: impl Into<String>) -> Self {
469        Self {
470            kind: ErrorKind::Conflict,
471            message: alloc::format!("conflict: {}", message.into()),
472            code: None,
473            details: None,
474        }
475    }
476
477    /// Create an `Unavailable` error with the given message.
478    pub fn unavailable(message: impl Into<String>) -> Self {
479        Self {
480            kind: ErrorKind::Unavailable,
481            message: alloc::format!("unavailable: {}", message.into()),
482            code: None,
483            details: None,
484        }
485    }
486
487    /// Create an `Internal` error with the given message.
488    pub fn internal(message: impl Into<String>) -> Self {
489        Self {
490            kind: ErrorKind::Internal,
491            message: alloc::format!("internal: {}", message.into()),
492            code: None,
493            details: None,
494        }
495    }
496
497    // ---- builder methods ----
498
499    /// Attach a domain-scoped error code.
500    pub fn with_code(mut self, code: ErrorCode) -> Self {
501        self.code = Some(code);
502        self
503    }
504
505    /// Attach bounded key-value metadata.
506    pub fn with_details(mut self, details: Details) -> Self {
507        self.details = Some(details);
508        self
509    }
510
511    // ---- accessors ----
512
513    /// Return the semantic error category.
514    pub fn kind(&self) -> ErrorKind {
515        self.kind
516    }
517
518    /// Return the human-readable error message.
519    pub fn message(&self) -> &str {
520        &self.message
521    }
522
523    /// Return the domain-scoped error code, if set.
524    pub fn code(&self) -> Option<ErrorCode> {
525        self.code
526    }
527
528    /// Return the bounded metadata details, if set.
529    pub fn details(&self) -> Option<&Details> {
530        self.details.as_ref()
531    }
532
533    /// Retry guidance based on the error kind.
534    pub fn retry_hint(&self) -> RetryHint {
535        match self.kind {
536            ErrorKind::Unavailable => RetryHint::Retryable,
537            _ => RetryHint::NoRetry,
538        }
539    }
540}
541
542impl fmt::Display for KhiveError {
543    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
544        write!(f, "{}", self.message)
545    }
546}
547
548#[cfg(feature = "std")]
549impl std::error::Error for KhiveError {}