Skip to main content

cent/
error.rs

1//! The errors of every call, and [`retryable`].
2
3use std::fmt;
4use std::sync::Arc;
5
6use bytes::Bytes;
7use serde::ser::SerializeMap;
8use serde::{Serialize, Serializer};
9
10#[cfg(feature = "client")]
11use crate::batch::BatchFailedCommandsError;
12use crate::broadcast::BroadcastFailedChannelsError;
13
14/// A boxed error, as application functions return them: the endpoint and
15/// token functions, HTTP clients, handler functions.
16pub type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
17
18/// A shared error source: errors are [`Clone`], so that an automatic batch
19/// can give its error to every call it carried.
20pub(crate) type Source = Arc<dyn std::error::Error + Send + Sync + 'static>;
21
22/// The error of a call. Every call returns one unless it did everything it
23/// was asked: `?` is always correct code.
24///
25/// Match it by kind:
26///
27/// ```
28/// # fn check(err: cent::Error) {
29/// match &err {
30///     // Centrifugo refused the request: match the code, never the message.
31///     cent::Error::Api(e) if e.code == cent::ApiError::UNKNOWN_CHANNEL => {}
32///     // Some channels of a broadcast failed; the others got the publication.
33///     cent::Error::BroadcastFailedChannels(e) => {
34///         for (channel, err) in e.errors() {
35///             eprintln!("not published into {channel}: {err}");
36///         }
37///     }
38///     _ if err.is_retryable() => {} // a temporary failure: see `retryable`
39///     _ => {}
40/// }
41/// # }
42/// ```
43///
44/// Centrifugo adds error codes over time: an unknown code is still an
45/// [`Error::Api`], so match the codes you handle and treat the rest by kind.
46#[derive(Debug, Clone)]
47#[non_exhaustive]
48pub enum Error {
49    /// Centrifugo refused the request, or failed to carry it out.
50    Api(ApiError),
51    /// The request did not reach the API method: an HTTP status other than
52    /// 200. A 401 means the credentials were refused: see
53    /// [`Error::is_unauthorized`].
54    Http(Box<HttpError>),
55    /// The reply is not Centrifugo's - usually `api_endpoint` points
56    /// elsewhere.
57    Decode(DecodeError),
58    /// The client could tell the request is wrong, and did not send it.
59    InvalidRequest(InvalidRequestError),
60    /// The client refuses to work as configured: it was not created, it is
61    /// used where it cannot work (another tokio runtime), or a configured
62    /// function - [`Config::with_endpoint_fn`] or [`Config::bearer_token`] -
63    /// returned what cannot be sent, an endpoint failing [`Config::new`]'s
64    /// rules or an empty or malformed token, and nothing was sent. The
65    /// message names the option and the fix. Not retryable.
66    ///
67    /// [`Config::with_endpoint_fn`]: crate::Config::with_endpoint_fn
68    /// [`Config::bearer_token`]: crate::Config::bearer_token
69    /// [`Config::new`]: crate::Config::new
70    InvalidConfig(InvalidConfigError),
71    /// A call made after the client was closed.
72    Closed,
73    /// A [`Pending`](crate::Pending) read before its batch was sent.
74    BatchNotSent,
75    /// Centrifugo carried out a broadcast, and one or more of its channels
76    /// failed, up to all: the others got the publication.
77    BroadcastFailedChannels(Box<BroadcastFailedChannelsError>),
78    /// Centrifugo carried out a batch, and one or more of its commands
79    /// failed, up to all: each command has its own outcome.
80    #[cfg(feature = "client")]
81    BatchFailedCommands(Box<BatchFailedCommandsError>),
82    /// A broadcast with retries stopped by its `on_attempt_error` callback,
83    /// or by its deadline while waiting to retry.
84    RetryStopped(Box<RetryStoppedError>),
85    /// The call's deadline passed: its timeout, or the client's
86    /// `request_timeout`. Every timeout is this error.
87    Timeout(TimeoutError),
88    /// The network failed: a refused or reset connection, a TLS failure.
89    Network(NetworkError),
90    /// The application's function given to `Config::with_endpoint_fn` or
91    /// `Config::bearer_token` returned an error: it is the source, and the
92    /// message names the function. Judged by [`retryable`](crate::retryable)
93    /// as its source is. What such a function returns and the client cannot
94    /// send is an [`Error::InvalidConfig`] instead.
95    Function(FunctionError),
96    /// A payload did not encode, or decode as the type asked: from
97    /// [`json`](crate::json) and [`PayloadExt::decode`](crate::PayloadExt::decode).
98    Payload(PayloadError),
99}
100
101/// An error Centrifugo returned: it understood the request, and refused it or
102/// failed to carry it out. It is the same whether Centrifugo puts it in a 200
103/// reply or, in its transport error mode, in the body of an HTTP error
104/// status.
105///
106/// Compare [`code`](Self::code) with the constants, such as
107/// [`ApiError::UNKNOWN_CHANNEL`]: the code is stable, the message is for
108/// people.
109#[derive(Debug, Clone, PartialEq, Eq)]
110#[non_exhaustive]
111pub struct ApiError {
112    /// Identifies the error.
113    pub code: u32,
114    /// Describes the error for people. Never compare it.
115    pub message: String,
116    /// Set by Centrifugo (v6.10.0 and newer) when the same request may
117    /// succeed if retried later: the error came from a temporary condition,
118    /// such as a broker being unavailable or a rate limit, not from the
119    /// request. It does not mean nothing was done: a publication may have
120    /// happened, so retry it with the same `idempotency_key`.
121    pub temporary: bool,
122    /// The method of a batch command which only Centrifugo PRO has: Centrifugo
123    /// OSS answers it with code 104, where a call of its own gets a 404.
124    pro_method: Option<&'static str>,
125}
126
127impl ApiError {
128    /// Internal error: temporary.
129    pub const INTERNAL: u32 = 100;
130    /// The channel's namespace is not configured.
131    pub const UNKNOWN_CHANNEL: u32 = 102;
132    /// Not found. In a batch, also a Centrifugo PRO method sent to
133    /// Centrifugo OSS.
134    pub const NOT_FOUND: u32 = 104;
135    /// Bad request.
136    pub const BAD_REQUEST: u32 = 107;
137    /// Not available: the feature is off for the channel.
138    pub const NOT_AVAILABLE: u32 = 108;
139    /// Too many requests: temporary.
140    pub const TOO_MANY_REQUESTS: u32 = 111;
141    /// Unrecoverable position in a channel's history.
142    pub const UNRECOVERABLE_POSITION: u32 = 112;
143    /// Conflict.
144    pub const CONFLICT: u32 = 113;
145
146    /// Returns an error with `code` and `message`, for test doubles.
147    #[must_use]
148    pub fn new(code: u32, message: impl Into<String>) -> Self {
149        Self {
150            code,
151            message: message.into(),
152            temporary: false,
153            pro_method: None,
154        }
155    }
156
157    /// Sets [`temporary`](Self::temporary).
158    #[must_use]
159    pub fn temporary(mut self, temporary: bool) -> Self {
160        self.temporary = temporary;
161        self
162    }
163
164    /// The error of a batch command for `method`, with the hint of a PRO
165    /// method sent to Centrifugo OSS when it may be that.
166    #[cfg(feature = "client")]
167    pub(crate) fn in_batch(mut self, method: &'static str) -> Self {
168        if self.code == Self::NOT_FOUND && crate::request::is_pro(method) {
169            self.pro_method = Some(method);
170        }
171        self
172    }
173}
174
175impl fmt::Display for ApiError {
176    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177        let message = if self.message.is_empty() {
178            "server error"
179        } else {
180            &self.message
181        };
182        write!(f, "{message} (code {})", self.code)?;
183        if let Some(m) = self.pro_method {
184            write!(
185                f,
186                " ({m} is a Centrifugo PRO method: is the server Centrifugo OSS?)"
187            )?;
188        }
189        Ok(())
190    }
191}
192
193impl std::error::Error for ApiError {}
194
195/// A reply with an HTTP status other than 200 OK: the request did not reach
196/// the API method at all.
197#[derive(Debug, Clone)]
198#[non_exhaustive]
199pub struct HttpError {
200    /// The HTTP status.
201    pub status: http::StatusCode,
202    /// The start of the reply's body, for diagnostics.
203    pub body: Bytes,
204    /// The reply's headers, as received: a request ID a proxy set, or a
205    /// `Retry-After`.
206    pub headers: http::HeaderMap,
207    /// The method of the request when only Centrifugo PRO has it: a 404 for
208    /// it most likely means the server is Centrifugo OSS.
209    pro_method: Option<&'static str>,
210}
211
212impl HttpError {
213    /// Returns an error for a reply with `status`, `headers` and `body`, for
214    /// test doubles.
215    #[must_use]
216    pub fn new(status: http::StatusCode, headers: http::HeaderMap, body: impl Into<Bytes>) -> Self {
217        Self {
218            status,
219            body: body.into(),
220            headers,
221            pro_method: None,
222        }
223    }
224
225    #[cfg(feature = "client")]
226    pub(crate) fn with_pro_method(mut self, method: Option<&'static str>) -> Self {
227        self.pro_method = method;
228        self
229    }
230}
231
232impl fmt::Display for HttpError {
233    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234        write!(f, "unexpected HTTP status {}", self.status.as_u16())?;
235        let code = self.status.as_u16();
236        if self.status.is_redirection() {
237            // Centrifugo's API never redirects a call: its router redirects
238            // only a path not in canonical form, a doubled slash say, and
239            // something in front of it may redirect http to https.
240            f.write_str(" (a redirect, which the client does not follow: check api_endpoint's scheme, http or https, and its path)")?;
241        } else if code == 404 {
242            match self.pro_method {
243                Some(m) => write!(
244                    f,
245                    " ({m} is a Centrifugo PRO method: if other methods work, the server is Centrifugo OSS)"
246                )?,
247                None => f.write_str(
248                    " (is api_endpoint the API base URL, such as http://localhost:8000/api?)",
249                )?,
250            }
251        } else if code == 401 {
252            f.write_str(" (check the credentials: api_key or bearer_token)")?;
253        }
254        if !self.body.is_empty() {
255            write!(f, ": {}", String::from_utf8_lossy(&self.body))?;
256        }
257        Ok(())
258    }
259}
260
261impl std::error::Error for HttpError {}
262
263/// A reply which is not Centrifugo's: usually an `api_endpoint` which does not
264/// point at Centrifugo's API, so that something else answers instead.
265#[derive(Debug, Clone)]
266pub struct DecodeError {
267    message: String,
268    source: Option<Source>,
269}
270
271#[cfg(feature = "client")]
272impl DecodeError {
273    pub(crate) fn json(err: serde_json::Error) -> Self {
274        Self {
275            message: err.to_string(),
276            source: Some(Arc::new(err)),
277        }
278    }
279
280    pub(crate) fn message(message: impl Into<String>) -> Self {
281        Self {
282            message: message.into(),
283            source: None,
284        }
285    }
286}
287
288impl fmt::Display for DecodeError {
289    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
290        write!(f, "decoding the reply: {}", self.message)
291    }
292}
293
294impl std::error::Error for DecodeError {
295    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
296        self.source.as_deref().map(|e| e as _)
297    }
298}
299
300/// A payload which did not encode, or decode as the type asked.
301#[derive(Debug, Clone)]
302pub struct PayloadError {
303    encode: bool,
304    source: Option<Source>,
305}
306
307impl PayloadError {
308    pub(crate) fn encode(err: serde_json::Error) -> Self {
309        Self {
310            encode: true,
311            source: Some(Arc::new(err)),
312        }
313    }
314
315    pub(crate) fn decode(err: serde_json::Error) -> Self {
316        Self {
317            encode: false,
318            source: Some(Arc::new(err)),
319        }
320    }
321
322    /// A payload field which is unset.
323    pub(crate) fn missing() -> Self {
324        Self {
325            encode: false,
326            source: None,
327        }
328    }
329}
330
331impl fmt::Display for PayloadError {
332    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
333        f.write_str(if self.encode {
334            "encoding the payload: "
335        } else {
336            "decoding the payload: "
337        })?;
338        match &self.source {
339            Some(e) => e.fmt(f),
340            None => f.write_str("no payload"),
341        }
342    }
343}
344
345impl std::error::Error for PayloadError {
346    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
347        self.source.as_deref().map(|e| e as _)
348    }
349}
350
351/// A request the client did not send, because it could tell it is wrong: a
352/// publication without a channel or data, say. Only rules which hold for
353/// every Centrifugo are checked; everything else is Centrifugo's to check.
354#[derive(Debug, Clone)]
355pub struct InvalidRequestError {
356    method: &'static str,
357    problem: String,
358    /// The position of the command in its batch.
359    command: Option<usize>,
360}
361
362impl InvalidRequestError {
363    pub(crate) fn new(method: &'static str, problem: impl Into<String>) -> Self {
364        Self {
365            method,
366            problem: problem.into(),
367            command: None,
368        }
369    }
370
371    #[cfg(feature = "client")]
372    pub(crate) fn in_command(mut self, index: usize) -> Self {
373        self.command = Some(index);
374        self
375    }
376
377    /// The API method of the request, such as `"publish"`.
378    #[must_use]
379    pub fn method(&self) -> &'static str {
380        self.method
381    }
382
383    /// The position of the command in its batch, for a batch not sent
384    /// because of it.
385    #[must_use]
386    pub fn command(&self) -> Option<usize> {
387        self.command
388    }
389}
390
391impl fmt::Display for InvalidRequestError {
392    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
393        if let Some(i) = self.command {
394            write!(f, "batch command #{i}: ")?;
395        }
396        write!(f, "invalid {} request: {}", self.method, self.problem)
397    }
398}
399
400impl std::error::Error for InvalidRequestError {}
401
402/// A client not created - or used where it cannot work - with a message
403/// naming the option and the fix.
404#[derive(Debug, Clone)]
405pub struct InvalidConfigError(pub(crate) String);
406
407impl fmt::Display for InvalidConfigError {
408    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
409        write!(f, "invalid config: {}", self.0)
410    }
411}
412
413impl std::error::Error for InvalidConfigError {}
414
415/// A call whose deadline passed. After a timeout Centrifugo may still have
416/// carried the request out: retry a publication only with the same
417/// `idempotency_key`.
418#[derive(Debug, Clone)]
419pub struct TimeoutError {
420    pub(crate) method: Option<&'static str>,
421    /// Set for a call of an automatic batch which never left the queue.
422    pub(crate) unsent: bool,
423}
424
425impl TimeoutError {
426    /// The API method of the call, when the timeout is a call's.
427    #[must_use]
428    pub fn method(&self) -> Option<&'static str> {
429        self.method
430    }
431
432    /// Whether the call was never sent: it timed out before its request
433    /// left - waiting in an automatic batch's queue, or with its deadline
434    /// already passed. Then it surely did not take effect, and a retry
435    /// cannot publish twice.
436    #[must_use]
437    pub fn unsent(&self) -> bool {
438        self.unsent
439    }
440}
441
442impl fmt::Display for TimeoutError {
443    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
444        if let Some(m) = self.method {
445            write!(f, "{m}: ")?;
446        }
447        f.write_str("timed out")?;
448        if self.unsent {
449            f.write_str(" before it was sent")?;
450        }
451        Ok(())
452    }
453}
454
455impl std::error::Error for TimeoutError {}
456
457/// A failure of the network: connecting, TLS, the connection breaking.
458#[derive(Debug, Clone)]
459pub struct NetworkError {
460    method: &'static str,
461    source: Source,
462    /// The server's certificate was refused: retrying cannot help.
463    certificate: bool,
464}
465
466impl NetworkError {
467    #[cfg(feature = "client")]
468    pub(crate) fn new(method: &'static str, source: Source, certificate: bool) -> Self {
469        Self {
470            method,
471            source,
472            certificate,
473        }
474    }
475
476    /// Whether the server's TLS certificate was refused, which a retry cannot
477    /// fix.
478    #[must_use]
479    pub fn is_certificate(&self) -> bool {
480        self.certificate
481    }
482}
483
484impl fmt::Display for NetworkError {
485    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
486        write!(f, "{}: {}", self.method, self.source)?;
487        // Show the chain: hyper's errors say only "client error (Connect)".
488        let mut cause = self.source.source();
489        while let Some(c) = cause {
490            write!(f, ": {c}")?;
491            cause = c.source();
492        }
493        Ok(())
494    }
495}
496
497impl std::error::Error for NetworkError {
498    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
499        Some(&*self.source)
500    }
501}
502
503/// An error of the application's function given to
504/// `Config::with_endpoint_fn` or `Config::bearer_token`: the function's own
505/// error, its source, and the function's name.
506#[derive(Debug, Clone)]
507pub struct FunctionError {
508    function: &'static str,
509    source: Source,
510}
511
512impl FunctionError {
513    #[cfg(feature = "client")]
514    pub(crate) fn new(function: &'static str, source: Source) -> Self {
515        Self { function, source }
516    }
517
518    /// The function, as `Config` names it: `"with_endpoint_fn"` or
519    /// `"bearer_token"`.
520    #[must_use]
521    pub fn function(&self) -> &'static str {
522        self.function
523    }
524}
525
526impl fmt::Display for FunctionError {
527    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
528        write!(f, "{}: {}", self.function, self.source)
529    }
530}
531
532impl std::error::Error for FunctionError {
533    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
534        Some(&*self.source)
535    }
536}
537
538/// A broadcast with retries which stopped before its last attempt: its
539/// `on_attempt_error` callback returned an error, or the call's deadline
540/// came while it waited to retry. [`error`](Self::error) is the broadcast's
541/// error at that point - a [`Error::BroadcastFailedChannels`] holding every
542/// channel's outcome when some attempt got a reply.
543#[derive(Debug, Clone)]
544pub struct RetryStoppedError {
545    reason: Source,
546    error: Error,
547}
548
549impl RetryStoppedError {
550    #[cfg(feature = "client")]
551    pub(crate) fn new(reason: Source, error: Error) -> Self {
552        Self { reason, error }
553    }
554
555    /// Why the retries stopped: the callback's error, or [`Error::Timeout`].
556    #[must_use]
557    pub fn reason(&self) -> &(dyn std::error::Error + Send + Sync + 'static) {
558        &*self.reason
559    }
560
561    /// The broadcast's error when it stopped.
562    #[must_use]
563    pub fn error(&self) -> &Error {
564        &self.error
565    }
566}
567
568impl fmt::Display for RetryStoppedError {
569    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
570        write!(
571            f,
572            "broadcast retries stopped: {}; {}",
573            self.reason, self.error
574        )
575    }
576}
577
578impl std::error::Error for RetryStoppedError {
579    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
580        Some(&self.error)
581    }
582}
583
584impl Error {
585    #[cfg(feature = "client")]
586    pub(crate) fn invalid_config(message: impl Into<String>) -> Self {
587        Self::InvalidConfig(InvalidConfigError(message.into()))
588    }
589
590    pub(crate) fn invalid_request(method: &'static str, problem: impl Into<String>) -> Self {
591        Self::InvalidRequest(InvalidRequestError::new(method, problem))
592    }
593
594    #[cfg(feature = "client")]
595    pub(crate) fn timeout(method: &'static str) -> Self {
596        Self::Timeout(TimeoutError {
597            method: Some(method),
598            unsent: false,
599        })
600    }
601
602    /// The code of a Centrifugo error, compared with the constants of
603    /// [`ApiError`]: `err.api_code() == Some(ApiError::UNKNOWN_CHANNEL)`.
604    /// `None` for any other error - a broadcast or batch in which some parts
605    /// failed included: look at each part's error instead.
606    #[must_use]
607    pub fn api_code(&self) -> Option<u32> {
608        match self {
609            Self::Api(e) => Some(e.code),
610            _ => None,
611        }
612    }
613
614    /// Whether Centrifugo refused the credentials: an HTTP 401.
615    #[must_use]
616    pub fn is_unauthorized(&self) -> bool {
617        matches!(self, Self::Http(e) if e.status == http::StatusCode::UNAUTHORIZED)
618    }
619
620    /// Whether the call timed out.
621    #[must_use]
622    pub fn is_timeout(&self) -> bool {
623        matches!(self, Self::Timeout(_))
624    }
625
626    /// Whether a new attempt, with time left, may succeed: see [`retryable`].
627    #[must_use]
628    pub fn is_retryable(&self) -> bool {
629        retryable(self)
630    }
631
632    /// The result of a broadcast in which some channels failed - also inside
633    /// [`Error::RetryStopped`]: every channel's outcome.
634    #[must_use]
635    pub fn broadcast_result(&self) -> Option<&crate::BroadcastResult> {
636        match self {
637            Self::BroadcastFailedChannels(e) => Some(e.result()),
638            Self::RetryStopped(e) => e.error.broadcast_result(),
639            _ => None,
640        }
641    }
642}
643
644impl fmt::Display for Error {
645    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
646        match self {
647            Self::Api(e) => e.fmt(f),
648            Self::Http(e) => e.fmt(f),
649            Self::Decode(e) => e.fmt(f),
650            Self::InvalidRequest(e) => e.fmt(f),
651            Self::InvalidConfig(e) => e.fmt(f),
652            Self::Closed => f.write_str("client closed"),
653            Self::BatchNotSent => f.write_str("batch not sent yet"),
654            Self::BroadcastFailedChannels(e) => e.fmt(f),
655            #[cfg(feature = "client")]
656            Self::BatchFailedCommands(e) => e.fmt(f),
657            Self::RetryStopped(e) => e.fmt(f),
658            Self::Timeout(e) => e.fmt(f),
659            Self::Network(e) => e.fmt(f),
660            Self::Function(e) => e.fmt(f),
661            Self::Payload(e) => e.fmt(f),
662        }
663    }
664}
665
666impl std::error::Error for Error {
667    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
668        match self {
669            Self::Decode(e) => e.source(),
670            Self::Payload(e) => e.source(),
671            Self::Network(e) => Some(&*e.source),
672            Self::Function(e) => Some(&*e.source),
673            Self::RetryStopped(e) => Some(&e.error),
674            _ => None,
675        }
676    }
677}
678
679/// An error inside a result - a channel's in a broadcast, a command's in a
680/// batch - encodes as `{"code": ..., "message": ...}` for a Centrifugo error,
681/// and `{"message": ...}` for any other (spec 3.7).
682impl Serialize for Error {
683    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
684        let mut map = serializer.serialize_map(None)?;
685        if let Self::Api(e) = self {
686            map.serialize_entry("code", &e.code)?;
687            map.serialize_entry("message", &e.message)?;
688        } else {
689            map.serialize_entry("message", &self.to_string())?;
690        }
691        map.end()
692    }
693}
694
695/// Reports whether retrying the call which returned `err` may succeed: the
696/// error came from a temporary condition, not from the request.
697///
698/// Retryable are:
699///
700/// - an [`Error::Api`] Centrifugo marked [`temporary`](ApiError::temporary),
701///   and the internal error (code 100) from Centrifugo versions which did not
702///   mark errors yet;
703/// - a network failure, but a refused TLS certificate, and a timeout - also
704///   the call's own, which a retry needs a new deadline for;
705/// - an [`Error::Http`] with status 429 or 5xx, such as from a proxy in front
706///   of Centrifugo;
707/// - a broadcast or batch with at least one failed part which is retryable -
708///   also inside [`Error::RetryStopped`].
709///
710/// Not retryable are the request's own errors - an unknown channel, a bad
711/// request, [`Error::InvalidRequest`] - a reply which is not Centrifugo's,
712/// refused credentials, [`Error::Closed`], [`Error::InvalidConfig`] - an
713/// endpoint or token a configured function returned and the client cannot
714/// send included - and the errors of the application's `with_endpoint_fn`
715/// and `bearer_token` functions, unless they are I/O errors a retry may fix.
716///
717/// A retryable error does not mean nothing was done: after a timeout, or even
718/// an internal error, Centrifugo may have published already. Retry a
719/// publication only with the same `idempotency_key`, so that it is not
720/// published twice. Retry a broadcast with
721/// [`Client::broadcast_with_retry`](crate::Client::broadcast_with_retry),
722/// which sends again only the channels which may still succeed.
723#[must_use]
724pub fn retryable(err: &Error) -> bool {
725    match err {
726        Error::Api(e) => e.temporary || e.code == ApiError::INTERNAL,
727        Error::Http(e) => {
728            e.status == http::StatusCode::TOO_MANY_REQUESTS || e.status.is_server_error()
729        }
730        Error::Timeout(_) => true,
731        Error::Network(e) => !e.certificate,
732        Error::BroadcastFailedChannels(e) => e.errors().any(|(_, e)| retryable(e)),
733        #[cfg(feature = "client")]
734        Error::BatchFailedCommands(e) => e.failed().iter().any(|c| retryable(&c.error)),
735        Error::RetryStopped(e) => retryable(&e.error),
736        Error::Function(e) => io_retryable(&*e.source),
737        Error::Decode(_)
738        | Error::InvalidRequest(_)
739        | Error::InvalidConfig(_)
740        | Error::Payload(_)
741        | Error::Closed
742        | Error::BatchNotSent => false,
743    }
744}
745
746/// Whether an error of the application's - or one inside it - is an I/O
747/// failure a retry may fix.
748fn io_retryable(err: &(dyn std::error::Error + 'static)) -> bool {
749    use std::io::ErrorKind::{
750        BrokenPipe, ConnectionAborted, ConnectionRefused, ConnectionReset, Interrupted, TimedOut,
751        UnexpectedEof,
752    };
753    for e in chain(err) {
754        if let Some(e) = e.downcast_ref::<Error>() {
755            return retryable(e);
756        }
757        let kind = e.downcast_ref::<std::io::Error>().map(std::io::Error::kind);
758        if let Some(
759            ConnectionRefused | ConnectionReset | ConnectionAborted | BrokenPipe | TimedOut
760            | Interrupted | UnexpectedEof,
761        ) = kind
762        {
763            return true;
764        }
765    }
766    false
767}
768
769/// The errors of `err`'s chain, from `err` itself: by `source`, and into the
770/// error an `io::Error` wraps, which its `source` skips.
771pub(crate) fn chain<'a>(
772    err: &'a (dyn std::error::Error + 'static),
773) -> impl Iterator<Item = &'a (dyn std::error::Error + 'static)> {
774    std::iter::successors(Some(err), |e| {
775        match e
776            .downcast_ref::<std::io::Error>()
777            .and_then(std::io::Error::get_ref)
778        {
779            Some(inner) => Some(inner as &(dyn std::error::Error + 'static)),
780            None => e.source(),
781        }
782    })
783}