Skip to main content

troupekit_core/
error.rs

1use serde::{Deserialize, Serialize};
2
3/// Errors from core types and storage backends.
4/// Covers bad input, optimistic-lock conflicts, vector dimension mismatches,
5/// missing records and backend failures; each variant carries its detail.
6#[derive(Debug, Clone, PartialEq, thiserror::Error)]
7pub enum CoreError {
8    #[error("invalid message: {0}")]
9    InvalidMessage(String),
10    #[error("conflict: expected version {expected}, found {actual}")]
11    Conflict { expected: u64, actual: u64 },
12    #[error("vector dimension mismatch: expected {expected}, got {actual}")]
13    DimensionMismatch { expected: usize, actual: usize },
14    #[error("not found: {0}")]
15    NotFound(String),
16    #[error("store error: {0}")]
17    Store(String),
18}
19
20/// Kind of a failed model or provider call.
21/// The kind alone decides whether a retry middleware may repeat the call;
22/// see `ProviderError::is_retryable`. `Host`: a model supplied by a binding
23/// host failed in its own callback; it is never retried.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
25pub enum ProviderErrorKind {
26    RateLimited,
27    Auth,
28    BadRequest,
29    Server,
30    Network,
31    Stalled,
32    Decode,
33    Host,
34}
35
36/// A failed provider call: its kind, a human-readable message and an
37/// optional server-sent retry delay in milliseconds.
38/// Displays as `Kind: message`.
39#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, thiserror::Error)]
40#[error("{kind:?}: {message}")]
41pub struct ProviderError {
42    pub kind: ProviderErrorKind,
43    pub message: String,
44    pub retry_after_ms: Option<u64>,
45}
46
47impl ProviderError {
48    /// Builds an error of `kind` with a human-readable `message`.
49    /// The retry delay starts empty; add one with `with_retry_after`.
50    /// Returns the new error.
51    pub fn new(kind: ProviderErrorKind, message: impl Into<String>) -> Self {
52        Self { kind, message: message.into(), retry_after_ms: None }
53    }
54
55    /// Sets the retry delay to `ms` milliseconds, as sent by the provider.
56    /// Consumes the error and returns it with the delay set,
57    /// so it chains after `new`.
58    pub fn with_retry_after(mut self, ms: u64) -> Self {
59        self.retry_after_ms = Some(ms);
60        self
61    }
62
63    /// Reports whether the failure is transient.
64    /// True for rate limits, server errors, network errors and stalls;
65    /// false for auth, bad request and decode errors.
66    pub fn is_retryable(&self) -> bool {
67        matches!(
68            self.kind,
69            ProviderErrorKind::RateLimited | ProviderErrorKind::Server | ProviderErrorKind::Network | ProviderErrorKind::Stalled
70        )
71    }
72}
73
74#[cfg(test)]
75mod tests {
76    use super::*;
77
78    #[test]
79    fn retryable_kinds() {
80        for k in [ProviderErrorKind::RateLimited, ProviderErrorKind::Server, ProviderErrorKind::Network, ProviderErrorKind::Stalled] {
81            assert!(ProviderError::new(k, "x").is_retryable());
82        }
83        for k in [ProviderErrorKind::Auth, ProviderErrorKind::BadRequest, ProviderErrorKind::Decode, ProviderErrorKind::Host] {
84            assert!(!ProviderError::new(k, "x").is_retryable());
85        }
86    }
87
88    #[test]
89    fn carries_retry_after() {
90        let e = ProviderError::new(ProviderErrorKind::RateLimited, "slow down").with_retry_after(1500);
91        assert_eq!(e.retry_after_ms, Some(1500));
92        assert_eq!(e.to_string(), "RateLimited: slow down");
93    }
94}