Skip to main content

objectstore_server/endpoints/
common.rs

1//! Common types and utilities for API endpoints.
2
3use 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/// Error type for API operations.
19#[derive(Debug, Error)]
20pub enum ApiError {
21    /// Errors indicating malformed or illegal requests.
22    #[error("client error: {context}")]
23    Client {
24        /// Context describing the operation that failed.
25        context: Cow<'static, str>,
26        /// The underlying error, if available.
27        #[source]
28        cause: Option<Box<dyn Error + Send + Sync>>,
29    },
30
31    /// The requested operation was valid but could not be satisfied.
32    #[error("{0}")]
33    Conflict(Cow<'static, str>),
34
35    /// Authorization/authentication errors.
36    #[error("auth error: {0}")]
37    Auth(#[from] AuthError),
38
39    /// Service errors, indicating that something went wrong when receiving or executing a request.
40    #[error("service error: {0}")]
41    Service(#[from] ServiceError),
42
43    /// Errors encountered when parsing or executing a batch request.
44    #[error("batch error: {0}")]
45    Batch(#[from] BatchError),
46
47    /// Internal server errors.
48    #[error("internal error: {context}")]
49    Internal {
50        /// Context describing the operation that failed.
51        context: Cow<'static, str>,
52        /// The underlying error, if available.
53        #[source]
54        cause: Option<Box<dyn Error + Send + Sync>>,
55    },
56}
57
58impl ApiError {
59    /// Creates a client error with context and an underlying cause.
60    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    /// Creates a client error with context and no underlying cause.
71    pub fn client(context: impl Into<Cow<'static, str>>) -> Self {
72        Self::Client {
73            context: context.into(),
74            cause: None,
75        }
76    }
77
78    /// Creates a conflict error with a client-safe explanation.
79    pub fn conflict(context: impl Into<Cow<'static, str>>) -> Self {
80        Self::Conflict(context.into())
81    }
82
83    /// Creates an internal server error with context and an underlying cause.
84    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    /// Returns the HTTP status code appropriate for this error variant.
95    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    /// Reports this error to error tracking if it indicates a server fault (5xx status).
138    ///
139    /// Call this exactly once wherever an `ApiError` is serialized into a client-visible
140    /// response: standalone responses ([`IntoResponse`]) and batch response parts.
141    pub fn capture(&self) {
142        // Service errors and admission rejections are already logged at the source.
143        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
182/// Result type for API operations.
183pub type ApiResult<T> = Result<T, ApiError>;
184
185/// Inserts `Accept-Ranges: bytes` into the response headers.
186pub fn insert_accept_ranges(response: &mut Response) {
187    response.headers_mut().insert(
188        http::header::ACCEPT_RANGES,
189        HeaderValue::from_static("bytes"),
190    );
191}