1#[derive(Debug, thiserror::Error)]
3pub enum AllSourceError {
4 #[error("Event not found: {0}")]
5 EventNotFound(String),
6
7 #[error("Entity not found: {0}")]
8 EntityNotFound(String),
9
10 #[error("Tenant already exists: {0}")]
11 TenantAlreadyExists(String),
12
13 #[error("Tenant not found: {0}")]
14 TenantNotFound(String),
15
16 #[error("Invalid event: {0}")]
17 InvalidEvent(String),
18
19 #[error("Invalid query: {0}")]
20 InvalidQuery(String),
21
22 #[error("Invalid input: {0}")]
23 InvalidInput(String),
24
25 #[error("Storage error: {0}")]
26 StorageError(String),
27
28 #[error("Serialization error: {0}")]
29 SerializationError(#[from] serde_json::Error),
30
31 #[error("Arrow error: {0}")]
32 ArrowError(String),
33
34 #[error("Index error: {0}")]
35 IndexError(String),
36
37 #[error("Validation error: {0}")]
38 ValidationError(String),
39
40 #[error("Concurrency error: {0}")]
41 ConcurrencyError(String),
42
43 #[error("Version conflict: expected {expected}, current {current}")]
44 VersionConflict { expected: u64, current: u64 },
45
46 #[error("Queue full: {0}")]
47 QueueFull(String),
48
49 #[error("Store is read-only: {0}")]
53 ReadOnly(String),
54
55 #[error(
64 "Archive version index incomplete: {remaining} archive file(s) not yet folded, stopped by \
65 {reason}; retry to resume"
66 )]
67 ArchiveIndexIncomplete { remaining: usize, reason: String },
68
69 #[error(
78 "Archive hydration refused: tenant needs ~{needed_bytes} resident byte(s), {available_bytes} \
79 available; retry once memory frees or the tenant is compacted"
80 )]
81 ArchiveHydrationRefused {
82 needed_bytes: u64,
83 available_bytes: u64,
84 },
85
86 #[error("Internal error: {0}")]
87 InternalError(String),
88
89 #[error(
93 "Schema violation for event_type '{event_type}' (schema v{schema_version}): {errors:?}"
94 )]
95 SchemaViolation {
96 event_type: String,
97 schema_version: u32,
98 errors: Vec<String>,
99 },
100}
101
102impl AllSourceError {
103 pub fn is_retryable(&self) -> bool {
106 matches!(
107 self,
108 AllSourceError::StorageError(_)
109 | AllSourceError::ConcurrencyError(_)
110 | AllSourceError::VersionConflict { .. }
111 | AllSourceError::QueueFull(_)
112 | AllSourceError::ArchiveIndexIncomplete { .. }
113 | AllSourceError::ArchiveHydrationRefused { .. }
114 )
115 }
116}
117
118pub use AllSourceError as Error;
120
121impl From<arrow::error::ArrowError> for AllSourceError {
122 fn from(err: arrow::error::ArrowError) -> Self {
123 AllSourceError::ArrowError(err.to_string())
124 }
125}
126
127impl From<parquet::errors::ParquetError> for AllSourceError {
128 fn from(err: parquet::errors::ParquetError) -> Self {
129 AllSourceError::StorageError(err.to_string())
130 }
131}
132
133impl From<crate::infrastructure::persistence::SimdJsonError> for AllSourceError {
134 fn from(err: crate::infrastructure::persistence::SimdJsonError) -> Self {
135 AllSourceError::SerializationError(serde_json::Error::io(std::io::Error::new(
136 std::io::ErrorKind::InvalidData,
137 err.to_string(),
138 )))
139 }
140}
141
142#[cfg(feature = "postgres")]
143impl From<sqlx::Error> for AllSourceError {
144 fn from(err: sqlx::Error) -> Self {
145 AllSourceError::StorageError(format!("Database error: {err}"))
146 }
147}
148
149pub type Result<T> = std::result::Result<T, AllSourceError>;
151
152#[cfg(feature = "server")]
153mod axum_impl {
154 use super::AllSourceError;
155 use axum::{
156 http::StatusCode,
157 response::{IntoResponse, Response},
158 };
159
160 impl IntoResponse for AllSourceError {
162 fn into_response(self) -> Response {
163 let (status, error_message) = match self {
164 AllSourceError::EventNotFound(_)
165 | AllSourceError::EntityNotFound(_)
166 | AllSourceError::TenantNotFound(_) => (StatusCode::NOT_FOUND, self.to_string()),
167 AllSourceError::InvalidEvent(_)
168 | AllSourceError::InvalidQuery(_)
169 | AllSourceError::InvalidInput(_)
170 | AllSourceError::ValidationError(_) => (StatusCode::BAD_REQUEST, self.to_string()),
171 AllSourceError::VersionConflict { expected, current } => {
172 let body = serde_json::json!({
173 "error": "version_conflict",
174 "expected_version": expected,
175 "current_version": current,
176 });
177 return (StatusCode::CONFLICT, axum::Json(body)).into_response();
178 }
179 AllSourceError::TenantAlreadyExists(_) | AllSourceError::ConcurrencyError(_) => {
180 (StatusCode::CONFLICT, self.to_string())
181 }
182 AllSourceError::ArchiveIndexIncomplete {
183 remaining,
184 ref reason,
185 } => {
186 let body = serde_json::json!({
189 "error": "archive_index_incomplete",
190 "remaining_files": remaining,
191 "stopped_by": reason,
192 });
193 return (
194 StatusCode::SERVICE_UNAVAILABLE,
195 [(axum::http::header::RETRY_AFTER, "1")],
196 axum::Json(body),
197 )
198 .into_response();
199 }
200 AllSourceError::ArchiveHydrationRefused {
201 needed_bytes,
202 available_bytes,
203 } => {
204 let body = serde_json::json!({
209 "error": "archive_hydration_refused",
210 "needed_bytes": needed_bytes,
211 "available_bytes": available_bytes,
212 });
213 return (
214 StatusCode::SERVICE_UNAVAILABLE,
215 [(axum::http::header::RETRY_AFTER, "30")],
216 axum::Json(body),
217 )
218 .into_response();
219 }
220 AllSourceError::QueueFull(_) => (StatusCode::SERVICE_UNAVAILABLE, self.to_string()),
221 AllSourceError::ReadOnly(_) => (StatusCode::SERVICE_UNAVAILABLE, self.to_string()),
222 AllSourceError::StorageError(_)
223 | AllSourceError::ArrowError(_)
224 | AllSourceError::IndexError(_)
225 | AllSourceError::InternalError(_) => {
226 (StatusCode::INTERNAL_SERVER_ERROR, self.to_string())
227 }
228 AllSourceError::SerializationError(_) => {
229 (StatusCode::UNPROCESSABLE_ENTITY, self.to_string())
230 }
231 AllSourceError::SchemaViolation {
232 event_type,
233 schema_version,
234 errors,
235 } => {
236 let body = serde_json::json!({
237 "error": {
238 "code": "schema_violation",
239 "message": format!(
240 "Event payload does not match registered schema for '{event_type}'"
241 ),
242 "details": {
243 "event_type": event_type,
244 "schema_version": schema_version,
245 "errors": errors,
246 }
247 }
248 });
249 return (StatusCode::UNPROCESSABLE_ENTITY, axum::Json(body)).into_response();
250 }
251 };
252
253 let body = serde_json::json!({
254 "error": error_message,
255 });
256
257 (status, axum::Json(body)).into_response()
258 }
259 }
260}
261
262#[cfg(test)]
263mod tests {
264 use super::*;
265
266 #[cfg(feature = "server")]
267 use axum::{http::StatusCode, response::IntoResponse};
268
269 #[test]
270 fn test_error_display() {
271 let err = AllSourceError::EventNotFound("event-123".to_string());
272 assert_eq!(err.to_string(), "Event not found: event-123");
273
274 let err = AllSourceError::EntityNotFound("entity-456".to_string());
275 assert_eq!(err.to_string(), "Entity not found: entity-456");
276
277 let err = AllSourceError::TenantAlreadyExists("tenant-1".to_string());
278 assert_eq!(err.to_string(), "Tenant already exists: tenant-1");
279
280 let err = AllSourceError::TenantNotFound("tenant-2".to_string());
281 assert_eq!(err.to_string(), "Tenant not found: tenant-2");
282 }
283
284 #[test]
285 fn test_error_variants() {
286 let errors: Vec<AllSourceError> = vec![
287 AllSourceError::InvalidEvent("bad event".to_string()),
288 AllSourceError::InvalidQuery("bad query".to_string()),
289 AllSourceError::InvalidInput("bad input".to_string()),
290 AllSourceError::StorageError("storage failed".to_string()),
291 AllSourceError::ArrowError("arrow failed".to_string()),
292 AllSourceError::IndexError("index failed".to_string()),
293 AllSourceError::ValidationError("validation failed".to_string()),
294 AllSourceError::ConcurrencyError("conflict".to_string()),
295 AllSourceError::QueueFull("queue full".to_string()),
296 AllSourceError::InternalError("internal error".to_string()),
297 ];
298
299 for err in errors {
300 let msg = err.to_string();
301 assert!(!msg.is_empty());
302 }
303 }
304
305 #[cfg(feature = "server")]
306 #[test]
307 fn test_into_response_not_found() {
308 let err = AllSourceError::EventNotFound("event-123".to_string());
309 let response = err.into_response();
310 assert_eq!(response.status(), StatusCode::NOT_FOUND);
311
312 let err = AllSourceError::EntityNotFound("entity-456".to_string());
313 let response = err.into_response();
314 assert_eq!(response.status(), StatusCode::NOT_FOUND);
315
316 let err = AllSourceError::TenantNotFound("tenant-1".to_string());
317 let response = err.into_response();
318 assert_eq!(response.status(), StatusCode::NOT_FOUND);
319 }
320
321 #[cfg(feature = "server")]
322 #[test]
323 fn test_into_response_bad_request() {
324 let err = AllSourceError::InvalidEvent("bad event".to_string());
325 let response = err.into_response();
326 assert_eq!(response.status(), StatusCode::BAD_REQUEST);
327
328 let err = AllSourceError::InvalidQuery("bad query".to_string());
329 let response = err.into_response();
330 assert_eq!(response.status(), StatusCode::BAD_REQUEST);
331
332 let err = AllSourceError::InvalidInput("bad input".to_string());
333 let response = err.into_response();
334 assert_eq!(response.status(), StatusCode::BAD_REQUEST);
335
336 let err = AllSourceError::ValidationError("validation failed".to_string());
337 let response = err.into_response();
338 assert_eq!(response.status(), StatusCode::BAD_REQUEST);
339 }
340
341 #[cfg(feature = "server")]
342 #[test]
343 fn test_into_response_conflict() {
344 let err = AllSourceError::TenantAlreadyExists("tenant-1".to_string());
345 let response = err.into_response();
346 assert_eq!(response.status(), StatusCode::CONFLICT);
347
348 let err = AllSourceError::ConcurrencyError("conflict".to_string());
349 let response = err.into_response();
350 assert_eq!(response.status(), StatusCode::CONFLICT);
351 }
352
353 #[cfg(feature = "server")]
354 #[test]
355 fn test_into_response_service_unavailable() {
356 let err = AllSourceError::QueueFull("queue is full".to_string());
357 let response = err.into_response();
358 assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
359 }
360
361 #[cfg(feature = "server")]
365 #[tokio::test]
366 async fn test_into_response_schema_violation() {
367 use axum::body::to_bytes;
368 let err = AllSourceError::SchemaViolation {
369 event_type: "user.created".to_string(),
370 schema_version: 2,
371 errors: vec!["Missing required field: email".to_string()],
372 };
373 let response = err.into_response();
374 assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
375
376 let body_bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
377 let body: serde_json::Value = serde_json::from_slice(&body_bytes).unwrap();
378 assert_eq!(body["error"]["code"], "schema_violation");
379 assert_eq!(body["error"]["details"]["event_type"], "user.created");
380 assert_eq!(body["error"]["details"]["schema_version"], 2);
381 let errors = body["error"]["details"]["errors"].as_array().unwrap();
382 assert_eq!(errors.len(), 1);
383 assert!(errors[0].as_str().unwrap().contains("email"));
384 }
385
386 #[cfg(feature = "server")]
387 #[test]
388 fn test_into_response_internal_error() {
389 let err = AllSourceError::StorageError("storage error".to_string());
390 let response = err.into_response();
391 assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
392
393 let err = AllSourceError::ArrowError("arrow error".to_string());
394 let response = err.into_response();
395 assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
396
397 let err = AllSourceError::IndexError("index error".to_string());
398 let response = err.into_response();
399 assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
400
401 let err = AllSourceError::InternalError("internal error".to_string());
402 let response = err.into_response();
403 assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
404 }
405
406 #[test]
407 fn test_from_arrow_error() {
408 let arrow_err = arrow::error::ArrowError::InvalidArgumentError("test".to_string());
409 let err: AllSourceError = arrow_err.into();
410 assert!(matches!(err, AllSourceError::ArrowError(_)));
411 }
412
413 #[test]
414 fn test_from_parquet_error() {
415 let parquet_err = parquet::errors::ParquetError::General("test".to_string());
416 let err: AllSourceError = parquet_err.into();
417 assert!(matches!(err, AllSourceError::StorageError(_)));
418 }
419
420 #[test]
421 fn test_error_debug() {
422 let err = AllSourceError::EventNotFound("test".to_string());
423 let debug_str = format!("{err:?}");
424 assert!(debug_str.contains("EventNotFound"));
425 }
426
427 #[test]
428 fn test_is_retryable() {
429 assert!(AllSourceError::StorageError("io".to_string()).is_retryable());
431 assert!(AllSourceError::ConcurrencyError("conflict".to_string()).is_retryable());
432 assert!(AllSourceError::QueueFull("backpressure".to_string()).is_retryable());
433
434 assert!(!AllSourceError::EventNotFound("e1".to_string()).is_retryable());
436 assert!(!AllSourceError::InvalidEvent("bad".to_string()).is_retryable());
437 assert!(!AllSourceError::InvalidQuery("bad".to_string()).is_retryable());
438 assert!(!AllSourceError::ValidationError("bad".to_string()).is_retryable());
439 assert!(!AllSourceError::TenantNotFound("t1".to_string()).is_retryable());
440 assert!(!AllSourceError::TenantAlreadyExists("t1".to_string()).is_retryable());
441 assert!(!AllSourceError::InternalError("bug".to_string()).is_retryable());
442 }
443}