use std::{error::Error as StdError, fmt, num::ParseIntError, sync::Arc};
use bytes::{BufMut, Bytes};
use serde_json::{from_slice as from_json_slice, Value as JsonValue};
use thiserror::Error;
use super::{EndpointError, MatrixVersion, OutgoingResponse};
#[allow(clippy::exhaustive_structs)]
#[derive(Clone, Debug)]
pub struct MatrixError {
pub status_code: http::StatusCode,
pub body: MatrixErrorBody,
}
impl fmt::Display for MatrixError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let status_code = self.status_code.as_u16();
match &self.body {
MatrixErrorBody::Json(json) => write!(f, "[{status_code}] {json}"),
MatrixErrorBody::NotJson { .. } => write!(f, "[{status_code}] <non-json bytes>"),
}
}
}
impl StdError for MatrixError {}
impl OutgoingResponse for MatrixError {
fn try_into_http_response<T: Default + BufMut>(
self,
) -> Result<http::Response<T>, IntoHttpError> {
http::Response::builder()
.header(http::header::CONTENT_TYPE, "application/json")
.status(self.status_code)
.body(match self.body {
MatrixErrorBody::Json(json) => crate::serde::json_to_buf(&json)?,
MatrixErrorBody::NotJson { .. } => {
return Err(IntoHttpError::Json(serde::ser::Error::custom(
"attempted to serialize MatrixErrorBody::NotJson",
)));
}
})
.map_err(Into::into)
}
}
impl EndpointError for MatrixError {
fn from_http_response<T: AsRef<[u8]>>(response: http::Response<T>) -> Self {
let status_code = response.status();
let body = MatrixErrorBody::from_bytes(response.body().as_ref());
Self { status_code, body }
}
}
#[derive(Clone, Debug)]
#[allow(clippy::exhaustive_enums)]
pub enum MatrixErrorBody {
Json(JsonValue),
NotJson {
bytes: Bytes,
deserialization_error: Arc<serde_json::Error>,
},
}
impl MatrixErrorBody {
pub fn from_bytes(body_bytes: &[u8]) -> Self {
match from_json_slice(body_bytes) {
Ok(json) => MatrixErrorBody::Json(json),
Err(e) => MatrixErrorBody::NotJson {
bytes: Bytes::copy_from_slice(body_bytes),
deserialization_error: Arc::new(e),
},
}
}
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum IntoHttpError {
#[error("no access token given, but this endpoint requires one")]
NeedsAuthentication,
#[error(
"endpoint was not supported by server-reported versions, \
but no unstable path to fall back to was defined"
)]
NoUnstablePath,
#[error("could not create any path variant for endpoint, as it was removed in version {0}")]
EndpointRemoved(MatrixVersion),
#[error("JSON serialization failed: {0}")]
Json(#[from] serde_json::Error),
#[error("query parameter serialization failed: {0}")]
Query(#[from] serde_html_form::ser::Error),
#[error("header serialization failed: {0}")]
Header(#[from] HeaderSerializationError),
#[error("HTTP request construction failed: {0}")]
Http(#[from] http::Error),
}
impl From<http::header::InvalidHeaderValue> for IntoHttpError {
fn from(value: http::header::InvalidHeaderValue) -> Self {
Self::Header(value.into())
}
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum FromHttpRequestError {
#[error("deserialization failed: {0}")]
Deserialization(DeserializationError),
#[error("http method mismatch: expected {expected}, received: {received}")]
MethodMismatch {
expected: http::method::Method,
received: http::method::Method,
},
}
impl<T> From<T> for FromHttpRequestError
where
T: Into<DeserializationError>,
{
fn from(err: T) -> Self {
Self::Deserialization(err.into())
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum FromHttpResponseError<E> {
Deserialization(DeserializationError),
Server(E),
}
impl<E> FromHttpResponseError<E> {
pub fn map<F>(self, f: impl FnOnce(E) -> F) -> FromHttpResponseError<F> {
match self {
Self::Deserialization(d) => FromHttpResponseError::Deserialization(d),
Self::Server(s) => FromHttpResponseError::Server(f(s)),
}
}
}
impl<E, F> FromHttpResponseError<Result<E, F>> {
pub fn transpose(self) -> Result<FromHttpResponseError<E>, F> {
match self {
Self::Deserialization(d) => Ok(FromHttpResponseError::Deserialization(d)),
Self::Server(s) => s.map(FromHttpResponseError::Server),
}
}
}
impl<E: fmt::Display> fmt::Display for FromHttpResponseError<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Deserialization(err) => write!(f, "deserialization failed: {err}"),
Self::Server(err) => write!(f, "the server returned an error: {err}"),
}
}
}
impl<E, T> From<T> for FromHttpResponseError<E>
where
T: Into<DeserializationError>,
{
fn from(err: T) -> Self {
Self::Deserialization(err.into())
}
}
impl<E: StdError> StdError for FromHttpResponseError<E> {}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum DeserializationError {
#[error(transparent)]
Utf8(#[from] std::str::Utf8Error),
#[error(transparent)]
Json(#[from] serde_json::Error),
#[error(transparent)]
Query(#[from] serde_html_form::de::Error),
#[error(transparent)]
Ident(#[from] crate::IdParseError),
#[error(transparent)]
Header(#[from] HeaderDeserializationError),
#[error(transparent)]
MultipartMixed(#[from] MultipartMixedDeserializationError),
}
impl From<std::convert::Infallible> for DeserializationError {
fn from(err: std::convert::Infallible) -> Self {
match err {}
}
}
impl From<http::header::ToStrError> for DeserializationError {
fn from(err: http::header::ToStrError) -> Self {
Self::Header(HeaderDeserializationError::ToStrError(err))
}
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum HeaderDeserializationError {
#[error("{0}")]
ToStrError(#[from] http::header::ToStrError),
#[error("{0}")]
ParseIntError(#[from] ParseIntError),
#[error("failed to parse HTTP date")]
InvalidHttpDate,
#[error("missing header `{0}`")]
MissingHeader(String),
#[error("invalid header: {0}")]
InvalidHeader(Box<dyn std::error::Error + Send + Sync + 'static>),
#[error(
"The {header} header was received with an unexpected value, \
expected {expected}, received {unexpected}"
)]
InvalidHeaderValue {
header: String,
expected: String,
unexpected: String,
},
#[error(
"The `Content-Type` header for a `multipart/mixed` response is missing the `boundary` attribute"
)]
MissingMultipartBoundary,
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum MultipartMixedDeserializationError {
#[error(
"multipart/mixed response does not have enough body parts, \
expected {expected}, found {found}"
)]
MissingBodyParts {
expected: usize,
found: usize,
},
#[error("multipart/mixed body part is missing separator between headers and content")]
MissingBodyPartInnerSeparator,
#[error("multipart/mixed body part header is missing separator between name and value")]
MissingHeaderSeparator,
#[error("invalid multipart/mixed header: {0}")]
InvalidHeader(Box<dyn std::error::Error + Send + Sync + 'static>),
}
#[derive(Debug)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct UnknownVersionError;
impl fmt::Display for UnknownVersionError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "version string was unknown")
}
}
impl StdError for UnknownVersionError {}
#[derive(Debug)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct IncorrectArgumentCount {
pub expected: usize,
pub got: usize,
}
impl fmt::Display for IncorrectArgumentCount {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "incorrect path argument count, expected {}, got {}", self.expected, self.got)
}
}
impl StdError for IncorrectArgumentCount {}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum HeaderSerializationError {
#[error(transparent)]
ToHeaderValue(#[from] http::header::InvalidHeaderValue),
#[error("invalid HTTP date")]
InvalidHttpDate,
}