Skip to main content

graphrt_provider_api/
error.rs

1//! Provider and deploy errors, classified so the gateway can react without
2//! parsing messages (plan §6, conformance C9).
3
4use std::fmt;
5use std::time::Duration;
6
7/// What kind of failure a provider call hit.
8///
9/// `#[non_exhaustive]`: match with a wildcard arm, new kinds may be added.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11#[non_exhaustive]
12pub enum ProviderErrorKind {
13    /// No capacity (quota, region full, Fargate capacity). The gateway falls
14    /// back: another replica / region, or `stop` → cold start.
15    Capacity,
16    /// HTTP 429 or a provider throttling code. Retried with jittered backoff.
17    RateLimited,
18    /// 401/403 after the one refresh. Not retried.
19    Auth,
20    /// The resource does not exist (deleted out of band).
21    NotFound,
22    /// Network error, timeout, 5xx, 409 conflict. Retried with backoff.
23    Transient,
24    /// Anything else (bad request, invalid config). Not retried.
25    Fatal,
26    /// The platform cut the request at its hard time limit and no preemption
27    /// was possible (Lambda, `max_grace_secs = 0`). Not retried: the gateway
28    /// records the run as `failed{error_type: platform_timeout}`.
29    PlatformTimeout,
30}
31
32impl ProviderErrorKind {
33    /// Whether the shared retry loop retries this kind.
34    pub fn is_retryable(self) -> bool {
35        matches!(self, Self::RateLimited | Self::Transient)
36    }
37
38    /// Stable lowercase name for logs and metrics labels.
39    pub fn as_str(self) -> &'static str {
40        match self {
41            Self::Capacity => "capacity",
42            Self::RateLimited => "rate_limited",
43            Self::Auth => "auth",
44            Self::NotFound => "not_found",
45            Self::Transient => "transient",
46            Self::Fatal => "fatal",
47            Self::PlatformTimeout => "platform_timeout",
48        }
49    }
50}
51
52impl fmt::Display for ProviderErrorKind {
53    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
54        formatter.write_str(self.as_str())
55    }
56}
57
58/// A failed run-time provider call. The message never contains credentials:
59/// response bodies are truncated and headers are never included.
60#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
61#[error("{kind}: {message}")]
62pub struct ProviderError {
63    /// Classification.
64    pub kind: ProviderErrorKind,
65    /// Human-readable detail.
66    pub message: String,
67    /// Server-provided `Retry-After`, honoured by the retry loop.
68    pub retry_after: Option<Duration>,
69}
70
71impl ProviderError {
72    /// Builds an error of `kind`.
73    pub fn new(kind: ProviderErrorKind, message: impl Into<String>) -> Self {
74        Self { kind, message: message.into(), retry_after: None }
75    }
76
77    /// Attaches a `Retry-After` hint.
78    pub fn with_retry_after(mut self, retry_after: Option<Duration>) -> Self {
79        self.retry_after = retry_after;
80        self
81    }
82
83    /// Shorthand constructors.
84    pub fn capacity(message: impl Into<String>) -> Self {
85        Self::new(ProviderErrorKind::Capacity, message)
86    }
87    /// See [`ProviderErrorKind::RateLimited`].
88    pub fn rate_limited(message: impl Into<String>) -> Self {
89        Self::new(ProviderErrorKind::RateLimited, message)
90    }
91    /// See [`ProviderErrorKind::Auth`].
92    pub fn auth(message: impl Into<String>) -> Self {
93        Self::new(ProviderErrorKind::Auth, message)
94    }
95    /// See [`ProviderErrorKind::NotFound`].
96    pub fn not_found(message: impl Into<String>) -> Self {
97        Self::new(ProviderErrorKind::NotFound, message)
98    }
99    /// See [`ProviderErrorKind::Transient`].
100    pub fn transient(message: impl Into<String>) -> Self {
101        Self::new(ProviderErrorKind::Transient, message)
102    }
103    /// See [`ProviderErrorKind::Fatal`].
104    pub fn fatal(message: impl Into<String>) -> Self {
105        Self::new(ProviderErrorKind::Fatal, message)
106    }
107    /// See [`ProviderErrorKind::PlatformTimeout`].
108    pub fn platform_timeout(message: impl Into<String>) -> Self {
109        Self::new(ProviderErrorKind::PlatformTimeout, message)
110    }
111
112    /// Classifies an HTTP status of a provider API. Providers refine the
113    /// result with their own error codes (e.g. a 403 `RESOURCE_EXHAUSTED` is
114    /// `Capacity`).
115    pub fn kind_for_status(status: u16) -> ProviderErrorKind {
116        match status {
117            401 | 403 => ProviderErrorKind::Auth,
118            404 | 410 => ProviderErrorKind::NotFound,
119            429 => ProviderErrorKind::RateLimited,
120            408 | 409 | 425 | 500..=599 => ProviderErrorKind::Transient,
121            _ => ProviderErrorKind::Fatal,
122        }
123    }
124}
125
126/// What kind of failure `DeployDriver::apply` hit.
127#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
128pub enum DeployErrorKind {
129    /// The spec is invalid for this target (e.g. async runs on Lambda).
130    Invalid,
131    /// The target does not support a requested feature.
132    Unsupported,
133    /// The provider API failed.
134    Provider(ProviderErrorKind),
135}
136
137/// A failed deploy.
138#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
139#[error("deploy failed ({kind:?}): {message}")]
140pub struct DeployError {
141    /// Classification.
142    pub kind: DeployErrorKind,
143    /// Human-readable detail.
144    pub message: String,
145}
146
147impl DeployError {
148    /// An invalid spec.
149    pub fn invalid(message: impl Into<String>) -> Self {
150        Self { kind: DeployErrorKind::Invalid, message: message.into() }
151    }
152    /// An unsupported feature.
153    pub fn unsupported(message: impl Into<String>) -> Self {
154        Self { kind: DeployErrorKind::Unsupported, message: message.into() }
155    }
156}
157
158impl From<ProviderError> for DeployError {
159    fn from(error: ProviderError) -> Self {
160        Self { kind: DeployErrorKind::Provider(error.kind), message: error.message }
161    }
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167
168    #[test]
169    fn platform_timeout_is_its_own_non_retryable_kind() {
170        let error = ProviderError::platform_timeout("Lambda cut the run after 840 s");
171        assert_eq!(error.kind, ProviderErrorKind::PlatformTimeout);
172        assert!(!error.kind.is_retryable());
173        assert_eq!(error.kind.as_str(), "platform_timeout");
174        assert_eq!(error.to_string(), "platform_timeout: Lambda cut the run after 840 s");
175        assert_eq!(DeployError::from(error).kind, DeployErrorKind::Provider(ProviderErrorKind::PlatformTimeout));
176    }
177}