Skip to main content

xmtp_proto/traits/
error.rs

1use std::fmt::Display;
2
3use crate::{ApiEndpoint, ProtoError};
4use thiserror::Error;
5use xmtp_common::{BoxDynError, ErrorCode, RetryableError, retryable};
6
7/// Authentication failures with no credential or callback error text.
8// implements: AUTH-026
9#[derive(Clone, Copy, Debug, Error, ErrorCode)]
10pub enum AuthError {
11    /// The backend rejected the credential. Retryable if a callback can run.
12    #[error("credential rejected")]
13    CredentialRejected { retryable: bool },
14    /// The callback failed. Retryable if a callback can run.
15    #[error("auth callback failed")]
16    CallbackFailed { retryable: bool },
17    /// Authentication is locked until the cool-down ends. Not retryable.
18    #[error("auth attempts exhausted")]
19    Exhausted,
20    /// This attempt reached the limit and started the cool-down. Not retryable.
21    /// The public code stays the same as a later cool-down refusal.
22    #[error("auth attempts exhausted")]
23    #[error_code("AuthError::Exhausted")]
24    ExhaustedAfterAttempt,
25    /// No credential was set on the handle. Not retryable.
26    #[error("auth credential missing")]
27    MissingCredential,
28}
29
30impl RetryableError for AuthError {
31    fn is_retryable(&self) -> bool {
32        match self {
33            Self::CredentialRejected { retryable } | Self::CallbackFailed { retryable } => {
34                *retryable
35            }
36            Self::Exhausted | Self::ExhaustedAfterAttempt | Self::MissingCredential => false,
37        }
38    }
39}
40
41impl AuthError {
42    /// True while the lockout cool-down runs. The error is not retryable now,
43    /// but it clears when the cool-down ends, so a long-lived transport must
44    /// wait instead of shutting down. Every other variant needs the caller or
45    /// the application to act, so none of them clears on its own.
46    pub fn is_locked_out(&self) -> bool {
47        matches!(self, Self::Exhausted | Self::ExhaustedAfterAttempt)
48    }
49}
50
51impl ApiClientError {
52    /// True while an authentication cool-down runs. `#[error(transparent)]`
53    /// forwards Display but not `source()`, so the inner `AuthError` cannot be
54    /// reached by walking the chain. Match the variant instead.
55    pub fn is_locked_out(&self) -> bool {
56        matches!(self, Self::Auth(auth) if auth.is_locked_out())
57    }
58}
59
60#[derive(Debug, Error, ErrorCode)]
61#[non_exhaustive]
62pub enum ApiClientError {
63    #[error(transparent)]
64    #[error_code(inherit)]
65    Auth(#[from] AuthError),
66    /// The client encountered an error.
67    #[error("api client at endpoint \"{}\" has error {}", endpoint, source)]
68    ClientWithEndpoint {
69        endpoint: String,
70        /// The client error.
71        source: NetworkError,
72    },
73    /// The transport failed. Retryability follows the source.
74    #[error("client errored {}", source)]
75    Client { source: NetworkError },
76    /// The HTTP request is invalid. Not retryable.
77    #[error(transparent)]
78    Http(#[from] http::Error),
79    /// The request body is invalid. Not retryable.
80    #[error(transparent)]
81    Body(#[from] BodyError),
82    /// The response cannot be decoded. Not retryable.
83    #[error(transparent)]
84    DecodeError(#[from] prost::DecodeError),
85    /// A protocol conversion failed. Not retryable.
86    #[error(transparent)]
87    Conversion(#[from] crate::ConversionError),
88    /// A protocol operation failed. Not retryable.
89    #[error(transparent)]
90    ProtoError(#[from] ProtoError),
91    /// The URI is invalid. Not retryable.
92    #[error(transparent)]
93    InvalidUri(#[from] http::uri::InvalidUri),
94    /// The request expired. Retryable.
95    #[error(transparent)]
96    Expired(#[from] xmtp_common::time::Expired),
97    /// A client operation failed. Retryability follows the source.
98    #[error("{0}")]
99    Other(Box<dyn RetryableError>),
100    /// A client operation failed. Not retryable.
101    #[error("{0}")]
102    OtherUnretryable(BoxDynError),
103    /// Writes are disabled. Not retryable.
104    #[error("Writes are disabled on this client.")]
105    WritesDisabled,
106}
107
108/// A lower level NetworkError, like gRPC/QUIC/HTTP/1.1 errors go here.
109/// use [`ApiClientError::new`] to construct
110// needed because of AsDynError sealed trait
111#[derive(Debug)]
112pub struct NetworkError {
113    source: Box<dyn RetryableError>,
114}
115
116impl std::error::Error for NetworkError {
117    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
118        Some(self.source.as_ref())
119    }
120}
121
122impl Display for NetworkError {
123    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
124        write!(f, "{}", self.source)
125    }
126}
127
128impl RetryableError for NetworkError {
129    fn is_retryable(&self) -> bool {
130        self.source.is_retryable()
131    }
132}
133
134impl NetworkError {
135    pub fn new(e: impl RetryableError + 'static) -> Self {
136        NetworkError {
137            source: Box::new(e),
138        }
139    }
140}
141
142impl ApiClientError {
143    pub fn new(endpoint: ApiEndpoint, source: impl RetryableError + 'static) -> Self {
144        Self::ClientWithEndpoint {
145            endpoint: endpoint.to_string(),
146            source: NetworkError::new(source),
147        }
148    }
149
150    /// add an endpoint to a ApiError::Client error
151    pub fn endpoint(self, endpoint: impl ToString) -> Self {
152        match self {
153            Self::Client { source } => Self::ClientWithEndpoint {
154                source,
155                endpoint: endpoint.to_string(),
156            },
157            v => v,
158        }
159    }
160
161    pub fn client(client: impl RetryableError + 'static) -> Self {
162        Self::Client {
163            source: NetworkError::new(client),
164        }
165    }
166
167    /// Try to pull a [`NetworkError`] out of this error enum.
168    /// returns None if there's no match
169    pub fn network_error(&self) -> Option<&NetworkError> {
170        use ApiClientError::*;
171        match self {
172            ClientWithEndpoint { source, .. } | Client { source, .. } => Some(source),
173            _ => None,
174        }
175    }
176}
177
178impl ApiClientError {
179    pub fn other<R: RetryableError + 'static>(e: R) -> Self {
180        ApiClientError::Other(Box::new(e))
181    }
182}
183
184impl RetryableError for ApiClientError {
185    fn is_retryable(&self) -> bool {
186        use ApiClientError::*;
187        match self {
188            Client { source } => retryable!(*source),
189            ClientWithEndpoint { source, .. } => retryable!(source),
190            Auth(e) => retryable!(e),
191            Body(e) => retryable!(e),
192            Http(_) => false,
193            DecodeError(_) => false,
194            Conversion(_) => false,
195            ProtoError(_) => false,
196            InvalidUri(_) => false,
197            Expired(_) => true,
198            Other(r) => retryable!(r),
199            OtherUnretryable(_) => false,
200            WritesDisabled => false,
201        }
202    }
203}
204
205// Infallible errors by definition can never occur
206impl From<std::convert::Infallible> for ApiClientError {
207    fn from(_v: std::convert::Infallible) -> ApiClientError {
208        unreachable!("Infallible errors can never occur")
209    }
210}
211
212#[derive(Debug, Error)]
213pub enum BodyError {
214    #[error(transparent)]
215    UninitializedField(#[from] derive_builder::UninitializedFieldError),
216    #[error(transparent)]
217    Conversion(#[from] crate::ConversionError),
218}
219
220impl RetryableError for BodyError {
221    fn is_retryable(&self) -> bool {
222        false
223    }
224}
225
226/// Find a typed gRPC status through transport and wrapper error sources.
227pub fn grpc_status<'a>(
228    mut error: &'a (dyn std::error::Error + 'static),
229) -> Option<&'a tonic::Status> {
230    loop {
231        if let Some(status) = error.downcast_ref::<tonic::Status>() {
232            return Some(status);
233        }
234        error = match error.downcast_ref::<ApiClientError>() {
235            Some(ApiClientError::Other(inner)) => inner.as_ref(),
236            Some(ApiClientError::OtherUnretryable(inner)) => inner.as_ref(),
237            _ => error.source()?,
238        };
239    }
240}