Skip to main content

grow_graylog/core/
error.rs

1// Generated by sdk-kit 0.3.0 — do not edit; change sdk-kit and run "sdk-kit sync"
2//! Error type shared by every module of the SDK (SPEC §2.1).
3
4use std::fmt;
5use std::str::FromStr;
6use std::sync::Arc;
7use std::time::Duration;
8
9/// Result alias used by every fallible SDK function.
10pub type Result<T> = std::result::Result<T, Error>;
11
12/// Canonical error codes. The wire value (`as_str`) is the same in every language.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
14#[non_exhaustive]
15pub enum ErrorCode {
16    /// Invalid or missing configuration.
17    Config,
18    /// Bad credentials (HTTP 401).
19    Authentication,
20    /// Credentials lack permission (HTTP 403).
21    PermissionDenied,
22    /// Missing resource (HTTP 404).
23    NotFound,
24    /// Conflict or failed precondition (HTTP 409, 412, CAS mismatch).
25    Conflict,
26    /// Throttled (HTTP 429).
27    RateLimited,
28    /// Rejected input (HTTP 400, 413, 422, other 4xx, client-side validation).
29    Validation,
30    /// Network failure or server error (HTTP 500, 502, 503).
31    Unavailable,
32    /// A deadline was exceeded (HTTP 408, 504).
33    Timeout,
34    /// The service or deployment does not offer the capability (HTTP 501).
35    Unsupported,
36    /// The caller cancelled the operation.
37    Cancelled,
38}
39
40impl ErrorCode {
41    /// Every code, in declaration order.
42    pub const ALL: [ErrorCode; 11] = [
43        ErrorCode::Config,
44        ErrorCode::Authentication,
45        ErrorCode::PermissionDenied,
46        ErrorCode::NotFound,
47        ErrorCode::Conflict,
48        ErrorCode::RateLimited,
49        ErrorCode::Validation,
50        ErrorCode::Unavailable,
51        ErrorCode::Timeout,
52        ErrorCode::Unsupported,
53        ErrorCode::Cancelled,
54    ];
55
56    /// Wire value, e.g. `"NOT_FOUND"`.
57    pub fn as_str(self) -> &'static str {
58        match self {
59            ErrorCode::Config => "CONFIG",
60            ErrorCode::Authentication => "AUTHENTICATION",
61            ErrorCode::PermissionDenied => "PERMISSION_DENIED",
62            ErrorCode::NotFound => "NOT_FOUND",
63            ErrorCode::Conflict => "CONFLICT",
64            ErrorCode::RateLimited => "RATE_LIMITED",
65            ErrorCode::Validation => "VALIDATION",
66            ErrorCode::Unavailable => "UNAVAILABLE",
67            ErrorCode::Timeout => "TIMEOUT",
68            ErrorCode::Unsupported => "UNSUPPORTED",
69            ErrorCode::Cancelled => "CANCELLED",
70        }
71    }
72
73    /// Whether errors with this code are retryable by default.
74    pub fn default_retryable(self) -> bool {
75        matches!(
76            self,
77            ErrorCode::RateLimited | ErrorCode::Unavailable | ErrorCode::Timeout
78        )
79    }
80
81    /// Short human reason used in error messages, e.g. `"not found"`.
82    pub fn reason(self) -> &'static str {
83        match self {
84            ErrorCode::Config => "invalid configuration",
85            ErrorCode::Authentication => "authentication failed",
86            ErrorCode::PermissionDenied => "permission denied",
87            ErrorCode::NotFound => "not found",
88            ErrorCode::Conflict => "conflict",
89            ErrorCode::RateLimited => "rate limited",
90            ErrorCode::Validation => "invalid request",
91            ErrorCode::Unavailable => "service unavailable",
92            ErrorCode::Timeout => "timed out",
93            ErrorCode::Unsupported => "not supported",
94            ErrorCode::Cancelled => "cancelled",
95        }
96    }
97
98    /// Code for an HTTP status according to SPEC §2.1 (`None` for 1xx–3xx).
99    pub fn from_http_status(status: u16) -> Option<ErrorCode> {
100        Some(match status {
101            401 => ErrorCode::Authentication,
102            403 => ErrorCode::PermissionDenied,
103            404 => ErrorCode::NotFound,
104            409 | 412 => ErrorCode::Conflict,
105            429 => ErrorCode::RateLimited,
106            408 | 504 => ErrorCode::Timeout,
107            501 => ErrorCode::Unsupported,
108            400..=499 => ErrorCode::Validation,
109            500..=599 => ErrorCode::Unavailable,
110            _ => return None,
111        })
112    }
113}
114
115impl fmt::Display for ErrorCode {
116    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117        f.write_str(self.as_str())
118    }
119}
120
121impl FromStr for ErrorCode {
122    type Err = Error;
123
124    fn from_str(s: &str) -> Result<Self> {
125        ErrorCode::ALL
126            .into_iter()
127            .find(|c| c.as_str() == s)
128            .ok_or_else(|| Error::validation(format!("unknown error code {s:?}")))
129    }
130}
131
132/// Details carried by every [`Error`] variant.
133#[derive(Clone)]
134pub struct ErrorContext {
135    message: String,
136    http_status: Option<u16>,
137    request_id: Option<String>,
138    retryable: bool,
139    retry_after: Option<Duration>,
140    source: Option<Arc<dyn std::error::Error + Send + Sync + 'static>>,
141}
142
143impl fmt::Debug for ErrorContext {
144    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145        f.debug_struct("ErrorContext")
146            .field("message", &self.message)
147            .field("http_status", &self.http_status)
148            .field("request_id", &self.request_id)
149            .field("retryable", &self.retryable)
150            .field("retry_after", &self.retry_after)
151            .field("source", &self.source.as_ref().map(|s| s.to_string()))
152            .finish()
153    }
154}
155
156/// The SDK error. Match on the variant or use [`Error::code`].
157///
158/// Messages never contain secrets, tokens, request bodies or unfiltered response bodies.
159#[derive(Debug, Clone)]
160#[non_exhaustive]
161pub enum Error {
162    /// `CONFIG`: invalid or missing configuration.
163    Config(Box<ErrorContext>),
164    /// `AUTHENTICATION`: HTTP 401.
165    Authentication(Box<ErrorContext>),
166    /// `PERMISSION_DENIED`: HTTP 403.
167    PermissionDenied(Box<ErrorContext>),
168    /// `NOT_FOUND`: HTTP 404 or a missing record.
169    NotFound(Box<ErrorContext>),
170    /// `CONFLICT`: HTTP 409, 412 or a CAS mismatch.
171    Conflict(Box<ErrorContext>),
172    /// `RATE_LIMITED`: HTTP 429 (see [`Error::retry_after`]).
173    RateLimited(Box<ErrorContext>),
174    /// `VALIDATION`: rejected input.
175    Validation(Box<ErrorContext>),
176    /// `UNAVAILABLE`: network error or HTTP 500/502/503.
177    Unavailable(Box<ErrorContext>),
178    /// `TIMEOUT`: a deadline was exceeded.
179    Timeout(Box<ErrorContext>),
180    /// `UNSUPPORTED`: capability not offered by the service.
181    Unsupported(Box<ErrorContext>),
182    /// `CANCELLED`: the caller cancelled.
183    Cancelled(Box<ErrorContext>),
184}
185
186impl Error {
187    /// Creates an error with the given code; `retryable` defaults per code.
188    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
189        let ctx = Box::new(ErrorContext {
190            message: message.into(),
191            http_status: None,
192            request_id: None,
193            retryable: code.default_retryable(),
194            retry_after: None,
195            source: None,
196        });
197        match code {
198            ErrorCode::Config => Error::Config(ctx),
199            ErrorCode::Authentication => Error::Authentication(ctx),
200            ErrorCode::PermissionDenied => Error::PermissionDenied(ctx),
201            ErrorCode::NotFound => Error::NotFound(ctx),
202            ErrorCode::Conflict => Error::Conflict(ctx),
203            ErrorCode::RateLimited => Error::RateLimited(ctx),
204            ErrorCode::Validation => Error::Validation(ctx),
205            ErrorCode::Unavailable => Error::Unavailable(ctx),
206            ErrorCode::Timeout => Error::Timeout(ctx),
207            ErrorCode::Unsupported => Error::Unsupported(ctx),
208            ErrorCode::Cancelled => Error::Cancelled(ctx),
209        }
210    }
211
212    /// Error for an HTTP status (SPEC §2.1 mapping); non-error statuses map to `UNAVAILABLE`.
213    pub fn from_status(status: u16, message: impl Into<String>) -> Self {
214        let code = ErrorCode::from_http_status(status).unwrap_or(ErrorCode::Unavailable);
215        Error::new(code, message).with_status(status)
216    }
217
218    /// `CONFIG` error.
219    pub fn config(message: impl Into<String>) -> Self {
220        Error::new(ErrorCode::Config, message)
221    }
222    /// `VALIDATION` error.
223    pub fn validation(message: impl Into<String>) -> Self {
224        Error::new(ErrorCode::Validation, message)
225    }
226    /// `NOT_FOUND` error.
227    pub fn not_found(message: impl Into<String>) -> Self {
228        Error::new(ErrorCode::NotFound, message)
229    }
230    /// `CONFLICT` error.
231    pub fn conflict(message: impl Into<String>) -> Self {
232        Error::new(ErrorCode::Conflict, message)
233    }
234    /// `TIMEOUT` error.
235    pub fn timeout(message: impl Into<String>) -> Self {
236        Error::new(ErrorCode::Timeout, message)
237    }
238    /// `UNAVAILABLE` error.
239    pub fn unavailable(message: impl Into<String>) -> Self {
240        Error::new(ErrorCode::Unavailable, message)
241    }
242    /// `UNSUPPORTED` error.
243    pub fn unsupported(message: impl Into<String>) -> Self {
244        Error::new(ErrorCode::Unsupported, message)
245    }
246    /// `CANCELLED` error.
247    pub fn cancelled(message: impl Into<String>) -> Self {
248        Error::new(ErrorCode::Cancelled, message)
249    }
250
251    fn ctx(&self) -> &ErrorContext {
252        match self {
253            Error::Config(c)
254            | Error::Authentication(c)
255            | Error::PermissionDenied(c)
256            | Error::NotFound(c)
257            | Error::Conflict(c)
258            | Error::RateLimited(c)
259            | Error::Validation(c)
260            | Error::Unavailable(c)
261            | Error::Timeout(c)
262            | Error::Unsupported(c)
263            | Error::Cancelled(c) => c,
264        }
265    }
266
267    fn ctx_mut(&mut self) -> &mut ErrorContext {
268        match self {
269            Error::Config(c)
270            | Error::Authentication(c)
271            | Error::PermissionDenied(c)
272            | Error::NotFound(c)
273            | Error::Conflict(c)
274            | Error::RateLimited(c)
275            | Error::Validation(c)
276            | Error::Unavailable(c)
277            | Error::Timeout(c)
278            | Error::Unsupported(c)
279            | Error::Cancelled(c) => c,
280        }
281    }
282
283    /// Sets the HTTP status.
284    pub fn with_status(mut self, status: u16) -> Self {
285        self.ctx_mut().http_status = Some(status);
286        self
287    }
288    /// Sets the vendor request id.
289    pub fn with_request_id(mut self, request_id: impl Into<String>) -> Self {
290        self.ctx_mut().request_id = Some(request_id.into());
291        self
292    }
293    /// Overrides whether the error is retryable.
294    pub fn with_retryable(mut self, retryable: bool) -> Self {
295        self.ctx_mut().retryable = retryable;
296        self
297    }
298    /// Sets the server-requested wait before a retry.
299    pub fn with_retry_after(mut self, retry_after: Duration) -> Self {
300        self.ctx_mut().retry_after = Some(retry_after);
301        self
302    }
303    /// Sets the underlying cause (it must not expose secrets).
304    pub fn with_source(mut self, source: impl std::error::Error + Send + Sync + 'static) -> Self {
305        self.ctx_mut().source = Some(Arc::new(source));
306        self
307    }
308    /// Replaces the message.
309    pub fn with_message(mut self, message: impl Into<String>) -> Self {
310        self.ctx_mut().message = message.into();
311        self
312    }
313
314    /// Canonical code.
315    pub fn code(&self) -> ErrorCode {
316        match self {
317            Error::Config(_) => ErrorCode::Config,
318            Error::Authentication(_) => ErrorCode::Authentication,
319            Error::PermissionDenied(_) => ErrorCode::PermissionDenied,
320            Error::NotFound(_) => ErrorCode::NotFound,
321            Error::Conflict(_) => ErrorCode::Conflict,
322            Error::RateLimited(_) => ErrorCode::RateLimited,
323            Error::Validation(_) => ErrorCode::Validation,
324            Error::Unavailable(_) => ErrorCode::Unavailable,
325            Error::Timeout(_) => ErrorCode::Timeout,
326            Error::Unsupported(_) => ErrorCode::Unsupported,
327            Error::Cancelled(_) => ErrorCode::Cancelled,
328        }
329    }
330    /// Human-readable message (redacted).
331    pub fn message(&self) -> &str {
332        &self.ctx().message
333    }
334    /// HTTP status when the error came from a response.
335    pub fn http_status(&self) -> Option<u16> {
336        self.ctx().http_status
337    }
338    /// Vendor request id when the response carried one.
339    pub fn request_id(&self) -> Option<&str> {
340        self.ctx().request_id.as_deref()
341    }
342    /// Whether retrying the same call may succeed.
343    pub fn is_retryable(&self) -> bool {
344        self.ctx().retryable
345    }
346    /// Server-requested wait (`Retry-After`) when known.
347    pub fn retry_after(&self) -> Option<Duration> {
348        self.ctx().retry_after
349    }
350    /// Whether this error has the given code.
351    pub fn is(&self, code: ErrorCode) -> bool {
352        self.code() == code
353    }
354    /// The underlying cause, when any.
355    pub fn cause(&self) -> Option<&(dyn std::error::Error + Send + Sync + 'static)> {
356        self.ctx().source.as_deref()
357    }
358}
359
360impl fmt::Display for Error {
361    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
362        f.write_str(&self.ctx().message)
363    }
364}
365
366impl std::error::Error for Error {
367    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
368        self.ctx()
369            .source
370            .as_deref()
371            .map(|s| s as &(dyn std::error::Error + 'static))
372    }
373}
374
375impl From<serde_json::Error> for Error {
376    fn from(err: serde_json::Error) -> Self {
377        Error::validation(format!("invalid JSON: {}", err.classify_name())).with_source(err)
378    }
379}
380
381/// Small helper so `serde_json::Error` can describe itself without echoing input.
382trait ClassifyName {
383    fn classify_name(&self) -> &'static str;
384}
385
386impl ClassifyName for serde_json::Error {
387    fn classify_name(&self) -> &'static str {
388        match self.classify() {
389            serde_json::error::Category::Io => "I/O error",
390            serde_json::error::Category::Syntax => "syntax error",
391            serde_json::error::Category::Data => "unexpected data",
392            serde_json::error::Category::Eof => "unexpected end of input",
393        }
394    }
395}