Skip to main content

matrix_sdk/
error.rs

1// Copyright 2020 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Error conditions.
16
17use std::{io::Error as IoError, sync::Arc, time::Duration};
18
19use as_variant::as_variant;
20use http::StatusCode;
21#[cfg(feature = "qrcode")]
22use matrix_sdk_base::crypto::ScanError;
23#[cfg(feature = "e2e-encryption")]
24use matrix_sdk_base::crypto::{
25    BootstrapCrossSigningError, CryptoStoreError, DecryptorError, KeyExportError, MegolmError,
26    OlmError, SignatureError,
27};
28use matrix_sdk_base::{
29    Error as SdkBaseError, QueueWedgeError, RoomState, StoreError,
30    cross_process_lock::CrossProcessLockUnobtained, event_cache::store::EventCacheStoreError,
31    media::store::MediaStoreError,
32};
33use oauth2::{RequestTokenError, basic::BasicErrorResponseType};
34use reqwest::Error as ReqwestError;
35use ruma::{
36    IdParseError,
37    api::{
38        client::uiaa::{UiaaInfo, UiaaResponse},
39        error::{
40            ErrorKind, FromHttpResponseError, IntoHttpError, RetryAfter, UnknownTokenErrorData,
41        },
42    },
43    events::{room::power_levels::PowerLevelsError, tag::InvalidUserTagName},
44    push::{InsertPushRuleError, RemovePushRuleError},
45    time::SystemTime,
46};
47use serde_json::Error as JsonError;
48use thiserror::Error;
49use url::ParseError as UrlParseError;
50
51use crate::{
52    authentication::oauth::OAuthError, cross_process_lock::CrossProcessLockError,
53    event_cache::EventCacheError, media::MediaError, room::reply::ReplyError,
54    sliding_sync::Error as SlidingSyncError,
55};
56
57/// Result type of the matrix-sdk.
58pub type Result<T, E = Error> = std::result::Result<T, E>;
59
60/// Result type of a pure HTTP request.
61pub type HttpResult<T> = std::result::Result<T, HttpError>;
62
63/// An error response from a Matrix API call, using a client API specific
64/// representation if the endpoint is from that.
65pub type RumaApiError = UiaaResponse;
66
67/// An HTTP error, representing either a connection error or an error while
68/// converting the raw HTTP response into a Matrix response.
69#[derive(Error, Debug)]
70pub enum HttpError {
71    /// Error at the HTTP layer.
72    #[error(transparent)]
73    Reqwest(#[from] ReqwestError),
74
75    /// API response error (deserialization, or a Matrix-specific error).
76    // `Box` its inner value to reduce the enum size.
77    #[error(transparent)]
78    Api(#[from] Box<FromHttpResponseError<RumaApiError>>),
79
80    /// Error when creating an API request (e.g. serialization of
81    /// body/headers/query parameters).
82    #[error(transparent)]
83    IntoHttp(IntoHttpError),
84
85    /// Error while refreshing the access token.
86    #[error(transparent)]
87    RefreshToken(RefreshTokenError),
88
89    /// Error while fetching data that is cached.
90    ///
91    /// This variant is present for convenience because cached data wraps
92    /// [`HttpError`] into an [`Arc`] to be able to clone it.
93    #[error(transparent)]
94    Cached(Arc<HttpError>),
95}
96
97#[rustfmt::skip] // stop rustfmt breaking the `<code>` in docs across multiple lines
98impl HttpError {
99    /// If `self` is
100    /// <code>[Api](Self::Api)([Server](FromHttpResponseError::Server)(e))</code>,
101    /// returns `Some(e)`.
102    ///
103    /// Otherwise, returns `None`.
104    pub fn as_ruma_api_error(&self) -> Option<&RumaApiError> {
105        match self {
106            Self::Api(error) => {
107                as_variant!(error.as_ref(), FromHttpResponseError::Server)
108            },
109            _ => None
110        }
111    }
112}
113
114// Another impl block that's formatted with rustfmt.
115impl HttpError {
116    /// If `self` is a server error in the `errcode` + `error` format expected
117    /// for client API endpoints, returns it.
118    pub fn as_client_api_error(&self) -> Option<&ruma::api::error::Error> {
119        self.as_ruma_api_error().and_then(as_variant!(UiaaResponse::MatrixError))
120    }
121
122    /// If `self` is a server error in the `errcode` + `error` format expected
123    /// for client API endpoints, returns the error kind (`errcode`).
124    pub fn client_api_error_kind(&self) -> Option<&ErrorKind> {
125        self.as_client_api_error().and_then(ruma::api::error::Error::error_kind)
126    }
127
128    /// Whether the homeserver rejected the access token this request was sent
129    /// with.
130    pub(crate) fn is_rejected_token(&self) -> bool {
131        match self {
132            Self::RefreshToken(error) => error.session_rejection().is_some(),
133            Self::Cached(inner) => inner.is_rejected_token(),
134            _ => matches!(self.client_api_error_kind(), Some(ErrorKind::UnknownToken(_))),
135        }
136    }
137
138    /// Try to destructure the error into a user-interactive auth info.
139    ///
140    /// Some requests require user-interactive auth, doing such a request will
141    /// always fail the first time with a 401 status code, the response body
142    /// will contain info on how the client can authenticate.
143    ///
144    /// The request will need to be retried, this time containing additional
145    /// authentication data.
146    ///
147    /// This method is a convenience method to get to the info the server
148    /// returned on the first, failed request.
149    pub fn as_uiaa_response(&self) -> Option<&UiaaInfo> {
150        self.as_ruma_api_error().and_then(as_variant!(UiaaResponse::AuthResponse))
151    }
152
153    /// Returns whether an HTTP error response should be qualified as transient
154    /// or permanent.
155    pub(crate) fn retry_kind(&self) -> RetryKind {
156        match self {
157            // If it was a plain network error, it's either that we're
158            // disconnected from the internet, or that the remote is, so retry a
159            // few times.
160            HttpError::Reqwest(_) => RetryKind::NetworkFailure,
161
162            HttpError::Api(error) => match error.as_ref() {
163                FromHttpResponseError::Server(api_error) => RetryKind::from_api_error(api_error),
164                _ => RetryKind::Permanent,
165            },
166
167            HttpError::RefreshToken(error) => {
168                if error.session_rejection().is_some() {
169                    RetryKind::Permanent
170                } else if let RefreshTokenError::MatrixAuth(http_error) = error {
171                    http_error.retry_kind()
172                } else {
173                    RetryKind::Transient { retry_after: None }
174                }
175            }
176
177            _ => RetryKind::Permanent,
178        }
179    }
180
181    /// If this is a server error, returns whether it matches the expected
182    /// format for an endpoint that is not implemented.
183    pub fn is_endpoint_not_implemented(&self) -> bool {
184        self.as_client_api_error().is_some_and(|error| error.is_endpoint_not_implemented())
185    }
186}
187
188impl From<FromHttpResponseError<RumaApiError>> for HttpError {
189    fn from(value: FromHttpResponseError<RumaApiError>) -> Self {
190        Self::Api(Box::new(value))
191    }
192}
193
194/// The HTTP status code that some reverse proxies return for server errors.
195const STATUS_CODE_PROXY_UNKNOWN_SERVER_ERROR: u16 = 520;
196
197/// How should we behave with respect to retry behavior after an [`HttpError`]
198/// happened?
199#[derive(Debug)]
200pub(crate) enum RetryKind {
201    /// The request failed because of an error at the network layer.
202    NetworkFailure,
203
204    /// The request failed with a "transient" error, meaning it could be retried
205    /// either soon, or after a given amount of time expressed in `retry_after`.
206    Transient {
207        // This is used only for attempts to retry, so on non-wasm32 code (in the `native` module).
208        #[cfg_attr(target_family = "wasm", allow(dead_code))]
209        retry_after: Option<Duration>,
210    },
211
212    /// The request failed with a non-transient error, and retrying it would
213    /// likely cause the same error again, so it's not worth retrying.
214    Permanent,
215}
216
217impl RetryKind {
218    /// Construct a [`RetryKind`] from a Ruma API error.
219    ///
220    /// The Ruma API error is for errors which have the standard error response
221    /// format defined in the [spec].
222    ///
223    /// [spec]: https://spec.matrix.org/v1.11/client-server-api/#standard-error-response
224    fn from_api_error(api_error: &UiaaResponse) -> Self {
225        match api_error {
226            UiaaResponse::MatrixError(client_error) => match client_error.error_kind() {
227                Some(ErrorKind::LimitExceeded(limit_exceeded)) => {
228                    RetryKind::from_retry_after(limit_exceeded.retry_after.as_ref())
229                }
230                Some(ErrorKind::Unrecognized) => RetryKind::Permanent,
231                _ => RetryKind::from_status_code(client_error.status_code)
232                    // This should only happen for non-error status codes, which shouldn't be
233                    // checked here
234                    .unwrap_or(RetryKind::Permanent),
235            },
236            UiaaResponse::AuthResponse(_) => RetryKind::Permanent,
237        }
238    }
239
240    /// Create a [`RetryKind`] if we have found a [`RetryAfter`] defined in an
241    /// error.
242    ///
243    /// This method should be used for errors where the server explicitly tells
244    /// us how long we must wait before we retry the request again.
245    fn from_retry_after(retry_after: Option<&RetryAfter>) -> Self {
246        let retry_after = retry_after.and_then(|retry_after| match retry_after {
247            RetryAfter::Delay(d) => Some(*d),
248            // `duration_since` fails if the date is already in the past, in which case we
249            // fall back to the regular backoff.
250            RetryAfter::DateTime(time) => time.duration_since(SystemTime::now()).ok(),
251        });
252
253        Self::Transient { retry_after }
254    }
255
256    /// Construct a [`RetryKind`] from a HTTP [`StatusCode`].
257    ///
258    /// This should be used if we don't have a more specific Matrix style error
259    /// which gives us more information about the nature of the error, i.e. if
260    /// we received an error from a reverse proxy while the Matrix homeserver is
261    /// down.
262    ///
263    /// Non-error status codes will return a [None] value.
264    fn from_status_code(status_code: StatusCode) -> Option<Self> {
265        // The list of status code below should be considered retryable, since
266        // they reference an issue that should fix itself with time. Any
267        // other status codes besides 520 (unknown server error emitted by
268        // reverse proxies) should be considered permanent.
269        match status_code {
270            // The timeout should probably have been processed somewhere else as a different error
271            // type, but we can add it for completeness
272            StatusCode::REQUEST_TIMEOUT
273            | StatusCode::TOO_MANY_REQUESTS
274            | StatusCode::INTERNAL_SERVER_ERROR
275            | StatusCode::BAD_GATEWAY
276            | StatusCode::SERVICE_UNAVAILABLE
277            | StatusCode::GATEWAY_TIMEOUT
278            | StatusCode::INSUFFICIENT_STORAGE => Some(RetryKind::Transient { retry_after: None }),
279            _ => {
280                // Special case: unknown server error from a reverse proxy, the
281                // server might recover
282                if status_code.as_u16() == STATUS_CODE_PROXY_UNKNOWN_SERVER_ERROR {
283                    Some(RetryKind::Transient { retry_after: None })
284                } else if status_code.is_client_error() || status_code.is_server_error() {
285                    Some(RetryKind::Permanent)
286                } else {
287                    None
288                }
289            }
290        }
291    }
292}
293
294/// Internal representation of errors.
295#[derive(Error, Debug)]
296#[non_exhaustive]
297pub enum Error {
298    /// Error doing an HTTP request.
299    #[error(transparent)]
300    Http(Box<HttpError>),
301
302    /// Queried endpoint requires authentication but was called on an anonymous
303    /// client.
304    #[error("the queried endpoint requires authentication but was called before logging in")]
305    AuthenticationRequired,
306
307    /// This request failed because the local data wasn't sufficient.
308    #[error("Local cache doesn't contain all necessary data to perform the action.")]
309    InsufficientData,
310
311    /// Attempting to restore a session after the olm-machine has already been
312    /// set up fails
313    #[cfg(feature = "e2e-encryption")]
314    #[error("The olm machine has already been initialized")]
315    BadCryptoStoreState,
316
317    /// Attempting to access the olm-machine but it is not yet available.
318    #[cfg(feature = "e2e-encryption")]
319    #[error("The olm machine isn't yet available")]
320    NoOlmMachine,
321
322    /// An error de/serializing type for the `StateStore`
323    #[error(transparent)]
324    SerdeJson(#[from] JsonError),
325
326    /// An IO error happened.
327    #[error(transparent)]
328    Io(#[from] IoError),
329
330    /// An error occurred in the crypto store.
331    #[cfg(feature = "e2e-encryption")]
332    #[error(transparent)]
333    CryptoStoreError(Box<CryptoStoreError>),
334
335    /// An error occurred with a cross-process store lock.
336    #[error(transparent)]
337    CrossProcessLockError(Box<CrossProcessLockError>),
338
339    /// An error occurred during a E2EE operation.
340    #[cfg(feature = "e2e-encryption")]
341    #[error(transparent)]
342    OlmError(Box<OlmError>),
343
344    /// An error occurred during a E2EE group operation.
345    #[cfg(feature = "e2e-encryption")]
346    #[error(transparent)]
347    MegolmError(Box<MegolmError>),
348
349    /// An error occurred during decryption.
350    #[cfg(feature = "e2e-encryption")]
351    #[error(transparent)]
352    DecryptorError(#[from] DecryptorError),
353
354    /// An error occurred during signing or verifying.
355    #[cfg(feature = "e2e-encryption")]
356    #[error(transparent)]
357    SignatureError(#[from] SignatureError),
358
359    /// An error occurred in the state store.
360    #[error(transparent)]
361    StateStore(Box<StoreError>),
362
363    /// An error occurred in the event cache store.
364    #[error(transparent)]
365    EventCacheStore(Box<EventCacheStoreError>),
366
367    /// An error occurred in the media store.
368    #[error(transparent)]
369    MediaStore(Box<MediaStoreError>),
370
371    /// An error encountered when trying to parse an identifier.
372    #[error(transparent)]
373    Identifier(#[from] IdParseError),
374
375    /// An error encountered when trying to parse a url.
376    #[error(transparent)]
377    Url(#[from] UrlParseError),
378
379    /// An error while scanning a QR code.
380    #[cfg(feature = "qrcode")]
381    #[error(transparent)]
382    QrCodeScanError(Box<ScanError>),
383
384    /// An error encountered when trying to parse a user tag name.
385    #[error(transparent)]
386    UserTagName(#[from] InvalidUserTagName),
387
388    /// An error occurred within sliding-sync
389    #[error(transparent)]
390    SlidingSync(Box<SlidingSyncError>),
391
392    /// Attempted to call a method on a room that requires the user to have a
393    /// specific membership state in the room, but the membership state is
394    /// different.
395    #[error("wrong room state: {0}")]
396    WrongRoomState(Box<WrongRoomState>),
397
398    /// Session callbacks have been set multiple times.
399    #[error("session callbacks have been set multiple times")]
400    MultipleSessionCallbacks,
401
402    /// An error occurred interacting with the OAuth 2.0 API.
403    #[error(transparent)]
404    OAuth(Box<OAuthError>),
405
406    /// A concurrent request to a deduplicated request has failed.
407    #[error("a concurrent request failed; see logs for details")]
408    ConcurrentRequestFailed,
409
410    /// An other error was raised.
411    ///
412    /// This might happen because encryption was enabled on the base-crate but
413    /// not here and that raised.
414    #[cfg(not(target_family = "wasm"))]
415    #[error("unknown error: {0}")]
416    UnknownError(Box<dyn std::error::Error + Send + Sync>),
417
418    /// An other error was raised.
419    #[cfg(target_family = "wasm")]
420    #[error("unknown error: {0}")]
421    UnknownError(Box<dyn std::error::Error>),
422
423    /// An error coming from the event cache subsystem.
424    #[error(transparent)]
425    EventCache(Box<EventCacheError>),
426
427    /// An item has been wedged in the send queue.
428    #[error(transparent)]
429    SendQueueWedgeError(Box<QueueWedgeError>),
430
431    /// Backups are not enabled
432    #[error("backups are not enabled")]
433    BackupNotEnabled,
434
435    /// It's forbidden to ignore your own user.
436    #[error("can't ignore the logged-in user")]
437    CantIgnoreLoggedInUser,
438
439    /// An error happened during handling of a media subrequest.
440    #[error(transparent)]
441    Media(#[from] MediaError),
442
443    /// An error happened while attempting to reply to an event.
444    #[error(transparent)]
445    ReplyError(#[from] ReplyError),
446
447    /// An error happened while attempting to change power levels.
448    #[error("power levels error: {0}")]
449    PowerLevels(#[from] PowerLevelsError),
450
451    /// We timed out attempting to complete an operation.
452    #[error("timed out")]
453    Timeout,
454}
455
456#[rustfmt::skip] // stop rustfmt breaking the `<code>` in docs across multiple lines
457impl Error {
458    /// If `self` is
459    /// <code>[Http](Self::Http)([Api](HttpError::Api)([Server](FromHttpResponseError::Server)(e)))</code>,
460    /// returns `Some(e)`.
461    ///
462    /// Otherwise, returns `None`.
463    pub fn as_ruma_api_error(&self) -> Option<&RumaApiError> {
464        as_variant!(self, Self::Http).and_then(|e| e.as_ruma_api_error())
465    }
466
467    /// If `self` is a server error in the `errcode` + `error` format expected
468    /// for client API endpoints, returns it.
469    pub fn as_client_api_error(&self) -> Option<&ruma::api::error::Error> {
470        self.as_ruma_api_error().and_then(as_variant!(UiaaResponse::MatrixError))
471    }
472
473    /// If `self` is a server error in the `errcode` + `error` format expected
474    /// for client API endpoints, returns the error kind (`errcode`).
475    pub fn client_api_error_kind(&self) -> Option<&ErrorKind> {
476        self.as_client_api_error().and_then(ruma::api::error::Error::error_kind)
477    }
478
479    /// Try to destructure the error into an universal interactive auth info.
480    ///
481    /// Some requests require universal interactive auth, doing such a request
482    /// will always fail the first time with a 401 status code, the response
483    /// body will contain info how the client can authenticate.
484    ///
485    /// The request will need to be retried, this time containing additional
486    /// authentication data.
487    ///
488    /// This method is an convenience method to get to the info the server
489    /// returned on the first, failed request.
490    pub fn as_uiaa_response(&self) -> Option<&UiaaInfo> {
491        self.as_ruma_api_error().and_then(as_variant!(UiaaResponse::AuthResponse))
492    }
493}
494
495impl From<HttpError> for Error {
496    fn from(error: HttpError) -> Self {
497        Error::Http(Box::new(error))
498    }
499}
500
501#[cfg(feature = "e2e-encryption")]
502impl From<CryptoStoreError> for Error {
503    fn from(error: CryptoStoreError) -> Self {
504        Error::CryptoStoreError(Box::new(error))
505    }
506}
507
508impl From<CrossProcessLockError> for Error {
509    fn from(error: CrossProcessLockError) -> Self {
510        Error::CrossProcessLockError(Box::new(error))
511    }
512}
513
514impl From<CrossProcessLockUnobtained> for Error {
515    fn from(error: CrossProcessLockUnobtained) -> Self {
516        CrossProcessLockError::from(error).into()
517    }
518}
519
520#[cfg(feature = "e2e-encryption")]
521impl From<OlmError> for Error {
522    fn from(error: OlmError) -> Self {
523        Error::OlmError(Box::new(error))
524    }
525}
526
527#[cfg(feature = "e2e-encryption")]
528impl From<MegolmError> for Error {
529    fn from(error: MegolmError) -> Self {
530        Error::MegolmError(Box::new(error))
531    }
532}
533
534impl From<StoreError> for Error {
535    fn from(error: StoreError) -> Self {
536        Error::StateStore(Box::new(error))
537    }
538}
539
540impl From<EventCacheStoreError> for Error {
541    fn from(error: EventCacheStoreError) -> Self {
542        Error::EventCacheStore(Box::new(error))
543    }
544}
545
546impl From<MediaStoreError> for Error {
547    fn from(error: MediaStoreError) -> Self {
548        Error::MediaStore(Box::new(error))
549    }
550}
551
552#[cfg(feature = "qrcode")]
553impl From<ScanError> for Error {
554    fn from(error: ScanError) -> Self {
555        Error::QrCodeScanError(Box::new(error))
556    }
557}
558
559impl From<SlidingSyncError> for Error {
560    fn from(error: SlidingSyncError) -> Self {
561        Error::SlidingSync(Box::new(error))
562    }
563}
564
565impl From<OAuthError> for Error {
566    fn from(error: OAuthError) -> Self {
567        Error::OAuth(Box::new(error))
568    }
569}
570
571impl From<EventCacheError> for Error {
572    fn from(error: EventCacheError) -> Self {
573        Error::EventCache(Box::new(error))
574    }
575}
576
577impl From<QueueWedgeError> for Error {
578    fn from(error: QueueWedgeError) -> Self {
579        Error::SendQueueWedgeError(Box::new(error))
580    }
581}
582
583#[cfg(feature = "e2e-encryption")]
584impl From<BootstrapCrossSigningError> for Error {
585    fn from(error: BootstrapCrossSigningError) -> Self {
586        match error {
587            BootstrapCrossSigningError::CryptoStore(e) => e.into(),
588            BootstrapCrossSigningError::Signature(e) => e.into(),
589        }
590    }
591}
592
593/// Error for the room key importing functionality.
594#[cfg(feature = "e2e-encryption")]
595#[derive(Error, Debug)]
596// This is allowed because key importing isn't enabled under wasm.
597#[allow(dead_code)]
598// Flat error: the wrapped types (JSON, IO, crypto store, key export) cannot
599// cross the FFI boundary, so only variant names and messages are exposed.
600#[cfg_attr(feature = "uniffi", derive(uniffi::Error), uniffi(flat_error))]
601pub enum RoomKeyImportError {
602    /// An error de/serializing type for the `StateStore`
603    #[error(transparent)]
604    SerdeJson(#[from] JsonError),
605
606    /// The crypto store isn't yet open. Logging in is required to open the
607    /// crypto store.
608    #[error("The crypto store hasn't been yet opened, can't import yet.")]
609    StoreClosed,
610
611    /// An IO error happened.
612    #[error(transparent)]
613    Io(#[from] IoError),
614
615    /// An error occurred in the crypto store.
616    #[error(transparent)]
617    CryptoStore(#[from] CryptoStoreError),
618
619    /// An error occurred while importing the key export.
620    #[error(transparent)]
621    Export(#[from] KeyExportError),
622}
623
624impl From<FromHttpResponseError<ruma::api::error::Error>> for HttpError {
625    fn from(err: FromHttpResponseError<ruma::api::error::Error>) -> Self {
626        Self::Api(Box::new(err.map(Into::into)))
627    }
628}
629
630impl From<SdkBaseError> for Error {
631    fn from(e: SdkBaseError) -> Self {
632        match e {
633            SdkBaseError::StateStore(e) => Self::StateStore(Box::new(e)),
634            #[cfg(feature = "e2e-encryption")]
635            SdkBaseError::CryptoStore(e) => Self::CryptoStoreError(Box::new(e)),
636            #[cfg(feature = "e2e-encryption")]
637            SdkBaseError::BadCryptoStoreState => Self::BadCryptoStoreState,
638            #[cfg(feature = "e2e-encryption")]
639            SdkBaseError::OlmError(e) => Self::OlmError(Box::new(e)),
640            #[cfg(feature = "eyre")]
641            _ => Self::UnknownError(eyre::eyre!(e).into()),
642            #[cfg(all(not(feature = "eyre"), feature = "anyhow", not(target_family = "wasm")))]
643            _ => Self::UnknownError(anyhow::anyhow!(e).into()),
644            #[cfg(all(not(feature = "eyre"), feature = "anyhow", target_family = "wasm"))]
645            _ => Self::UnknownError(e.into()),
646            #[cfg(all(
647                not(feature = "eyre"),
648                not(feature = "anyhow"),
649                not(target_family = "wasm")
650            ))]
651            _ => {
652                let e: Box<dyn std::error::Error + Send + Sync> = format!("{e:?}").into();
653                Self::UnknownError(e)
654            }
655            #[cfg(all(not(feature = "eyre"), not(feature = "anyhow"), target_family = "wasm"))]
656            _ => {
657                let e: Box<dyn std::error::Error> = format!("{e:?}").into();
658                Self::UnknownError(e)
659            }
660        }
661    }
662}
663
664impl From<ReqwestError> for Error {
665    fn from(e: ReqwestError) -> Self {
666        Error::Http(Box::new(HttpError::Reqwest(e)))
667    }
668}
669
670/// Errors that can happen when interacting with the beacon API.
671#[derive(Debug, Error)]
672pub enum BeaconError {
673    /// A network error occurred.
674    #[error("Network error: {0}")]
675    Network(#[from] HttpError),
676
677    /// The beacon information is not found.
678    #[error("Existing beacon information not found.")]
679    NotFound,
680
681    /// The redacted event is not an error, but it's not useful for the client.
682    #[error("Beacon event is redacted and cannot be processed.")]
683    Redacted,
684
685    /// The client must join the room to access the beacon information.
686    #[error("Must join the room to access beacon information.")]
687    Stripped,
688
689    /// The beacon event could not be deserialized.
690    #[error("Deserialization error: {0}")]
691    Deserialization(#[from] serde_json::Error),
692
693    /// The beacon event is expired.
694    #[error("The beacon event has expired.")]
695    NotLive,
696
697    /// Allow for other errors to be wrapped.
698    #[error("Other error: {0}")]
699    Other(Box<Error>),
700}
701
702impl From<Error> for BeaconError {
703    fn from(err: Error) -> Self {
704        BeaconError::Other(Box::new(err))
705    }
706}
707
708/// Errors that can happen when refreshing an access token.
709///
710/// This is usually only returned by [`Client::refresh_access_token()`], unless
711/// [handling refresh tokens] is activated for the `Client`.
712///
713/// [`Client::refresh_access_token()`]: crate::Client::refresh_access_token()
714/// [handling refresh tokens]: crate::ClientBuilder::handle_refresh_tokens()
715#[derive(Debug, Error, Clone)]
716pub enum RefreshTokenError {
717    /// Tried to send a refresh token request without a refresh token.
718    #[error("missing refresh token")]
719    RefreshTokenRequired,
720
721    /// An error occurred interacting with the native Matrix authentication API.
722    #[error(transparent)]
723    MatrixAuth(Arc<HttpError>),
724
725    /// An error occurred interacting with the OAuth 2.0 API.
726    #[error(transparent)]
727    OAuth(#[from] Arc<OAuthError>),
728}
729
730impl RefreshTokenError {
731    /// Returns the [`UnknownTokenErrorData`] if the session was rejected, as
732    /// opposed to the refresh request itself not getting through.
733    pub(crate) fn session_rejection(&self) -> Option<UnknownTokenErrorData> {
734        match self {
735            // There is no refresh token to exchange and retrying won't fix it.
736            Self::RefreshTokenRequired => Some(UnknownTokenErrorData::default()),
737
738            Self::MatrixAuth(error) => {
739                if error.as_client_api_error()?.status_code != StatusCode::UNAUTHORIZED {
740                    return None;
741                }
742                match error.client_api_error_kind()? {
743                    ErrorKind::UnknownToken(data) => Some(data.clone()),
744                    _ => None,
745                }
746            }
747
748            Self::OAuth(oauth_error) => matches!(
749                &**oauth_error,
750                OAuthError::RefreshToken(RequestTokenError::ServerResponse(error_response))
751                    if *error_response.error() == BasicErrorResponseType::InvalidGrant
752            )
753            .then(UnknownTokenErrorData::default),
754        }
755    }
756}
757
758/// Errors that can occur when manipulating push notification settings.
759#[derive(Debug, Error, Clone, PartialEq)]
760pub enum NotificationSettingsError {
761    /// Invalid parameter.
762    #[error("Invalid parameter `{0}`")]
763    InvalidParameter(String),
764    /// Unable to add push rule.
765    #[error("Unable to add push rule")]
766    UnableToAddPushRule,
767    /// Unable to remove push rule.
768    #[error("Unable to remove push rule")]
769    UnableToRemovePushRule,
770    /// Unable to update push rule.
771    #[error("Unable to update push rule")]
772    UnableToUpdatePushRule,
773    /// Rule not found
774    #[error("Rule `{0}` not found")]
775    RuleNotFound(String),
776    /// Unable to save the push rules
777    #[error("Unable to save push rules")]
778    UnableToSavePushRules,
779}
780
781impl NotificationSettingsError {
782    /// Whether this error is the [`RuleNotFound`](Self::RuleNotFound) variant.
783    pub fn is_rule_not_found(&self) -> bool {
784        matches!(self, Self::RuleNotFound(_))
785    }
786}
787
788impl From<InsertPushRuleError> for NotificationSettingsError {
789    fn from(_: InsertPushRuleError) -> Self {
790        Self::UnableToAddPushRule
791    }
792}
793
794impl From<RemovePushRuleError> for NotificationSettingsError {
795    fn from(_: RemovePushRuleError) -> Self {
796        Self::UnableToRemovePushRule
797    }
798}
799
800#[derive(Debug, Error)]
801#[error("expected: {expected}, got: {got:?}")]
802pub struct WrongRoomState {
803    expected: &'static str,
804    got: RoomState,
805}
806
807impl WrongRoomState {
808    pub(crate) fn new(expected: &'static str, got: RoomState) -> Self {
809        Self { expected, got }
810    }
811}
812
813#[cfg(test)]
814mod tests {
815    use std::time::Duration;
816
817    use assert_matches::assert_matches;
818    use http::StatusCode;
819    use ruma::{
820        api::{EndpointError as _, error::RetryAfter},
821        time::SystemTime,
822    };
823
824    use super::{
825        HttpError, RefreshTokenError, RetryKind, RumaApiError,
826        STATUS_CODE_PROXY_UNKNOWN_SERVER_ERROR,
827    };
828    use crate::error::FromHttpResponseError;
829
830    /// The error a request gets back when refreshing its access token failed
831    /// against the homeserver with the given status code and body.
832    fn refresh_failure(status_code: StatusCode, body: &str) -> HttpError {
833        let response = http::Response::builder().status(status_code).body(body.as_bytes()).unwrap();
834        let api_error = RumaApiError::from_http_response(response);
835
836        HttpError::RefreshToken(RefreshTokenError::MatrixAuth(std::sync::Arc::new(HttpError::Api(
837            Box::new(FromHttpResponseError::Server(api_error)),
838        ))))
839    }
840
841    #[test]
842    fn test_retry_kind_of_a_failed_refresh() {
843        // A 5xx should be retried worth sending again.
844        assert_matches!(
845            refresh_failure(StatusCode::BAD_GATEWAY, "").retry_kind(),
846            RetryKind::Transient { .. }
847        );
848
849        // The homeserver rejected the refresh token so retrying would only fail
850        // again.
851        assert_matches!(
852            refresh_failure(
853                StatusCode::UNAUTHORIZED,
854                r#"{"errcode": "M_UNKNOWN_TOKEN", "error": "Token is not active"}"#,
855            )
856            .retry_kind(),
857            RetryKind::Permanent
858        );
859
860        // There is no refresh token to exchange and retrying won't work.
861        assert_matches!(
862            HttpError::RefreshToken(RefreshTokenError::RefreshTokenRequired).retry_kind(),
863            RetryKind::Permanent
864        );
865
866        assert_matches!(
867            refresh_failure(
868                StatusCode::NOT_FOUND,
869                r#"{"errcode": "M_UNRECOGNIZED", "error": "Not found"}"#
870            )
871            .retry_kind(),
872            RetryKind::Permanent
873        );
874
875        assert_matches!(
876            refresh_failure(
877                StatusCode::TOO_MANY_REQUESTS,
878                r#"{"errcode": "M_LIMIT_EXCEEDED", "error": "Too many requests", "retry_after_ms": 2000}"#,
879            )
880            .retry_kind(),
881            RetryKind::Transient { retry_after: Some(delay) } => {
882                assert_eq!(delay, Duration::from_secs(2));
883            }
884        );
885    }
886
887    #[test]
888    fn test_retry_kind_from_retry_after() {
889        assert_matches!(
890            RetryKind::from_retry_after(None),
891            RetryKind::Transient { retry_after: None }
892        );
893
894        assert_matches!(
895            RetryKind::from_retry_after(Some(&RetryAfter::Delay(Duration::from_secs(5)))),
896            RetryKind::Transient { retry_after: Some(delay) } => {
897                assert_eq!(delay, Duration::from_secs(5));
898            }
899        );
900
901        // A date in the future is turned into the delay until that date.
902        let in_a_minute = SystemTime::now() + Duration::from_secs(60);
903        assert_matches!(
904            RetryKind::from_retry_after(Some(&RetryAfter::DateTime(in_a_minute))),
905            RetryKind::Transient { retry_after: Some(delay) } => {
906                assert!(delay > Duration::from_secs(55));
907                assert!(delay <= Duration::from_secs(60));
908            }
909        );
910
911        // A date in the past falls back to the regular backoff.
912        let a_minute_ago = SystemTime::now() - Duration::from_secs(60);
913        assert_matches!(
914            RetryKind::from_retry_after(Some(&RetryAfter::DateTime(a_minute_ago))),
915            RetryKind::Transient { retry_after: None }
916        );
917    }
918
919    #[test]
920    fn test_retry_kind_of_http_status_codes() {
921        let retry_status_code = [
922            StatusCode::REQUEST_TIMEOUT,
923            StatusCode::TOO_MANY_REQUESTS,
924            StatusCode::INTERNAL_SERVER_ERROR,
925            StatusCode::BAD_GATEWAY,
926            StatusCode::SERVICE_UNAVAILABLE,
927            StatusCode::GATEWAY_TIMEOUT,
928            StatusCode::INSUFFICIENT_STORAGE,
929            StatusCode::from_u16(STATUS_CODE_PROXY_UNKNOWN_SERVER_ERROR).unwrap(),
930        ];
931
932        // Check retryable status codes
933        for code in retry_status_code.iter() {
934            assert_matches!(
935                RetryKind::from_status_code(code.to_owned()),
936                Some(RetryKind::Transient { .. })
937            );
938        }
939
940        // Check any possible (existing) non-error code
941        for i in 1..400 {
942            let Ok(code) = StatusCode::from_u16(i) else {
943                continue;
944            };
945            if retry_status_code.contains(&code) {
946                continue;
947            }
948            assert_matches!(RetryKind::from_status_code(code.to_owned()), None);
949        }
950
951        // Check any possible (existing) error code
952        for i in 400..600 {
953            let Ok(code) = StatusCode::from_u16(i) else {
954                continue;
955            };
956            if retry_status_code.contains(&code) {
957                continue;
958            }
959            assert_matches!(RetryKind::from_status_code(code), Some(RetryKind::Permanent));
960        }
961    }
962}