use std::fmt;
use std::sync::Arc;
use bytes::Bytes;
use serde::ser::SerializeMap;
use serde::{Serialize, Serializer};
#[cfg(feature = "client")]
use crate::batch::BatchFailedCommandsError;
use crate::broadcast::BroadcastFailedChannelsError;
pub type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
pub(crate) type Source = Arc<dyn std::error::Error + Send + Sync + 'static>;
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Error {
Api(ApiError),
Http(Box<HttpError>),
Decode(DecodeError),
InvalidRequest(InvalidRequestError),
InvalidConfig(InvalidConfigError),
Closed,
BatchNotSent,
BroadcastFailedChannels(Box<BroadcastFailedChannelsError>),
#[cfg(feature = "client")]
BatchFailedCommands(Box<BatchFailedCommandsError>),
RetryStopped(Box<RetryStoppedError>),
Timeout(TimeoutError),
Network(NetworkError),
Function(FunctionError),
Payload(PayloadError),
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ApiError {
pub code: u32,
pub message: String,
pub temporary: bool,
pro_method: Option<&'static str>,
}
impl ApiError {
pub const INTERNAL: u32 = 100;
pub const UNKNOWN_CHANNEL: u32 = 102;
pub const NOT_FOUND: u32 = 104;
pub const BAD_REQUEST: u32 = 107;
pub const NOT_AVAILABLE: u32 = 108;
pub const TOO_MANY_REQUESTS: u32 = 111;
pub const UNRECOVERABLE_POSITION: u32 = 112;
pub const CONFLICT: u32 = 113;
#[must_use]
pub fn new(code: u32, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
temporary: false,
pro_method: None,
}
}
#[must_use]
pub fn temporary(mut self, temporary: bool) -> Self {
self.temporary = temporary;
self
}
#[cfg(feature = "client")]
pub(crate) fn in_batch(mut self, method: &'static str) -> Self {
if self.code == Self::NOT_FOUND && crate::request::is_pro(method) {
self.pro_method = Some(method);
}
self
}
}
impl fmt::Display for ApiError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let message = if self.message.is_empty() {
"server error"
} else {
&self.message
};
write!(f, "{message} (code {})", self.code)?;
if let Some(m) = self.pro_method {
write!(
f,
" ({m} is a Centrifugo PRO method: is the server Centrifugo OSS?)"
)?;
}
Ok(())
}
}
impl std::error::Error for ApiError {}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct HttpError {
pub status: http::StatusCode,
pub body: Bytes,
pub headers: http::HeaderMap,
pro_method: Option<&'static str>,
}
impl HttpError {
#[must_use]
pub fn new(status: http::StatusCode, headers: http::HeaderMap, body: impl Into<Bytes>) -> Self {
Self {
status,
body: body.into(),
headers,
pro_method: None,
}
}
#[cfg(feature = "client")]
pub(crate) fn with_pro_method(mut self, method: Option<&'static str>) -> Self {
self.pro_method = method;
self
}
}
impl fmt::Display for HttpError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "unexpected HTTP status {}", self.status.as_u16())?;
let code = self.status.as_u16();
if self.status.is_redirection() {
f.write_str(" (a redirect, which the client does not follow: check api_endpoint's scheme, http or https, and its path)")?;
} else if code == 404 {
match self.pro_method {
Some(m) => write!(
f,
" ({m} is a Centrifugo PRO method: if other methods work, the server is Centrifugo OSS)"
)?,
None => f.write_str(
" (is api_endpoint the API base URL, such as http://localhost:8000/api?)",
)?,
}
} else if code == 401 {
f.write_str(" (check the credentials: api_key or bearer_token)")?;
}
if !self.body.is_empty() {
write!(f, ": {}", String::from_utf8_lossy(&self.body))?;
}
Ok(())
}
}
impl std::error::Error for HttpError {}
#[derive(Debug, Clone)]
pub struct DecodeError {
message: String,
source: Option<Source>,
}
#[cfg(feature = "client")]
impl DecodeError {
pub(crate) fn json(err: serde_json::Error) -> Self {
Self {
message: err.to_string(),
source: Some(Arc::new(err)),
}
}
pub(crate) fn message(message: impl Into<String>) -> Self {
Self {
message: message.into(),
source: None,
}
}
}
impl fmt::Display for DecodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "decoding the reply: {}", self.message)
}
}
impl std::error::Error for DecodeError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.source.as_deref().map(|e| e as _)
}
}
#[derive(Debug, Clone)]
pub struct PayloadError {
encode: bool,
source: Option<Source>,
}
impl PayloadError {
pub(crate) fn encode(err: serde_json::Error) -> Self {
Self {
encode: true,
source: Some(Arc::new(err)),
}
}
pub(crate) fn decode(err: serde_json::Error) -> Self {
Self {
encode: false,
source: Some(Arc::new(err)),
}
}
pub(crate) fn missing() -> Self {
Self {
encode: false,
source: None,
}
}
}
impl fmt::Display for PayloadError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(if self.encode {
"encoding the payload: "
} else {
"decoding the payload: "
})?;
match &self.source {
Some(e) => e.fmt(f),
None => f.write_str("no payload"),
}
}
}
impl std::error::Error for PayloadError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.source.as_deref().map(|e| e as _)
}
}
#[derive(Debug, Clone)]
pub struct InvalidRequestError {
method: &'static str,
problem: String,
command: Option<usize>,
}
impl InvalidRequestError {
pub(crate) fn new(method: &'static str, problem: impl Into<String>) -> Self {
Self {
method,
problem: problem.into(),
command: None,
}
}
#[cfg(feature = "client")]
pub(crate) fn in_command(mut self, index: usize) -> Self {
self.command = Some(index);
self
}
#[must_use]
pub fn method(&self) -> &'static str {
self.method
}
#[must_use]
pub fn command(&self) -> Option<usize> {
self.command
}
}
impl fmt::Display for InvalidRequestError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(i) = self.command {
write!(f, "batch command #{i}: ")?;
}
write!(f, "invalid {} request: {}", self.method, self.problem)
}
}
impl std::error::Error for InvalidRequestError {}
#[derive(Debug, Clone)]
pub struct InvalidConfigError(pub(crate) String);
impl fmt::Display for InvalidConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "invalid config: {}", self.0)
}
}
impl std::error::Error for InvalidConfigError {}
#[derive(Debug, Clone)]
pub struct TimeoutError {
pub(crate) method: Option<&'static str>,
pub(crate) unsent: bool,
}
impl TimeoutError {
#[must_use]
pub fn method(&self) -> Option<&'static str> {
self.method
}
#[must_use]
pub fn unsent(&self) -> bool {
self.unsent
}
}
impl fmt::Display for TimeoutError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(m) = self.method {
write!(f, "{m}: ")?;
}
f.write_str("timed out")?;
if self.unsent {
f.write_str(" before it was sent")?;
}
Ok(())
}
}
impl std::error::Error for TimeoutError {}
#[derive(Debug, Clone)]
pub struct NetworkError {
method: &'static str,
source: Source,
certificate: bool,
}
impl NetworkError {
#[cfg(feature = "client")]
pub(crate) fn new(method: &'static str, source: Source, certificate: bool) -> Self {
Self {
method,
source,
certificate,
}
}
#[must_use]
pub fn is_certificate(&self) -> bool {
self.certificate
}
}
impl fmt::Display for NetworkError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {}", self.method, self.source)?;
let mut cause = self.source.source();
while let Some(c) = cause {
write!(f, ": {c}")?;
cause = c.source();
}
Ok(())
}
}
impl std::error::Error for NetworkError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&*self.source)
}
}
#[derive(Debug, Clone)]
pub struct FunctionError {
function: &'static str,
source: Source,
}
impl FunctionError {
#[cfg(feature = "client")]
pub(crate) fn new(function: &'static str, source: Source) -> Self {
Self { function, source }
}
#[must_use]
pub fn function(&self) -> &'static str {
self.function
}
}
impl fmt::Display for FunctionError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {}", self.function, self.source)
}
}
impl std::error::Error for FunctionError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&*self.source)
}
}
#[derive(Debug, Clone)]
pub struct RetryStoppedError {
reason: Source,
error: Error,
}
impl RetryStoppedError {
#[cfg(feature = "client")]
pub(crate) fn new(reason: Source, error: Error) -> Self {
Self { reason, error }
}
#[must_use]
pub fn reason(&self) -> &(dyn std::error::Error + Send + Sync + 'static) {
&*self.reason
}
#[must_use]
pub fn error(&self) -> &Error {
&self.error
}
}
impl fmt::Display for RetryStoppedError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"broadcast retries stopped: {}; {}",
self.reason, self.error
)
}
}
impl std::error::Error for RetryStoppedError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.error)
}
}
impl Error {
#[cfg(feature = "client")]
pub(crate) fn invalid_config(message: impl Into<String>) -> Self {
Self::InvalidConfig(InvalidConfigError(message.into()))
}
pub(crate) fn invalid_request(method: &'static str, problem: impl Into<String>) -> Self {
Self::InvalidRequest(InvalidRequestError::new(method, problem))
}
#[cfg(feature = "client")]
pub(crate) fn timeout(method: &'static str) -> Self {
Self::Timeout(TimeoutError {
method: Some(method),
unsent: false,
})
}
#[must_use]
pub fn api_code(&self) -> Option<u32> {
match self {
Self::Api(e) => Some(e.code),
_ => None,
}
}
#[must_use]
pub fn is_unauthorized(&self) -> bool {
matches!(self, Self::Http(e) if e.status == http::StatusCode::UNAUTHORIZED)
}
#[must_use]
pub fn is_timeout(&self) -> bool {
matches!(self, Self::Timeout(_))
}
#[must_use]
pub fn is_retryable(&self) -> bool {
retryable(self)
}
#[must_use]
pub fn broadcast_result(&self) -> Option<&crate::BroadcastResult> {
match self {
Self::BroadcastFailedChannels(e) => Some(e.result()),
Self::RetryStopped(e) => e.error.broadcast_result(),
_ => None,
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Api(e) => e.fmt(f),
Self::Http(e) => e.fmt(f),
Self::Decode(e) => e.fmt(f),
Self::InvalidRequest(e) => e.fmt(f),
Self::InvalidConfig(e) => e.fmt(f),
Self::Closed => f.write_str("client closed"),
Self::BatchNotSent => f.write_str("batch not sent yet"),
Self::BroadcastFailedChannels(e) => e.fmt(f),
#[cfg(feature = "client")]
Self::BatchFailedCommands(e) => e.fmt(f),
Self::RetryStopped(e) => e.fmt(f),
Self::Timeout(e) => e.fmt(f),
Self::Network(e) => e.fmt(f),
Self::Function(e) => e.fmt(f),
Self::Payload(e) => e.fmt(f),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Decode(e) => e.source(),
Self::Payload(e) => e.source(),
Self::Network(e) => Some(&*e.source),
Self::Function(e) => Some(&*e.source),
Self::RetryStopped(e) => Some(&e.error),
_ => None,
}
}
}
impl Serialize for Error {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut map = serializer.serialize_map(None)?;
if let Self::Api(e) = self {
map.serialize_entry("code", &e.code)?;
map.serialize_entry("message", &e.message)?;
} else {
map.serialize_entry("message", &self.to_string())?;
}
map.end()
}
}
#[must_use]
pub fn retryable(err: &Error) -> bool {
match err {
Error::Api(e) => e.temporary || e.code == ApiError::INTERNAL,
Error::Http(e) => {
e.status == http::StatusCode::TOO_MANY_REQUESTS || e.status.is_server_error()
}
Error::Timeout(_) => true,
Error::Network(e) => !e.certificate,
Error::BroadcastFailedChannels(e) => e.errors().any(|(_, e)| retryable(e)),
#[cfg(feature = "client")]
Error::BatchFailedCommands(e) => e.failed().iter().any(|c| retryable(&c.error)),
Error::RetryStopped(e) => retryable(&e.error),
Error::Function(e) => io_retryable(&*e.source),
Error::Decode(_)
| Error::InvalidRequest(_)
| Error::InvalidConfig(_)
| Error::Payload(_)
| Error::Closed
| Error::BatchNotSent => false,
}
}
fn io_retryable(err: &(dyn std::error::Error + 'static)) -> bool {
use std::io::ErrorKind::{
BrokenPipe, ConnectionAborted, ConnectionRefused, ConnectionReset, Interrupted, TimedOut,
UnexpectedEof,
};
for e in chain(err) {
if let Some(e) = e.downcast_ref::<Error>() {
return retryable(e);
}
let kind = e.downcast_ref::<std::io::Error>().map(std::io::Error::kind);
if let Some(
ConnectionRefused | ConnectionReset | ConnectionAborted | BrokenPipe | TimedOut
| Interrupted | UnexpectedEof,
) = kind
{
return true;
}
}
false
}
pub(crate) fn chain<'a>(
err: &'a (dyn std::error::Error + 'static),
) -> impl Iterator<Item = &'a (dyn std::error::Error + 'static)> {
std::iter::successors(Some(err), |e| {
match e
.downcast_ref::<std::io::Error>()
.and_then(std::io::Error::get_ref)
{
Some(inner) => Some(inner as &(dyn std::error::Error + 'static)),
None => e.source(),
}
})
}