objectstore_server/endpoints/
common.rs1use std::borrow::Cow;
4use std::error::Error;
5
6use axum::Json;
7use axum::http::StatusCode;
8use axum::response::{IntoResponse, Response};
9use http::HeaderValue;
10use objectstore_service::error::{Error as ServiceError, ErrorKind as ServiceErrorKind};
11use objectstore_types::api::ApiErrorResponse;
12use thiserror::Error;
13
14use crate::auth::AuthError;
15use crate::extractors::batch::BatchError;
16use crate::rate_limits::LimitExceeded;
17
18#[derive(Debug, Error)]
20pub enum ApiError {
21 #[error("client error: {context}")]
23 Client {
24 context: Cow<'static, str>,
26 #[source]
28 cause: Option<Box<dyn Error + Send + Sync>>,
29 },
30
31 #[error("{0}")]
33 Conflict(Cow<'static, str>),
34
35 #[error("auth error: {0}")]
37 Auth(#[from] AuthError),
38
39 #[error("service error: {0}")]
41 Service(#[from] ServiceError),
42
43 #[error("batch error: {0}")]
45 Batch(#[from] BatchError),
46
47 #[error("internal error: {context}")]
49 Internal {
50 context: Cow<'static, str>,
52 #[source]
54 cause: Option<Box<dyn Error + Send + Sync>>,
55 },
56}
57
58impl ApiError {
59 pub fn map_client<E>(context: impl Into<Cow<'static, str>>, cause: E) -> Self
61 where
62 E: Error + Send + Sync + 'static,
63 {
64 Self::Client {
65 context: context.into(),
66 cause: Some(Box::new(cause)),
67 }
68 }
69
70 pub fn client(context: impl Into<Cow<'static, str>>) -> Self {
72 Self::Client {
73 context: context.into(),
74 cause: None,
75 }
76 }
77
78 pub fn conflict(context: impl Into<Cow<'static, str>>) -> Self {
80 Self::Conflict(context.into())
81 }
82
83 pub fn internal<E>(context: impl Into<Cow<'static, str>>, cause: E) -> Self
85 where
86 E: Error + Send + Sync + 'static,
87 {
88 Self::Internal {
89 context: context.into(),
90 cause: Some(Box::new(cause)),
91 }
92 }
93
94 pub fn status(&self) -> StatusCode {
96 match &self {
97 ApiError::Client { .. } => StatusCode::BAD_REQUEST,
98 ApiError::Conflict(_) => StatusCode::CONFLICT,
99
100 ApiError::Batch(error) => error.status(),
101
102 ApiError::Auth(AuthError::BadRequest(_)) => StatusCode::BAD_REQUEST,
103 ApiError::Auth(AuthError::ValidationFailure(_))
104 | ApiError::Auth(AuthError::VerificationFailure) => StatusCode::UNAUTHORIZED,
105 ApiError::Auth(AuthError::UnknownKey) => StatusCode::UNAUTHORIZED,
106 ApiError::Auth(AuthError::UnsupportedPresignedMethod) => StatusCode::FORBIDDEN,
107 ApiError::Auth(AuthError::NotPermitted) => StatusCode::FORBIDDEN,
108 ApiError::Auth(AuthError::InternalError(_)) => StatusCode::INTERNAL_SERVER_ERROR,
109
110 ApiError::Service(error) => match error.kind() {
111 ServiceErrorKind::InvalidMetadata
112 | ServiceErrorKind::InvalidUploadSessionToken
113 | ServiceErrorKind::ClientStream
114 | ServiceErrorKind::ChunkExceedsUploadLength { .. }
115 | ServiceErrorKind::ChunkTooSmall { .. } => StatusCode::BAD_REQUEST,
116 ServiceErrorKind::UnknownUploadSession => StatusCode::NOT_FOUND,
117 ServiceErrorKind::RangeNotSatisfiable { .. } => StatusCode::RANGE_NOT_SATISFIABLE,
118 ServiceErrorKind::UploadOffsetMismatch { .. } => StatusCode::CONFLICT,
119 ServiceErrorKind::UploadSessionGone => StatusCode::GONE,
120 ServiceErrorKind::AtCapacity => LimitExceeded::Capacity.status(),
121 ServiceErrorKind::Unsupported => StatusCode::NOT_IMPLEMENTED,
122 ServiceErrorKind::BackendRateLimited => StatusCode::TOO_MANY_REQUESTS,
123 ServiceErrorKind::BackendTimeout | ServiceErrorKind::BackendUnavailable => {
124 StatusCode::SERVICE_UNAVAILABLE
125 }
126 ServiceErrorKind::BackendFailure
127 | ServiceErrorKind::CorruptData
128 | ServiceErrorKind::Panic
129 | ServiceErrorKind::UnexpectedTombstone
130 | ServiceErrorKind::Internal => StatusCode::INTERNAL_SERVER_ERROR,
131 },
132
133 ApiError::Internal { .. } => StatusCode::INTERNAL_SERVER_ERROR,
134 }
135 }
136
137 pub fn capture(&self) {
142 if matches!(
144 self,
145 ApiError::Service(_) | ApiError::Batch(BatchError::RateLimited(_))
146 ) {
147 return;
148 }
149
150 if self.status().is_server_error() {
151 objectstore_log::error!(!!self, "error handling request");
152 }
153 }
154}
155
156impl IntoResponse for ApiError {
157 fn into_response(self) -> Response {
158 if let ApiError::Service(e) = &self
159 && e.kind() == ServiceErrorKind::AtCapacity
160 {
161 return LimitExceeded::Capacity.into_response();
162 }
163
164 self.capture();
165 let body = ApiErrorResponse::from_error(&self);
166 (self.status(), Json(body)).into_response()
167 }
168}
169
170impl From<crate::usecases::UseCaseError> for ApiError {
171 fn from(error: crate::usecases::UseCaseError) -> Self {
172 ApiError::map_client("use case policy violation", error)
173 }
174}
175
176impl From<objectstore_types::metadata::Error> for ApiError {
177 fn from(error: objectstore_types::metadata::Error) -> Self {
178 ApiError::map_client("invalid metadata", error)
179 }
180}
181
182pub type ApiResult<T> = Result<T, ApiError>;
184
185pub fn insert_accept_ranges(response: &mut Response) {
187 response.headers_mut().insert(
188 http::header::ACCEPT_RANGES,
189 HeaderValue::from_static("bytes"),
190 );
191}