Skip to main content

xmtp_mls/client/
error.rs

1//! Client errors: the client error type, its conversions and retry classification, and
2//! the stream failure details.
3
4use super::*;
5
6#[derive(Debug, Error, ErrorCode)]
7pub enum ClientError {
8    #[error(transparent)]
9    #[error_code(inherit)]
10    AddressValidation(#[from] IdentifierValidationError),
11    /// Could not publish.
12    ///
13    /// Failed to publish messages to the network. May be retryable.
14    #[error("could not publish: {0}")]
15    PublishError(String),
16    /// Storage error.
17    ///
18    /// Database operation failed. May be retryable.
19    #[error("storage error: {0}")]
20    Storage(#[from] StorageError),
21    /// API error.
22    ///
23    /// Network request to XMTP backend failed. Retryable.
24    #[error("API error: {0}")]
25    Api(#[from] xmtp_api::ApiError),
26    /// Identity error.
27    ///
28    /// Problem with identity operations. Not retryable.
29    #[error("identity error: {0}")]
30    Identity(#[from] crate::identity::IdentityError),
31    /// TLS Codec error.
32    ///
33    /// Encoding/decoding MLS TLS structures failed. Not retryable.
34    #[error("TLS Codec error: {0}")]
35    TlsError(#[from] TlsCodecError),
36    /// Key package verification failed.
37    ///
38    /// Invalid key package received from network. Not retryable.
39    #[error("key package verification: {0}")]
40    KeyPackageVerification(#[from] KeyPackageVerificationError),
41    /// Stream inconsistency.
42    ///
43    /// Message stream state became inconsistent. Not retryable.
44    #[error("Stream inconsistency error: {0}")]
45    StreamInconsistency(String),
46    /// Association error.
47    ///
48    /// Identity association operation failed. Not retryable.
49    #[error("Association error: {0}")]
50    Association(#[from] AssociationError),
51    /// Signature validation error.
52    ///
53    /// A signature failed verification. Not retryable.
54    #[error("signature validation error: {0}")]
55    SignatureValidation(#[from] SignatureError),
56    /// Identity update error.
57    ///
58    /// Failed to process identity update. Not retryable.
59    #[error(transparent)]
60    IdentityUpdate(#[from] IdentityUpdateError),
61    /// Signature request error.
62    ///
63    /// Failed to create/process signature request. Not retryable.
64    #[error(transparent)]
65    SignatureRequest(#[from] SignatureRequestError),
66    /// Group error.
67    ///
68    /// Group operation failed. May be retryable.
69    // the box is to prevent infinite cycle between client and group errors
70    #[error(transparent)]
71    Group(Box<GroupError>),
72    /// Local event error.
73    ///
74    /// Failed to process local event. Not retryable.
75    #[error(transparent)]
76    LocalEvent(#[from] LocalEventError),
77    /// Database connection error.
78    ///
79    /// Connection to database failed. Retryable.
80    #[error(transparent)]
81    Db(#[from] xmtp_db::ConnectionError),
82    /// Message decode failed.
83    ///
84    /// Enrichment returned no decoded message for a stored message. Not
85    /// retryable.
86    #[error("Failed to decode message")]
87    MessageDecodeFailed,
88    /// MLS store error.
89    ///
90    /// OpenMLS key store operation failed. Not retryable.
91    #[error(transparent)]
92    MlsStore(#[from] MlsStoreError),
93    /// Message enrichment error.
94    ///
95    /// Failed to enrich message content. Not retryable.
96    #[error(transparent)]
97    EnrichMessage(#[from] EnrichMessageError),
98    /// Conversion Error
99    ///
100    /// Data type failed to convert. Not retryable.
101    #[error(transparent)]
102    Conversion(#[from] xmtp_proto::ConversionError),
103    #[error(transparent)]
104    #[error_code(inherit)]
105    Handle(#[from] crate::inbox_handles::HandleError),
106    /// Registration not visible.
107    ///
108    /// The registration receipt was invalid or was not visible before the timeout.
109    /// Call `register_identity` again to retry a pending registration.
110    #[error("Registration is not visible")]
111    RegistrationNotVisible,
112    /// Client is closed.
113    ///
114    /// Operation was attempted on a client that has been shut down via
115    /// `Client::close`. Not retryable — build a new client instead.
116    #[error("client is closed")]
117    AlreadyClosed,
118    /// Server configuration unavailable.
119    ///
120    /// The backend did not serve its configuration, or the answer could not be
121    /// stored. A backend older than spec 006 answers `UNIMPLEMENTED`; there is
122    /// no compatibility shim. Retryable exactly when the wrapped failure is:
123    /// an unreachable backend is worth another attempt, `UNIMPLEMENTED` is not.
124    #[error("server configuration unavailable: {0}")]
125    ConfigurationUnavailable(#[source] Box<crate::server_configuration::ConfigurationFetchError>),
126    /// Server configuration invalid.
127    ///
128    /// The backend published a configuration this client cannot use: a missing
129    /// or malformed identifier, a minimum version that does not parse, or a
130    /// chain that is not a CAIP-2 identifier. Not retryable.
131    #[error("server configuration invalid: {0}")]
132    ConfigurationInvalid(#[from] xmtp_configuration::ServerConfigurationError),
133    /// Backend mismatch.
134    ///
135    /// This database is bound to one backend deployment and a different one
136    /// answered. Not retryable — use a database created for the backend this
137    /// app now points at.
138    #[error("this database is bound to backend {stored}, but {received} answered")]
139    BackendMismatch { stored: String, received: String },
140    /// Client version too old.
141    ///
142    /// The backend requires a newer libxmtp than this build. Not retryable —
143    /// ship an updated client.
144    #[error("client version {client} is below the {minimum} this backend requires")]
145    ClientVersionTooOld { client: String, minimum: String },
146    /// Authentication required.
147    ///
148    /// The backend requires a credential and none was configured. Not
149    /// retryable — supply an auth callback or handle before building.
150    #[error(
151        "this backend requires authentication; required scopes: [{}]",
152        required_scopes.join(", ")
153    )]
154    AuthRequired { required_scopes: Vec<String> },
155    /// Chain not accepted.
156    ///
157    /// The backend does not verify smart contract wallet signatures on this
158    /// chain. Not retryable — use a chain the deployment accepts.
159    #[error(
160        "this backend does not accept smart contract wallet signatures on {chain}; accepted: [{}]",
161        accepted.join(", ")
162    )]
163    ChainNotAccepted {
164        chain: String,
165        accepted: Vec<String>,
166    },
167    /// Invalid list options.
168    ///
169    /// A conversation listing named a limit below 1 or above the maximum page
170    /// size, a before conversation id without the before time of its list
171    /// order, or sync or one-shot groups. Not retryable — fix the options.
172    #[error("invalid list options: {0}")]
173    InvalidListOptions(&'static str),
174    /// Consent act refused.
175    ///
176    /// The consent entity cannot be stored, or names a conversation the
177    /// client does not hold. Not retryable.
178    #[error("consent act: {0}")]
179    #[error_code(inherit)]
180    ConsentAct(#[from] ConsentActError),
181}
182
183impl ClientError {
184    #[deny(clippy::wildcard_enum_match_arm)]
185    pub fn db_needs_connection(&self) -> bool {
186        use crate::worker::NeedsDbReconnect;
187        match self {
188            Self::Storage(s) | Self::ConsentAct(ConsentActError::Storage(s)) => {
189                s.db_needs_connection()
190            }
191            Self::Db(c) => c.db_needs_connection(),
192            Self::Group(error) => error.needs_db_reconnect(),
193            Self::Identity(error) => error.needs_db_reconnect(),
194            Self::IdentityUpdate(error) => error.needs_db_reconnect(),
195            Self::MlsStore(error) => error.needs_db_reconnect(),
196            Self::ConfigurationUnavailable(error) => error.db_needs_connection(),
197            Self::ConsentAct(_)
198            | Self::AddressValidation(..)
199            | Self::PublishError(..)
200            | Self::Api(..)
201            | Self::TlsError(..)
202            | Self::KeyPackageVerification(..)
203            | Self::StreamInconsistency(..)
204            | Self::Association(..)
205            | Self::SignatureValidation(..)
206            | Self::SignatureRequest(..)
207            | Self::LocalEvent(..)
208            | Self::MessageDecodeFailed
209            | Self::EnrichMessage(..)
210            | Self::Conversion(..)
211            | Self::Handle(..)
212            | Self::RegistrationNotVisible
213            | Self::AlreadyClosed
214            | Self::ConfigurationInvalid(..)
215            | Self::BackendMismatch { .. }
216            | Self::ClientVersionTooOld { .. }
217            | Self::AuthRequired { .. }
218            | Self::ChainNotAccepted { .. }
219            | Self::InvalidListOptions(..) => false,
220        }
221    }
222}
223
224impl From<NotFound> for ClientError {
225    fn from(value: NotFound) -> Self {
226        ClientError::Storage(StorageError::NotFound(value))
227    }
228}
229
230impl From<GroupError> for ClientError {
231    fn from(err: GroupError) -> ClientError {
232        ClientError::Group(Box::new(err))
233    }
234}
235
236impl From<BlockedConnection> for ClientError {
237    fn from(blocked_connection: BlockedConnection) -> Self {
238        match blocked_connection {
239            BlockedConnection::BackendMismatch { stored, received } => {
240                ClientError::BackendMismatch { stored, received }
241            }
242            BlockedConnection::ClientVersionTooOld { client, minimum } => {
243                ClientError::ClientVersionTooOld { client, minimum }
244            }
245        }
246    }
247}
248
249impl From<ServerConfigError> for ClientError {
250    fn from(error: ServerConfigError) -> Self {
251        match error {
252            ServerConfigError::Unavailable(error) => ClientError::ConfigurationUnavailable(error),
253            ServerConfigError::Invalid(error) => ClientError::ConfigurationInvalid(error),
254            ServerConfigError::Blocked(blocked_connection) => blocked_connection.into(),
255            ServerConfigError::Closed => ClientError::AlreadyClosed,
256        }
257    }
258}
259
260impl xmtp_common::RetryableError for ClientError {
261    fn is_retryable(&self) -> bool {
262        match self {
263            ClientError::Group(group_error) => retryable!(group_error),
264            ClientError::IdentityUpdate(error) => retryable!(error),
265            ClientError::Api(api_error) => retryable!(api_error),
266            ClientError::Storage(storage_error) => retryable!(storage_error),
267            ClientError::Db(db) => retryable!(db),
268            // SCW verification errors carry retryability through SignatureError;
269            // transient RPC provider failures must not advance the welcome cursor.
270            // See xmtp/libxmtp#3394.
271            ClientError::SignatureValidation(e) => retryable!(e),
272            // A backend that was briefly unreachable, or a database that was
273            // briefly locked, is worth another attempt: the refresh worker's
274            // backoff depends on this answer.
275            ClientError::ConfigurationUnavailable(e) => retryable!(e),
276            _ => false,
277        }
278    }
279
280    fn rate_limit_delay(&self) -> Option<xmtp_common::time::Duration> {
281        match self {
282            ClientError::Group(group_error) => group_error.rate_limit_delay(),
283            ClientError::IdentityUpdate(error) => error.rate_limit_delay(),
284            ClientError::Api(api_error) => api_error.rate_limit_delay(),
285            ClientError::SignatureValidation(e) => e.rate_limit_delay(),
286            ClientError::ConfigurationUnavailable(e) => e.rate_limit_delay(),
287            _ => None,
288        }
289    }
290}
291
292/// The structured stream failure in `error`, read as
293/// [`stream_failure_details`](crate::subscriptions::stream_failure::stream_failure_details)
294/// does, and also through [`ClientError::Group`], whose `source()` skips the
295/// group error because the variant is transparent.
296pub fn stream_failure_details(
297    error: &(dyn std::error::Error + 'static),
298) -> Option<crate::subscriptions::stream_failure::StreamFailureDetails> {
299    crate::subscriptions::stream_failure::stream_failure_details_opening(error, |error| {
300        match error.downcast_ref::<ClientError>() {
301            Some(ClientError::Group(error)) => Some(error.as_ref()),
302            _ => None,
303        }
304    })
305}