1use 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
14pub type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
17
18pub(crate) type Source = Arc<dyn std::error::Error + Send + Sync + 'static>;
21
22#[derive(Debug, Clone)]
47#[non_exhaustive]
48pub enum Error {
49 Api(ApiError),
51 Http(Box<HttpError>),
55 Decode(DecodeError),
58 InvalidRequest(InvalidRequestError),
60 InvalidConfig(InvalidConfigError),
71 Closed,
73 BatchNotSent,
75 BroadcastFailedChannels(Box<BroadcastFailedChannelsError>),
78 #[cfg(feature = "client")]
81 BatchFailedCommands(Box<BatchFailedCommandsError>),
82 RetryStopped(Box<RetryStoppedError>),
85 Timeout(TimeoutError),
88 Network(NetworkError),
90 Function(FunctionError),
96 Payload(PayloadError),
99}
100
101#[derive(Debug, Clone, PartialEq, Eq)]
110#[non_exhaustive]
111pub struct ApiError {
112 pub code: u32,
114 pub message: String,
116 pub temporary: bool,
122 pro_method: Option<&'static str>,
125}
126
127impl ApiError {
128 pub const INTERNAL: u32 = 100;
130 pub const UNKNOWN_CHANNEL: u32 = 102;
132 pub const NOT_FOUND: u32 = 104;
135 pub const BAD_REQUEST: u32 = 107;
137 pub const NOT_AVAILABLE: u32 = 108;
139 pub const TOO_MANY_REQUESTS: u32 = 111;
141 pub const UNRECOVERABLE_POSITION: u32 = 112;
143 pub const CONFLICT: u32 = 113;
145
146 #[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 #[must_use]
159 pub fn temporary(mut self, temporary: bool) -> Self {
160 self.temporary = temporary;
161 self
162 }
163
164 #[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#[derive(Debug, Clone)]
198#[non_exhaustive]
199pub struct HttpError {
200 pub status: http::StatusCode,
202 pub body: Bytes,
204 pub headers: http::HeaderMap,
207 pro_method: Option<&'static str>,
210}
211
212impl HttpError {
213 #[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 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#[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#[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 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#[derive(Debug, Clone)]
355pub struct InvalidRequestError {
356 method: &'static str,
357 problem: String,
358 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 #[must_use]
379 pub fn method(&self) -> &'static str {
380 self.method
381 }
382
383 #[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#[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#[derive(Debug, Clone)]
419pub struct TimeoutError {
420 pub(crate) method: Option<&'static str>,
421 pub(crate) unsent: bool,
423}
424
425impl TimeoutError {
426 #[must_use]
428 pub fn method(&self) -> Option<&'static str> {
429 self.method
430 }
431
432 #[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#[derive(Debug, Clone)]
459pub struct NetworkError {
460 method: &'static str,
461 source: Source,
462 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 #[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 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#[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 #[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#[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 #[must_use]
557 pub fn reason(&self) -> &(dyn std::error::Error + Send + Sync + 'static) {
558 &*self.reason
559 }
560
561 #[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 #[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 #[must_use]
616 pub fn is_unauthorized(&self) -> bool {
617 matches!(self, Self::Http(e) if e.status == http::StatusCode::UNAUTHORIZED)
618 }
619
620 #[must_use]
622 pub fn is_timeout(&self) -> bool {
623 matches!(self, Self::Timeout(_))
624 }
625
626 #[must_use]
628 pub fn is_retryable(&self) -> bool {
629 retryable(self)
630 }
631
632 #[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
679impl 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#[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
746fn 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
769pub(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}