use std::fmt;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error(transparent)]
Api(Box<ApiError>),
#[error(transparent)]
Transport(#[from] TransportError),
#[error(transparent)]
Decode(#[from] DecodeError),
#[error("invalid client configuration: {0}")]
Config(&'static str),
}
impl From<ApiError> for Error {
fn from(error: ApiError) -> Self {
Error::Api(Box::new(error))
}
}
impl Error {
#[must_use]
pub fn status(&self) -> Option<u16> {
match self {
Error::Api(api) => Some(api.status),
_ => None,
}
}
#[must_use]
pub fn problem(&self) -> Option<&Problem> {
match self {
Error::Api(api) => Some(&api.problem),
_ => None,
}
}
#[must_use]
pub fn is_timeout(&self) -> bool {
matches!(self, Error::Transport(t) if t.timed_out)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ApiError {
pub status: u16,
pub problem: Problem,
}
impl ApiError {
#[must_use]
pub fn problem(&self) -> &Problem {
&self.problem
}
#[must_use]
pub fn code(&self) -> Option<&str> {
self.problem.code.as_deref()
}
}
impl fmt::Display for ApiError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"crypto-service API error: HTTP {} {} ({})",
self.status, self.problem.title, self.problem.kind
)
}
}
impl std::error::Error for ApiError {}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Problem {
#[serde(rename = "type", default = "about_blank")]
pub kind: String,
#[serde(default)]
pub title: String,
#[serde(default)]
pub status: u16,
pub detail: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub instance: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub errors: Vec<ValidationError>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reset_seconds: Option<u64>,
#[serde(flatten)]
pub extensions: Map<String, Value>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ValidationError {
pub field: String,
pub message: String,
}
fn about_blank() -> String {
String::from("about:blank")
}
impl Problem {
#[must_use]
pub fn from_body(status: u16, body: &[u8]) -> Self {
match serde_json::from_slice::<Problem>(body) {
Ok(mut problem) => {
if problem.title.is_empty() {
problem.title = reason(status);
}
if problem.status == 0 {
problem.status = status;
}
problem
}
Err(_) => Self::blank(status),
}
}
#[must_use]
pub fn blank(status: u16) -> Self {
Problem {
kind: about_blank(),
title: reason(status),
status,
detail: format!("The server answered {status} without a problem body"),
instance: None,
code: None,
errors: Vec::new(),
limit: None,
reset_seconds: None,
extensions: Map::new(),
}
}
}
fn reason(status: u16) -> String {
http::StatusCode::from_u16(status)
.ok()
.and_then(|code| code.canonical_reason())
.unwrap_or("HTTP error")
.to_owned()
}
#[derive(Debug, thiserror::Error)]
#[error("{message}")]
pub struct TransportError {
pub timed_out: bool,
message: &'static str,
#[source]
source: Option<Box<dyn std::error::Error + Send + Sync + 'static>>,
}
impl TransportError {
pub fn new<E>(source: E, timed_out: bool) -> Self
where
E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
{
TransportError {
timed_out,
message: if timed_out {
"request timed out"
} else {
"network error"
},
source: Some(source.into()),
}
}
pub(crate) fn attempt_timeout() -> Self {
TransportError {
timed_out: true,
message: "request timed out",
source: None,
}
}
pub(crate) fn deadline() -> Self {
TransportError {
timed_out: true,
message: "deadline exceeded",
source: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("response body could not be decoded ({category} error at line {line}, column {column})")]
pub struct DecodeError {
category: &'static str,
line: usize,
column: usize,
}
impl DecodeError {
#[must_use]
pub fn line(&self) -> usize {
self.line
}
#[must_use]
pub fn column(&self) -> usize {
self.column
}
}
impl From<serde_json::Error> for DecodeError {
fn from(error: serde_json::Error) -> Self {
use serde_json::error::Category;
DecodeError {
category: match error.classify() {
Category::Io => "io",
Category::Syntax => "syntax",
Category::Data => "data",
Category::Eof => "eof",
},
line: error.line(),
column: error.column(),
}
}
}
#[cfg(test)]
mod tests;