khive-types 0.2.0

Core type primitives: Id128, Timestamp, Namespace, and the 3 substrate data types (Note, Entity, Event).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! Structured cross-crate error model for khive.
//!
//! Ported from khive-internal's `foundation/types/src/error/`.
//!
//! # Design
//!
//! - `KhiveError` — unified error struct with kind + code + message + details
//! - `ErrorKind` — semantic severity / HTTP-mapping bucket
//! - `ErrorCode` — domain-scoped numeric code (`ErrorDomain::Db, 1`)
//! - `Details` — bounded key/value metadata (max 8 pairs)
//! - `RetryHint` — whether the caller should retry
//!
//! All types are `#![no_std]` compatible. Serde impls are feature-gated
//! behind the `serde` flag (existing crate pattern).

extern crate alloc;
use alloc::borrow::Cow;
use alloc::string::String;
use core::fmt;

#[cfg(feature = "serde")]
use alloc::string::ToString;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

// ---- ErrorKind ----

/// Semantic error category — maps to HTTP status codes.
///
/// | Variant | HTTP |
/// |---------|------|
/// | `NotFound` | 404 |
/// | `InvalidInput` | 400 |
/// | `Unauthorized` | 403 |
/// | `Conflict` | 409 |
/// | `Unavailable` | 503 |
/// | `Internal` | 500 |
///
/// Closed taxonomy. New variants are a source-breaking change and require an ADR.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum ErrorKind {
    NotFound,
    InvalidInput,
    Unauthorized,
    Conflict,
    Unavailable,
    Internal,
}

impl ErrorKind {
    /// HTTP status code for this kind.
    pub fn http_status(self) -> u16 {
        match self {
            Self::NotFound => 404,
            Self::InvalidInput => 400,
            Self::Unauthorized => 403,
            Self::Conflict => 409,
            Self::Unavailable => 503,
            Self::Internal => 500,
        }
    }

    /// Snake-case string representation (stable across versions).
    pub fn as_str(self) -> &'static str {
        match self {
            Self::NotFound => "not_found",
            Self::InvalidInput => "invalid_input",
            Self::Unauthorized => "unauthorized",
            Self::Conflict => "conflict",
            Self::Unavailable => "unavailable",
            Self::Internal => "internal",
        }
    }
}

impl fmt::Display for ErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

// ---- ErrorDomain ----

/// Domain that owns the error code namespace.
///
/// Only the OSS-relevant domains are exposed; internal-only domains
/// (auth, billing, etc.) are not included.
///
/// Closed taxonomy. New variants are a source-breaking change and require an ADR.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
pub enum ErrorDomain {
    Db,
    Query,
    Runtime,
    Types,
}

impl ErrorDomain {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Db => "db",
            Self::Query => "query",
            Self::Runtime => "runtime",
            Self::Types => "types",
        }
    }
}

impl fmt::Display for ErrorDomain {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

// ---- ErrorCode ----

/// Domain-scoped numeric error code.
///
/// Wire shape: `"domain:N"` (e.g., `"db:1"`, `"runtime:10"`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ErrorCode {
    domain: ErrorDomain,
    code: u32,
}

impl ErrorCode {
    pub fn new(domain: ErrorDomain, code: u32) -> Self {
        Self { domain, code }
    }

    pub fn domain(self) -> ErrorDomain {
        self.domain
    }

    pub fn code(self) -> u32 {
        self.code
    }
}

impl fmt::Display for ErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}:{}", self.domain, self.code)
    }
}

#[cfg(feature = "serde")]
impl Serialize for ErrorCode {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(&self.to_string())
    }
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for ErrorCode {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let s = alloc::string::String::deserialize(d)?;
        let (domain_str, code_str) = s
            .split_once(':')
            .ok_or_else(|| serde::de::Error::custom("expected 'domain:N'"))?;
        let domain = match domain_str {
            "db" => ErrorDomain::Db,
            "query" => ErrorDomain::Query,
            "runtime" => ErrorDomain::Runtime,
            "types" => ErrorDomain::Types,
            other => {
                return Err(serde::de::Error::custom(alloc::format!(
                    "unknown domain: {other}"
                )))
            }
        };
        let code: u32 = code_str.parse().map_err(serde::de::Error::custom)?;
        Ok(ErrorCode::new(domain, code))
    }
}

// ---- RetryHint ----

/// Guidance to callers on whether retrying the operation makes sense.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum RetryHint {
    /// Do not retry — the same request will fail again.
    NoRetry,
    /// Retry may succeed (transient failure).
    Retryable,
}

// ---- Details ----

/// Bounded key/value metadata attached to a `KhiveError` (max 8 pairs).
///
/// Stored as `Cow<'static, str>` pairs: zero-alloc for static string literals
/// (the common construction path) and owned strings on deserialization (no
/// memory leak). Both paths are `no_std` + `alloc` compatible.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Details {
    entries: alloc::vec::Vec<(Cow<'static, str>, Cow<'static, str>)>,
}

