use std::collections::BTreeMap;
use std::fmt;
use std::time::Duration;
use crate::vocab::{PreemptReason, ProblemCode, RateLimitType};
pub type Result<T, E = Error> = std::result::Result<T, E>;
type Source = Box<dyn std::error::Error + Send + Sync + 'static>;
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
Api(ApiError),
Validation(ValidationError),
Network(NetworkError),
Timeout(TimeoutError),
Decode(DecodeError),
WebhookVerification(WebhookVerificationError),
Preempted(PreemptedError),
}
impl Error {
pub fn kind(&self) -> &'static str {
match self {
Error::Api(_) => "api",
Error::Validation(_) => "validation",
Error::Network(_) => "network",
Error::Timeout(_) => "timeout",
Error::Decode(_) => "decode",
Error::WebhookVerification(_) => "webhook_verification",
Error::Preempted(_) => "preempted",
}
}
pub fn as_api(&self) -> Option<&ApiError> {
match self {
Error::Api(e) => Some(e),
_ => None,
}
}
pub(crate) fn validation(message: impl Into<String>, param: Option<&str>) -> Self {
Error::Validation(ValidationError {
message: message.into(),
param: param.map(str::to_owned),
})
}
pub(crate) fn network(message: impl Into<String>, source: Option<Source>) -> Self {
Error::Network(NetworkError {
message: message.into(),
source,
})
}
pub(crate) fn timeout(message: impl Into<String>, source: Option<Source>) -> Self {
Error::Timeout(TimeoutError {
message: message.into(),
source,
})
}
pub(crate) fn decode(
message: impl Into<String>,
path: Option<String>,
raw: Option<String>,
source: Option<Source>,
) -> Self {
Error::Decode(DecodeError {
message: message.into(),
path,
raw,
source,
})
}
pub(crate) fn webhook(reason: WebhookVerificationReason, message: impl Into<String>) -> Self {
Error::WebhookVerification(WebhookVerificationError {
reason,
message: message.into(),
})
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Api(e) => e.fmt(f),
Error::Validation(e) => e.fmt(f),
Error::Network(e) => e.fmt(f),
Error::Timeout(e) => e.fmt(f),
Error::Decode(e) => e.fmt(f),
Error::WebhookVerification(e) => e.fmt(f),
Error::Preempted(e) => e.fmt(f),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Network(e) => e.source(),
Error::Timeout(e) => e.source(),
Error::Decode(e) => e.source(),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ApiErrorKind {
ValidationFailed,
CursorInvalid,
CursorMismatch,
Unauthorized,
Forbidden,
NotFound,
RateLimited,
InternalError,
Other,
}
impl ApiErrorKind {
pub fn as_str(&self) -> &'static str {
match self {
ApiErrorKind::ValidationFailed => "validation_failed",
ApiErrorKind::CursorInvalid => "cursor_invalid",
ApiErrorKind::CursorMismatch => "cursor_mismatch",
ApiErrorKind::Unauthorized => "unauthorized",
ApiErrorKind::Forbidden => "forbidden",
ApiErrorKind::NotFound => "not_found",
ApiErrorKind::RateLimited => "rate_limited",
ApiErrorKind::InternalError => "internal_error",
ApiErrorKind::Other => "other",
}
}
pub(crate) fn from_code(code: &ProblemCode) -> Self {
match code {
ProblemCode::ValidationFailed => ApiErrorKind::ValidationFailed,
ProblemCode::CursorInvalid => ApiErrorKind::CursorInvalid,
ProblemCode::CursorMismatch => ApiErrorKind::CursorMismatch,
ProblemCode::Unauthorized => ApiErrorKind::Unauthorized,
ProblemCode::Forbidden => ApiErrorKind::Forbidden,
ProblemCode::NotFound => ApiErrorKind::NotFound,
ProblemCode::RateLimited => ApiErrorKind::RateLimited,
ProblemCode::InternalError => ApiErrorKind::InternalError,
_ => ApiErrorKind::Other,
}
}
pub(crate) fn from_status(status: u16) -> Self {
match status {
400 => ApiErrorKind::ValidationFailed,
401 => ApiErrorKind::Unauthorized,
403 => ApiErrorKind::Forbidden,
404 => ApiErrorKind::NotFound,
429 => ApiErrorKind::RateLimited,
500..=599 => ApiErrorKind::InternalError,
_ => ApiErrorKind::Other,
}
}
}
impl fmt::Display for ApiErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct FieldIssue {
pub field: Option<String>,
pub issue: Option<String>,
pub allowed_values: Option<Vec<String>>,
pub constraints: Option<BTreeMap<String, String>>,
}
pub(crate) struct ApiErrorData {
pub status: u16,
pub code: Option<ProblemCode>,
pub r#type: Option<String>,
pub title: Option<String>,
pub detail: Option<String>,
pub request_id: Option<String>,
pub errors: Vec<FieldIssue>,
pub api_kind: ApiErrorKind,
pub limit_type: Option<RateLimitType>,
pub retry_after: Option<Duration>,
pub raw: Option<String>,
pub message: String,
}
pub struct ApiError(Box<ApiErrorData>);
impl ApiError {
pub(crate) fn new(data: ApiErrorData) -> Self {
ApiError(Box::new(data))
}
pub fn status(&self) -> u16 {
self.0.status
}
pub fn code(&self) -> Option<&ProblemCode> {
self.0.code.as_ref()
}
pub fn r#type(&self) -> Option<&str> {
self.0.r#type.as_deref()
}
pub fn title(&self) -> Option<&str> {
self.0.title.as_deref()
}
pub fn detail(&self) -> Option<&str> {
self.0.detail.as_deref()
}
pub fn request_id(&self) -> Option<&str> {
self.0.request_id.as_deref()
}
pub fn errors(&self) -> &[FieldIssue] {
&self.0.errors
}
pub fn api_kind(&self) -> ApiErrorKind {
self.0.api_kind
}
pub fn limit_type(&self) -> Option<&RateLimitType> {
self.0.limit_type.as_ref()
}
pub fn retry_after(&self) -> Option<Duration> {
self.0.retry_after
}
pub fn raw(&self) -> Option<&str> {
self.0.raw.as_deref()
}
pub fn raw_json(&self) -> Option<&str> {
self.0.raw.as_deref()
}
}
impl fmt::Display for ApiError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0.message)
}
}
impl fmt::Debug for ApiError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ApiError")
.field("status", &self.0.status)
.field("code", &self.0.code)
.field("api_kind", &self.0.api_kind)
.field("title", &self.0.title)
.field("detail", &self.0.detail)
.field("request_id", &self.0.request_id)
.field("errors", &self.0.errors)
.field("limit_type", &self.0.limit_type)
.field("retry_after", &self.0.retry_after)
.field("raw_len", &self.0.raw.as_ref().map(String::len))
.finish()
}
}
impl std::error::Error for ApiError {}
#[derive(Debug, Clone)]
pub struct ValidationError {
message: String,
param: Option<String>,
}
impl ValidationError {
pub fn param(&self) -> Option<&str> {
self.param.as_deref()
}
}
impl fmt::Display for ValidationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for ValidationError {}
#[derive(Debug)]
pub struct NetworkError {
message: String,
source: Option<Source>,
}
impl fmt::Display for NetworkError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for NetworkError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.source.as_ref().map(|e| e.as_ref() as _)
}
}
#[derive(Debug)]
pub struct TimeoutError {
message: String,
source: Option<Source>,
}
impl fmt::Display for TimeoutError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for TimeoutError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.source.as_ref().map(|e| e.as_ref() as _)
}
}
pub struct DecodeError {
message: String,
path: Option<String>,
raw: Option<String>,
source: Option<Source>,
}
impl DecodeError {
pub fn path(&self) -> Option<&str> {
self.path.as_deref()
}
pub fn raw(&self) -> Option<&str> {
self.raw.as_deref()
}
}
impl fmt::Display for DecodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl fmt::Debug for DecodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DecodeError")
.field("message", &self.message)
.field("path", &self.path)
.field("raw_len", &self.raw.as_ref().map(String::len))
.finish()
}
}
impl std::error::Error for DecodeError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.source.as_ref().map(|e| e.as_ref() as _)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum WebhookVerificationReason {
InvalidRawBody,
InvalidSecret,
MissingSignature,
MissingTimestamp,
DuplicateHeader,
NonAsciiHeader,
UnsupportedSignatureScheme,
UnparseableTimestamp,
SignatureMismatch,
TimestampOutsideTolerance,
}
impl WebhookVerificationReason {
pub fn as_str(&self) -> &'static str {
match self {
Self::InvalidRawBody => "invalid_raw_body",
Self::InvalidSecret => "invalid_secret",
Self::MissingSignature => "missing_signature",
Self::MissingTimestamp => "missing_timestamp",
Self::DuplicateHeader => "duplicate_header",
Self::NonAsciiHeader => "non_ascii_header",
Self::UnsupportedSignatureScheme => "unsupported_signature_scheme",
Self::UnparseableTimestamp => "unparseable_timestamp",
Self::SignatureMismatch => "signature_mismatch",
Self::TimestampOutsideTolerance => "timestamp_outside_tolerance",
}
}
}
impl fmt::Display for WebhookVerificationReason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone)]
pub struct WebhookVerificationError {
reason: WebhookVerificationReason,
message: String,
}
impl WebhookVerificationError {
pub fn reason(&self) -> WebhookVerificationReason {
self.reason
}
}
impl fmt::Display for WebhookVerificationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"webhook verification failed ({}): {}",
self.reason, self.message
)
}
}
impl std::error::Error for WebhookVerificationError {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PreemptedError {
reason: PreemptReason,
new_lease_id: Option<String>,
timestamp: Option<i64>,
}
impl PreemptedError {
pub(crate) fn new(
reason: PreemptReason,
new_lease_id: Option<String>,
timestamp: Option<i64>,
) -> Self {
PreemptedError {
reason,
new_lease_id,
timestamp,
}
}
pub fn reason(&self) -> &PreemptReason {
&self.reason
}
pub fn new_lease_id(&self) -> Option<&str> {
self.new_lease_id.as_deref()
}
pub fn timestamp(&self) -> Option<i64> {
self.timestamp
}
}
impl fmt::Display for PreemptedError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.reason {
PreemptReason::ConnectionLimit => write!(
f,
"stream preempted (connection_limit): another connection of this API key took over"
),
PreemptReason::QuotaExceeded => write!(
f,
"stream preempted (quota_exceeded): the WebSocket quota of the current period is used up"
),
_ => write!(f, "stream preempted ({})", self.reason),
}
}
}
impl std::error::Error for PreemptedError {}
impl From<ApiError> for Error {
fn from(e: ApiError) -> Self {
Error::Api(e)
}
}
impl From<PreemptedError> for Error {
fn from(e: PreemptedError) -> Self {
Error::Preempted(e)
}
}