Skip to main content

trusted_router/
error.rs

1//! Typed SDK errors.
2
3use serde_json::Value;
4use std::time::Duration;
5
6/// SDK result type.
7pub type Result<T> = std::result::Result<T, Error>;
8
9/// HTTP/API error classification.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum ErrorKind {
12    /// Invalid request or another 4xx response.
13    BadRequest,
14    /// Invalid or missing API key.
15    Authentication,
16    /// Authenticated but unauthorized.
17    PermissionDenied,
18    /// Missing route or object.
19    NotFound,
20    /// Rate limit response.
21    RateLimit,
22    /// Endpoint deliberately unsupported.
23    EndpointNotSupported,
24    /// `TrustedRouter` or upstream 5xx response.
25    Internal,
26    /// Non-HTTP transport failure.
27    Transport,
28    /// SDK deadline or stream idle deadline.
29    Timeout,
30    /// JSON encoding or decoding failure.
31    Serialization,
32    /// Invalid local SDK configuration.
33    InvalidConfiguration,
34    /// Attestation verification failure.
35    Attestation,
36    /// OAuth flow failure.
37    OAuth,
38}
39
40/// Structured API failure preserving routing/provider attribution.
41#[derive(Debug, Clone)]
42pub struct ApiError {
43    /// HTTP response status.
44    pub status_code: u16,
45    /// Human-readable message.
46    pub message: String,
47    /// Full parsed response when it was JSON.
48    pub payload: Option<Value>,
49    /// Numeric Retry-After value.
50    pub retry_after: Option<Duration>,
51    /// Error layer reported by the API, such as `routing` or `provider`.
52    pub layer: Option<String>,
53    /// Error source reported by the API.
54    pub source: Option<String>,
55    /// Provider identifier when reported.
56    pub provider: Option<String>,
57    /// Request identifier when reported.
58    pub request_id: Option<String>,
59}
60
61impl std::fmt::Display for ApiError {
62    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        write!(formatter, "{}", self.message)
64    }
65}
66
67impl std::error::Error for ApiError {}
68
69/// Error returned by the SDK.
70#[derive(Debug, thiserror::Error)]
71pub enum Error {
72    /// HTTP/API response failure.
73    #[error("{kind:?}: {error}")]
74    Api {
75        /// Classified error kind.
76        kind: ErrorKind,
77        /// Structured API details.
78        error: Box<ApiError>,
79    },
80    /// HTTP transport failure.
81    #[error("TrustedRouter endpoint unavailable: {0}")]
82    Transport(String),
83    /// SDK or stream timeout.
84    #[error("TrustedRouter request timed out: {0}")]
85    Timeout(String),
86    /// JSON encoding or decoding failure.
87    #[error("TrustedRouter JSON error: {0}")]
88    Serialization(String),
89    /// Invalid SDK configuration or request path.
90    #[error("Invalid TrustedRouter configuration: {0}")]
91    InvalidConfiguration(String),
92    /// Attestation verification failure.
93    #[error("TrustedRouter attestation verification failed: {0}")]
94    Attestation(String),
95    /// OAuth helper failure.
96    #[error("TrustedRouter OAuth error: {0}")]
97    OAuth(String),
98}
99
100impl Error {
101    /// Returns the stable error classification.
102    pub fn kind(&self) -> ErrorKind {
103        match self {
104            Self::Api { kind, .. } => *kind,
105            Self::Transport(_) => ErrorKind::Transport,
106            Self::Timeout(_) => ErrorKind::Timeout,
107            Self::Serialization(_) => ErrorKind::Serialization,
108            Self::InvalidConfiguration(_) => ErrorKind::InvalidConfiguration,
109            Self::Attestation(_) => ErrorKind::Attestation,
110            Self::OAuth(_) => ErrorKind::OAuth,
111        }
112    }
113
114    /// Returns the HTTP status when this came from an API response.
115    pub fn status_code(&self) -> Option<u16> {
116        match self {
117            Self::Api { error, .. } => Some(error.status_code),
118            _ => None,
119        }
120    }
121
122    /// Returns structured API details when available.
123    pub fn api_error(&self) -> Option<&ApiError> {
124        match self {
125            Self::Api { error, .. } => Some(error.as_ref()),
126            _ => None,
127        }
128    }
129}
130
131pub(crate) fn classify_api_error(
132    status_code: u16,
133    payload: Option<Value>,
134    retry_after: Option<Duration>,
135) -> Error {
136    let message = payload
137        .as_ref()
138        .and_then(error_object)
139        .and_then(|error| error.get("message"))
140        .and_then(Value::as_str)
141        .or_else(|| {
142            payload
143                .as_ref()
144                .and_then(|value| value.get("message"))
145                .and_then(Value::as_str)
146        })
147        .unwrap_or("TrustedRouter error")
148        .to_owned();
149    let string_field = |name: &str| -> Option<String> {
150        payload
151            .as_ref()
152            .and_then(error_object)
153            .and_then(|value| value.get(name))
154            .or_else(|| payload.as_ref().and_then(|value| value.get(name)))
155            .and_then(Value::as_str)
156            .map(str::to_owned)
157    };
158    let layer = string_field("layer");
159    let source = string_field("source");
160    let provider = string_field("provider");
161    let request_id = string_field("request_id");
162    let kind = match status_code {
163        401 => ErrorKind::Authentication,
164        403 => ErrorKind::PermissionDenied,
165        404 => ErrorKind::NotFound,
166        429 => ErrorKind::RateLimit,
167        501 => ErrorKind::EndpointNotSupported,
168        400..=499 => ErrorKind::BadRequest,
169        _ => ErrorKind::Internal,
170    };
171    Error::Api {
172        kind,
173        error: Box::new(ApiError {
174            status_code,
175            message,
176            payload,
177            retry_after,
178            layer,
179            source,
180            provider,
181            request_id,
182        }),
183    }
184}
185
186fn error_object(payload: &Value) -> Option<&serde_json::Map<String, Value>> {
187    payload.get("error")?.as_object()
188}