impl Details {
    /// Build `Details` from an iterable of `(&'static str, &'static str)` pairs.
    /// Silently truncates to 8 entries.
    pub fn new<I>(pairs: I) -> Self
    where
        I: IntoIterator<Item = (&'static str, &'static str)>,
    {
        let entries: alloc::vec::Vec<_> = pairs
            .into_iter()
            .take(8)
            .map(|(k, v)| (Cow::Borrowed(k), Cow::Borrowed(v)))
            .collect();
        Self { entries }
    }

    /// Look up a value by key.
    pub fn get(&self, key: &str) -> Option<&str> {
        self.entries
            .iter()
            .find(|(k, _)| k.as_ref() == key)
            .map(|(_, v)| v.as_ref())
    }

    /// Iterate over (key, value) pairs.
    pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> + '_ {
        self.entries.iter().map(|(k, v)| (k.as_ref(), v.as_ref()))
    }
}

#[cfg(feature = "serde")]
impl Serialize for Details {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;
        let mut map = s.serialize_map(Some(self.entries.len()))?;
        for (k, v) in &self.entries {
            map.serialize_entry(k.as_ref(), v.as_ref())?;
        }
        map.end()
    }
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Details {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        use serde::de::{MapAccess, Visitor};

        struct DetailsVisitor;

        impl<'de> Visitor<'de> for DetailsVisitor {
            type Value = Details;

            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("a map of string key-value pairs")
            }

            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Details, A::Error> {
                let mut entries: alloc::vec::Vec<(Cow<'static, str>, Cow<'static, str>)> =
                    alloc::vec::Vec::new();
                while let Some((k, v)) = map.next_entry::<String, String>()? {
                    if entries.len() >= 8 {
                        break;
                    }
                    entries.push((Cow::Owned(k), Cow::Owned(v)));
                }
                Ok(Details { entries })
            }
        }

        d.deserialize_map(DetailsVisitor)
    }
}

// ---- KhiveError ----

/// Unified error type for the khive runtime.
///
/// # Wire shape (serde)
///
/// ```json
/// {
///   "kind": "not_found",
///   "message": "entity not found: abc123",
///   "code": "runtime:10",
///   "details": { "resource": "entity", "id": "abc123" }
/// }
/// ```
///
/// `code` and `details` are `null` when absent.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct KhiveError {
    kind: ErrorKind,
    message: String,
    code: Option<ErrorCode>,
    details: Option<Details>,
}

impl KhiveError {
    // ---- constructors ----

    pub fn not_found(resource: impl fmt::Display, id: impl fmt::Display) -> Self {
        Self {
            kind: ErrorKind::NotFound,
            message: alloc::format!("{resource} not found: {id}"),
            code: None,
            details: None,
        }
    }

    pub fn invalid_input(message: impl Into<String>) -> Self {
        Self {
            kind: ErrorKind::InvalidInput,
            message: alloc::format!("invalid input: {}", message.into()),
            code: None,
            details: None,
        }
    }

    pub fn unauthorized(message: impl Into<String>) -> Self {
        Self {
            kind: ErrorKind::Unauthorized,
            message: alloc::format!("unauthorized: {}", message.into()),
            code: None,
            details: None,
        }
    }

    pub fn conflict(message: impl Into<String>) -> Self {
        Self {
            kind: ErrorKind::Conflict,
            message: alloc::format!("conflict: {}", message.into()),
            code: None,
            details: None,
        }
    }

    pub fn unavailable(message: impl Into<String>) -> Self {
        Self {
            kind: ErrorKind::Unavailable,
            message: alloc::format!("unavailable: {}", message.into()),
            code: None,
            details: None,
        }
    }

    pub fn internal(message: impl Into<String>) -> Self {
        Self {
            kind: ErrorKind::Internal,
            message: alloc::format!("internal: {}", message.into()),
            code: None,
            details: None,
        }
    }

    // ---- builder methods ----

    pub fn with_code(mut self, code: ErrorCode) -> Self {
        self.code = Some(code);
        self
    }

    pub fn with_details(mut self, details: Details) -> Self {
        self.details = Some(details);
        self
    }

    // ---- accessors ----

    pub fn kind(&self) -> ErrorKind {
        self.kind
    }

    pub fn message(&self) -> &str {
        &self.message
    }

    pub fn code(&self) -> Option<ErrorCode> {
        self.code
    }

    pub fn details(&self) -> Option<&Details> {
        self.details.as_ref()
    }

    /// Retry guidance based on the error kind.
    pub fn retry_hint(&self) -> RetryHint {
        match self.kind {
            ErrorKind::Unavailable => RetryHint::Retryable,
            _ => RetryHint::NoRetry,
        }
    }
}

impl fmt::Display for KhiveError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

#[cfg(feature = "std")]
impl std::error::Error for KhiveError {}