Skip to main content

allsource_core/
error.rs

1/// AllSource error types
2#[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    /// The store was opened read-only (e.g. a second process attached to a
50    /// data-dir already owned by a live writer). Writes are rejected so the
51    /// owner's WAL is never corrupted. See `EventStoreConfig::read_only`.
52    #[error("Store is read-only: {0}")]
53    ReadOnly(String),
54
55    /// A conditional write could not be authorised yet because the tenant's
56    /// version manifest does not account for every archive file. The scan
57    /// persisted what it folded, so retrying resolves strictly fewer files
58    /// than this attempt did and the condition clears on its own.
59    ///
60    /// `reason` carries the limit that stopped the fold. Without it an
61    /// operator cannot tell which budget dimension a stuck tenant is hitting,
62    /// and that is the first thing worth knowing.
63    #[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    /// A tenant's archive could not be made resident because the process has
70    /// no room for it.
71    ///
72    /// Reported instead of attempting the load, because the alternative is
73    /// not a slower load: the kernel kills the process, every other tenant's
74    /// requests fail with it, and the next attempt starts from the same
75    /// place. Refusing one tenant's request is strictly less damage
76    /// (gh#321).
77    #[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    /// A strict archive read stopped at one of its limits. Retrying at once
87    /// repeats the same work and stops at the same limit.
88    #[error("Strict archive read budget exceeded: {dimension}")]
89    ArchiveBudgetExceeded { dimension: String },
90
91    #[error("Internal error: {0}")]
92    InternalError(String),
93
94    /// Event payload failed validation against a registered schema. The
95    /// HTTP layer maps this to 422 with a structured body so callers can
96    /// distinguish schema problems from generic validation failures.
97    #[error(
98        "Schema violation for event_type '{event_type}' (schema v{schema_version}): {errors:?}"
99    )]
100    SchemaViolation {
101        event_type: String,
102        schema_version: u32,
103        errors: Vec<String>,
104    },
105}
106
107impl AllSourceError {
108    /// Returns true for transient errors that may succeed on retry
109    /// (storage I/O, concurrency conflicts, queue pressure).
110    pub fn is_retryable(&self) -> bool {
111        matches!(
112            self,
113            AllSourceError::StorageError(_)
114                | AllSourceError::ConcurrencyError(_)
115                | AllSourceError::VersionConflict { .. }
116                | AllSourceError::QueueFull(_)
117                | AllSourceError::ArchiveIndexIncomplete { .. }
118                | AllSourceError::ArchiveHydrationRefused { .. }
119                | AllSourceError::ArchiveBudgetExceeded { .. }
120        )
121    }
122}
123
124// Alias for domain layer convenience
125pub use AllSourceError as Error;
126
127impl From<arrow::error::ArrowError> for AllSourceError {
128    fn from(err: arrow::error::ArrowError) -> Self {
129        AllSourceError::ArrowError(err.to_string())
130    }
131}
132
133impl From<parquet::errors::ParquetError> for AllSourceError {
134    fn from(err: parquet::errors::ParquetError) -> Self {
135        AllSourceError::StorageError(err.to_string())
136    }
137}
138
139impl From<crate::infrastructure::persistence::SimdJsonError> for AllSourceError {
140    fn from(err: crate::infrastructure::persistence::SimdJsonError) -> Self {
141        AllSourceError::SerializationError(serde_json::Error::io(std::io::Error::new(
142            std::io::ErrorKind::InvalidData,
143            err.to_string(),
144        )))
145    }
146}
147
148#[cfg(feature = "postgres")]
149impl From<sqlx::Error> for AllSourceError {
150    fn from(err: sqlx::Error) -> Self {
151        AllSourceError::StorageError(format!("Database error: {err}"))
152    }
153}
154
155/// Custom Result type for AllSource operations
156pub type Result<T> = std::result::Result<T, AllSourceError>;
157
158#[cfg(feature = "server")]
159mod axum_impl {
160    use super::AllSourceError;
161    use axum::{
162        http::StatusCode,
163        response::{IntoResponse, Response},
164    };
165
166    /// Implement IntoResponse for axum error handling
167    impl IntoResponse for AllSourceError {
168        fn into_response(self) -> Response {
169            let (status, error_message) = match self {
170                AllSourceError::EventNotFound(_)
171                | AllSourceError::EntityNotFound(_)
172                | AllSourceError::TenantNotFound(_) => (StatusCode::NOT_FOUND, self.to_string()),
173                AllSourceError::InvalidEvent(_)
174                | AllSourceError::InvalidQuery(_)
175                | AllSourceError::InvalidInput(_)
176                | AllSourceError::ValidationError(_) => (StatusCode::BAD_REQUEST, self.to_string()),
177                AllSourceError::VersionConflict { expected, current } => {
178                    let body = serde_json::json!({
179                        "error": "version_conflict",
180                        "expected_version": expected,
181                        "current_version": current,
182                    });
183                    return (StatusCode::CONFLICT, axum::Json(body)).into_response();
184                }
185                AllSourceError::TenantAlreadyExists(_) | AllSourceError::ConcurrencyError(_) => {
186                    (StatusCode::CONFLICT, self.to_string())
187                }
188                AllSourceError::ArchiveIndexIncomplete {
189                    remaining,
190                    ref reason,
191                } => {
192                    // Retry-After 1s, not a back-off: each attempt folds more
193                    // files, so waiting longer does not make it likelier.
194                    let body = serde_json::json!({
195                        "error": "archive_index_incomplete",
196                        "remaining_files": remaining,
197                        "stopped_by": reason,
198                    });
199                    return (
200                        StatusCode::SERVICE_UNAVAILABLE,
201                        [(axum::http::header::RETRY_AFTER, "1")],
202                        axum::Json(body),
203                    )
204                        .into_response();
205                }
206                AllSourceError::ArchiveHydrationRefused {
207                    needed_bytes,
208                    available_bytes,
209                } => {
210                    // Retry-After 30s: unlike an incomplete index, this
211                    // attempt made no progress of its own. It clears when
212                    // another tenant is evicted or compaction shrinks this
213                    // one, neither of which a tight retry brings closer.
214                    let body = serde_json::json!({
215                        "error": "archive_hydration_refused",
216                        "needed_bytes": needed_bytes,
217                        "available_bytes": available_bytes,
218                    });
219                    return (
220                        StatusCode::SERVICE_UNAVAILABLE,
221                        [(axum::http::header::RETRY_AFTER, "30")],
222                        axum::Json(body),
223                    )
224                        .into_response();
225                }
226                AllSourceError::ArchiveBudgetExceeded { ref dimension } => {
227                    // A size limit stops the same request at the same place
228                    // until compaction or a raised limit changes either side;
229                    // elapsed time depends on load and can clear quickly.
230                    let retry_after = if dimension == "elapsed time" {
231                        "5"
232                    } else {
233                        "300"
234                    };
235                    let body = serde_json::json!({
236                        "error": "archive_budget_exceeded",
237                        "dimension": dimension,
238                    });
239                    return (
240                        StatusCode::SERVICE_UNAVAILABLE,
241                        [(axum::http::header::RETRY_AFTER, retry_after)],
242                        axum::Json(body),
243                    )
244                        .into_response();
245                }
246                AllSourceError::QueueFull(_) => (StatusCode::SERVICE_UNAVAILABLE, self.to_string()),
247                AllSourceError::ReadOnly(_) => (StatusCode::SERVICE_UNAVAILABLE, self.to_string()),
248                AllSourceError::StorageError(_)
249                | AllSourceError::ArrowError(_)
250                | AllSourceError::IndexError(_)
251                | AllSourceError::InternalError(_) => {
252                    (StatusCode::INTERNAL_SERVER_ERROR, self.to_string())
253                }
254                AllSourceError::SerializationError(_) => {
255                    (StatusCode::UNPROCESSABLE_ENTITY, self.to_string())
256                }
257                AllSourceError::SchemaViolation {
258                    event_type,
259                    schema_version,
260                    errors,
261                } => {
262                    let body = serde_json::json!({
263                        "error": {
264                            "code": "schema_violation",
265                            "message": format!(
266                                "Event payload does not match registered schema for '{event_type}'"
267                            ),
268                            "details": {
269                                "event_type": event_type,
270                                "schema_version": schema_version,
271                                "errors": errors,
272                            }
273                        }
274                    });
275                    return (StatusCode::UNPROCESSABLE_ENTITY, axum::Json(body)).into_response();
276                }
277            };
278
279            let body = serde_json::json!({
280                "error": error_message,
281            });
282
283            (status, axum::Json(body)).into_response()
284        }
285    }
286}
287
288#[cfg(test)]
289mod tests {
290    use super::*;
291
292    #[cfg(feature = "server")]
293    use axum::{http::StatusCode, response::IntoResponse};
294
295    #[test]
296    fn test_error_display() {
297        let err = AllSourceError::EventNotFound("event-123".to_string());
298        assert_eq!(err.to_string(), "Event not found: event-123");
299
300        let err = AllSourceError::EntityNotFound("entity-456".to_string());
301        assert_eq!(err.to_string(), "Entity not found: entity-456");
302
303        let err = AllSourceError::TenantAlreadyExists("tenant-1".to_string());
304        assert_eq!(err.to_string(), "Tenant already exists: tenant-1");
305
306        let err = AllSourceError::TenantNotFound("tenant-2".to_string());
307        assert_eq!(err.to_string(), "Tenant not found: tenant-2");
308    }
309
310    #[test]
311    fn test_error_variants() {
312        let errors: Vec<AllSourceError> = vec![
313            AllSourceError::InvalidEvent("bad event".to_string()),
314            AllSourceError::InvalidQuery("bad query".to_string()),
315            AllSourceError::InvalidInput("bad input".to_string()),
316            AllSourceError::StorageError("storage failed".to_string()),
317            AllSourceError::ArrowError("arrow failed".to_string()),
318            AllSourceError::IndexError("index failed".to_string()),
319            AllSourceError::ValidationError("validation failed".to_string()),
320            AllSourceError::ConcurrencyError("conflict".to_string()),
321            AllSourceError::QueueFull("queue full".to_string()),
322            AllSourceError::InternalError("internal error".to_string()),
323        ];
324
325        for err in errors {
326            let msg = err.to_string();
327            assert!(!msg.is_empty());
328        }
329    }
330
331    #[cfg(feature = "server")]
332    #[test]
333    fn test_into_response_not_found() {
334        let err = AllSourceError::EventNotFound("event-123".to_string());
335        let response = err.into_response();
336        assert_eq!(response.status(), StatusCode::NOT_FOUND);
337
338        let err = AllSourceError::EntityNotFound("entity-456".to_string());
339        let response = err.into_response();
340        assert_eq!(response.status(), StatusCode::NOT_FOUND);
341
342        let err = AllSourceError::TenantNotFound("tenant-1".to_string());
343        let response = err.into_response();
344        assert_eq!(response.status(), StatusCode::NOT_FOUND);
345    }
346
347    #[cfg(feature = "server")]
348    #[test]
349    fn test_into_response_bad_request() {
350        let err = AllSourceError::InvalidEvent("bad event".to_string());
351        let response = err.into_response();
352        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
353
354        let err = AllSourceError::InvalidQuery("bad query".to_string());
355        let response = err.into_response();
356        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
357
358        let err = AllSourceError::InvalidInput("bad input".to_string());
359        let response = err.into_response();
360        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
361
362        let err = AllSourceError::ValidationError("validation failed".to_string());
363        let response = err.into_response();
364        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
365    }
366
367    #[cfg(feature = "server")]
368    #[test]
369    fn test_into_response_conflict() {
370        let err = AllSourceError::TenantAlreadyExists("tenant-1".to_string());
371        let response = err.into_response();
372        assert_eq!(response.status(), StatusCode::CONFLICT);
373
374        let err = AllSourceError::ConcurrencyError("conflict".to_string());
375        let response = err.into_response();
376        assert_eq!(response.status(), StatusCode::CONFLICT);
377    }
378
379    #[cfg(feature = "server")]
380    #[test]
381    fn test_into_response_service_unavailable() {
382        let err = AllSourceError::QueueFull("queue is full".to_string());
383        let response = err.into_response();
384        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
385    }
386
387    /// Locks the wire contract from neotoma-gaps bead t-0795 AC #3:
388    /// 422 with `{error: {code: "schema_violation", details: {event_type,
389    /// schema_version, errors}}}`. Callers parse this shape — don't break it.
390    #[cfg(feature = "server")]
391    #[tokio::test]
392    async fn test_into_response_schema_violation() {
393        use axum::body::to_bytes;
394        let err = AllSourceError::SchemaViolation {
395            event_type: "user.created".to_string(),
396            schema_version: 2,
397            errors: vec!["Missing required field: email".to_string()],
398        };
399        let response = err.into_response();
400        assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
401
402        let body_bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
403        let body: serde_json::Value = serde_json::from_slice(&body_bytes).unwrap();
404        assert_eq!(body["error"]["code"], "schema_violation");
405        assert_eq!(body["error"]["details"]["event_type"], "user.created");
406        assert_eq!(body["error"]["details"]["schema_version"], 2);
407        let errors = body["error"]["details"]["errors"].as_array().unwrap();
408        assert_eq!(errors.len(), 1);
409        assert!(errors[0].as_str().unwrap().contains("email"));
410    }
411
412    #[cfg(feature = "server")]
413    #[test]
414    fn test_into_response_internal_error() {
415        let err = AllSourceError::StorageError("storage error".to_string());
416        let response = err.into_response();
417        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
418
419        let err = AllSourceError::ArrowError("arrow error".to_string());
420        let response = err.into_response();
421        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
422
423        let err = AllSourceError::IndexError("index error".to_string());
424        let response = err.into_response();
425        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
426
427        let err = AllSourceError::InternalError("internal error".to_string());
428        let response = err.into_response();
429        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
430    }
431
432    #[test]
433    fn test_from_arrow_error() {
434        let arrow_err = arrow::error::ArrowError::InvalidArgumentError("test".to_string());
435        let err: AllSourceError = arrow_err.into();
436        assert!(matches!(err, AllSourceError::ArrowError(_)));
437    }
438
439    #[test]
440    fn test_from_parquet_error() {
441        let parquet_err = parquet::errors::ParquetError::General("test".to_string());
442        let err: AllSourceError = parquet_err.into();
443        assert!(matches!(err, AllSourceError::StorageError(_)));
444    }
445
446    #[test]
447    fn test_error_debug() {
448        let err = AllSourceError::EventNotFound("test".to_string());
449        let debug_str = format!("{err:?}");
450        assert!(debug_str.contains("EventNotFound"));
451    }
452
453    #[test]
454    fn test_is_retryable() {
455        // Retryable errors
456        assert!(AllSourceError::StorageError("io".to_string()).is_retryable());
457        assert!(AllSourceError::ConcurrencyError("conflict".to_string()).is_retryable());
458        assert!(AllSourceError::QueueFull("backpressure".to_string()).is_retryable());
459
460        // Non-retryable errors
461        assert!(!AllSourceError::EventNotFound("e1".to_string()).is_retryable());
462        assert!(!AllSourceError::InvalidEvent("bad".to_string()).is_retryable());
463        assert!(!AllSourceError::InvalidQuery("bad".to_string()).is_retryable());
464        assert!(!AllSourceError::ValidationError("bad".to_string()).is_retryable());
465        assert!(!AllSourceError::TenantNotFound("t1".to_string()).is_retryable());
466        assert!(!AllSourceError::TenantAlreadyExists("t1".to_string()).is_retryable());
467        assert!(!AllSourceError::InternalError("bug".to_string()).is_retryable());
468    }
469}