use std::fmt;
use std::io;
use crate::types::{Bucket, Object};
#[derive(Debug)]
pub struct Error {
inner: Box<ErrorInner>,
}
#[derive(Debug)]
struct ErrorInner {
kind: ErrorKind,
retryable: Option<bool>,
message: String,
bucket: Option<Bucket>,
object: Option<Object>,
source: Option<Box<dyn std::error::Error + Send + Sync>>,
}
impl Error {
pub fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
Self {
inner: Box::new(ErrorInner {
kind,
retryable: None,
message: message.into(),
bucket: None,
object: None,
source: None,
}),
}
}
pub fn with_source(
mut self,
source: impl Into<Box<dyn std::error::Error + Send + Sync>>,
) -> Self {
self.inner.source = Some(source.into());
self
}
pub fn with_bucket(mut self, bucket: Bucket) -> Self {
self.inner.bucket = Some(bucket);
self
}
pub fn with_object(mut self, object: Object) -> Self {
self.inner.object = Some(object);
self
}
pub fn kind(&self) -> ErrorKind {
self.inner.kind
}
pub fn is_retryable(&self) -> bool {
self.inner.retryable.unwrap_or(matches!(
self.kind(),
ErrorKind::TooManyRequests | ErrorKind::Protocol | ErrorKind::Io
))
}
pub(crate) fn with_retryable(mut self, retryable: bool) -> Self {
self.inner.retryable = Some(retryable);
self
}
pub fn is(&self, kind: ErrorKind) -> bool {
self.inner.kind == kind
}
pub fn is_canceled(&self) -> bool {
self.inner.kind == ErrorKind::Canceled
}
pub fn bucket(&self) -> Option<&Bucket> {
self.inner.bucket.as_ref()
}
pub fn object(&self) -> Option<&Object> {
self.inner.object.as_ref()
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {}", self.inner.kind, self.inner.message)
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.inner.source.as_deref().map(|e| e as _)
}
}
impl From<io::Error> for Error {
fn from(e: io::Error) -> Self {
if e.get_ref().is_some_and(|inner| inner.is::<Error>()) {
if let Some(inner) = e.into_inner()
&& let Ok(orig) = inner.downcast::<Error>()
{
return *orig;
}
return Self::new(ErrorKind::Io, "io error");
}
let kind = if e.kind() == io::ErrorKind::Interrupted {
ErrorKind::Canceled
} else {
ErrorKind::Io
};
Self::new(kind, e.to_string()).with_source(e)
}
}
impl From<Error> for io::Error {
fn from(e: Error) -> Self {
if e.is_canceled() {
io::Error::new(io::ErrorKind::Interrupted, e)
} else {
io::Error::other(e)
}
}
}
impl From<tokio::task::JoinError> for Error {
fn from(e: tokio::task::JoinError) -> Self {
if e.is_cancelled() {
Self::new(ErrorKind::Canceled, "task canceled").with_source(e)
} else {
std::panic::resume_unwind(e.into_panic())
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
InvalidTlsIdentity,
MetadataInvalid,
TooManyRequests,
BandwidthLimitExceeded,
StorageLimitExceeded,
SegmentsLimitExceeded,
PermissionDenied,
BucketNameInvalid,
BucketAlreadyExists,
BucketNotEmpty,
BucketNotFound,
ObjectKeyInvalid,
ObjectNotFound,
UploadDone,
UploadIdInvalid,
Canceled,
InvalidGrant,
DecryptionFailed,
Protocol,
Io,
EdgeAuthDialFailed,
EdgeRegisterAccessFailed,
}
impl fmt::Display for ErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::TooManyRequests => "too many requests",
Self::BandwidthLimitExceeded => "bandwidth limit exceeded",
Self::StorageLimitExceeded => "storage limit exceeded",
Self::SegmentsLimitExceeded => "segments limit exceeded",
Self::PermissionDenied => "permission denied",
Self::BucketNameInvalid => "bucket name invalid",
Self::BucketAlreadyExists => "bucket already exists",
Self::BucketNotEmpty => "bucket not empty",
Self::BucketNotFound => "bucket not found",
Self::ObjectKeyInvalid => "object key invalid",
Self::ObjectNotFound => "object not found",
Self::UploadDone => "upload done",
Self::UploadIdInvalid => "upload ID invalid",
Self::Canceled => "canceled",
Self::InvalidGrant => "invalid grant",
Self::DecryptionFailed => "decryption failed",
Self::Protocol => "protocol",
Self::MetadataInvalid => "invalid custom metadata",
Self::InvalidTlsIdentity => "invalid TLS identity",
Self::Io => "i/o",
Self::EdgeAuthDialFailed => "dial to auth service failed",
Self::EdgeRegisterAccessFailed => "register access for edge service failed",
})
}
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
#[cfg(test)]
mod tests {
use super::*;
use std::time::SystemTime;
#[test]
fn kind_helpers() {
let e = Error::new(ErrorKind::Canceled, "stopped");
assert!(e.is_canceled());
assert!(e.is(ErrorKind::Canceled));
assert_eq!(e.kind(), ErrorKind::Canceled);
assert!(e.bucket().is_none());
assert!(e.object().is_none());
}
#[test]
fn create_bucket_dual_return() {
let bucket = Bucket {
name: "logs".into(),
created: SystemTime::UNIX_EPOCH,
};
let e = Error::new(
ErrorKind::BucketAlreadyExists,
"bucket already exists (\"logs\")",
)
.with_bucket(bucket.clone());
assert_eq!(e.kind(), ErrorKind::BucketAlreadyExists);
assert_eq!(e.bucket().map(|b| b.name.as_str()), Some("logs"));
}
#[test]
fn from_interrupted_io_is_canceled() {
let io = io::Error::new(io::ErrorKind::Interrupted, "abort");
let e = Error::from(io);
assert!(e.is_canceled());
}
#[test]
fn from_other_io_is_io() {
let io = io::Error::other("disk");
let e = Error::from(io);
assert_eq!(e.kind(), ErrorKind::Io);
}
#[test]
fn display_matches_go_phrasing() {
let e = Error::new(ErrorKind::BucketNotFound, "bucket not found (\"x\")");
assert_eq!(e.to_string(), "bucket not found: bucket not found (\"x\")");
}
#[test]
fn no_invalid_handle_kind() {
let names = format!("{:?}", ErrorKind::Protocol);
assert!(!names.to_lowercase().contains("handle"));
}
}