Skip to main content

acton_service/
error.rs

1//! Error types and HTTP response conversion
2
3use axum::{
4    http::StatusCode,
5    response::{IntoResponse, Response},
6    Json,
7};
8use serde::{Deserialize, Serialize};
9use std::fmt;
10use thiserror::Error;
11
12// ============================================================================
13// Structured Database Errors
14// ============================================================================
15
16pub use acton_service_core::error::{DatabaseErrorKind, DatabaseOperation};
17
18/// Structured database error with operation context
19#[derive(Debug, Clone, PartialEq, Eq)]
20#[cfg(any(
21    feature = "database",
22    feature = "mssql",
23    feature = "turso",
24    feature = "surrealdb"
25))]
26pub struct DatabaseError {
27    /// The operation being performed when the error occurred
28    pub operation: DatabaseOperation,
29    /// The category of error
30    pub kind: DatabaseErrorKind,
31    /// Human-readable error message
32    pub message: String,
33    /// Additional context (e.g., table name, query fragment)
34    pub context: Option<String>,
35}
36
37#[cfg(any(
38    feature = "database",
39    feature = "mssql",
40    feature = "turso",
41    feature = "surrealdb"
42))]
43impl DatabaseError {
44    /// Create a new database error
45    pub fn new(
46        operation: DatabaseOperation,
47        kind: DatabaseErrorKind,
48        message: impl Into<String>,
49    ) -> Self {
50        Self {
51            operation,
52            kind,
53            message: message.into(),
54            context: None,
55        }
56    }
57
58    /// Create a new database error with context
59    pub fn with_context(
60        operation: DatabaseOperation,
61        kind: DatabaseErrorKind,
62        message: impl Into<String>,
63        context: impl Into<String>,
64    ) -> Self {
65        Self {
66            operation,
67            kind,
68            message: message.into(),
69            context: Some(context.into()),
70        }
71    }
72
73    /// Create a "not found" error
74    pub fn not_found(operation: DatabaseOperation, message: impl Into<String>) -> Self {
75        Self::new(operation, DatabaseErrorKind::NotFound, message)
76    }
77
78    /// Create a connection failed error
79    pub fn connection_failed(message: impl Into<String>) -> Self {
80        Self::new(
81            DatabaseOperation::Connect,
82            DatabaseErrorKind::ConnectionFailed,
83            message,
84        )
85    }
86
87    /// Create a constraint violation error
88    pub fn constraint_violation(operation: DatabaseOperation, message: impl Into<String>) -> Self {
89        Self::new(operation, DatabaseErrorKind::ConstraintViolation, message)
90    }
91
92    /// Create a query failed error
93    pub fn query_failed(message: impl Into<String>) -> Self {
94        Self::new(
95            DatabaseOperation::Query,
96            DatabaseErrorKind::QueryFailed,
97            message,
98        )
99    }
100
101    /// Create a timeout error
102    pub fn timeout(operation: DatabaseOperation, message: impl Into<String>) -> Self {
103        Self::new(operation, DatabaseErrorKind::Timeout, message)
104    }
105
106    /// Create a pool exhausted error
107    pub fn pool_exhausted(message: impl Into<String>) -> Self {
108        Self::new(
109            DatabaseOperation::PoolAcquire,
110            DatabaseErrorKind::PoolExhausted,
111            message,
112        )
113    }
114
115    /// Create a transaction failed error
116    pub fn transaction_failed(message: impl Into<String>) -> Self {
117        Self::new(
118            DatabaseOperation::Transaction,
119            DatabaseErrorKind::TransactionFailed,
120            message,
121        )
122    }
123
124    /// Create a sync failed error (Turso specific)
125    pub fn sync_failed(message: impl Into<String>) -> Self {
126        Self::new(
127            DatabaseOperation::Sync,
128            DatabaseErrorKind::SyncFailed,
129            message,
130        )
131    }
132
133    /// Check if this error is retriable (transient errors that may succeed on retry)
134    pub fn is_retriable(&self) -> bool {
135        matches!(
136            self.kind,
137            DatabaseErrorKind::ConnectionFailed
138                | DatabaseErrorKind::Timeout
139                | DatabaseErrorKind::PoolExhausted
140                | DatabaseErrorKind::SyncFailed
141        )
142    }
143
144    /// Add context to an existing error
145    pub fn add_context(mut self, context: impl Into<String>) -> Self {
146        self.context = Some(context.into());
147        self
148    }
149}
150
151#[cfg(any(
152    feature = "database",
153    feature = "mssql",
154    feature = "turso",
155    feature = "surrealdb"
156))]
157impl fmt::Display for DatabaseError {
158    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159        write!(
160            f,
161            "Database {} error during {}: {}",
162            self.kind, self.operation, self.message
163        )?;
164        if let Some(ref ctx) = self.context {
165            write!(f, " [context: {}]", ctx)?;
166        }
167        Ok(())
168    }
169}
170
171#[cfg(any(
172    feature = "database",
173    feature = "mssql",
174    feature = "turso",
175    feature = "surrealdb"
176))]
177impl std::error::Error for DatabaseError {}
178
179/// Sanitize a database URL by removing credentials
180#[cfg(any(
181    feature = "database",
182    feature = "mssql",
183    feature = "turso",
184    feature = "surrealdb"
185))]
186pub fn sanitize_url(url: &str) -> String {
187    // Handle standard database URLs like postgres://user:pass@host/db
188    if let Some(at_pos) = url.find('@') {
189        if let Some(scheme_end) = url.find("://") {
190            let scheme = &url[..scheme_end + 3];
191            let after_at = &url[at_pos + 1..];
192            return format!("{}<redacted>@{}", scheme, after_at);
193        }
194    }
195    // Handle Turso URLs like libsql://db-org.turso.io?authToken=xxx
196    if url.contains("authToken=") || url.contains("auth_token=") {
197        let base = url.split('?').next().unwrap_or(url);
198        return format!("{}?<credentials redacted>", base);
199    }
200    url.to_string()
201}
202
203/// Result type alias using the framework error
204pub type Result<T> = std::result::Result<T, Error>;
205
206/// Main error type for the framework
207///
208/// Large error variants are boxed to reduce stack size
209///
210/// Marked `#[non_exhaustive]`: new variants are added as the framework grows
211/// (`Tls` was added in 0.34), and downstream code must not be broken by that.
212/// Match with a `_` arm.
213#[derive(Debug, Error)]
214#[non_exhaustive]
215pub enum Error {
216    /// Configuration error
217    #[error("Configuration error: {0}")]
218    Config(Box<figment::Error>),
219
220    /// Structured database error with operation context
221    #[cfg(any(
222        feature = "database",
223        feature = "mssql",
224        feature = "turso",
225        feature = "surrealdb"
226    ))]
227    #[error("{0}")]
228    Database(DatabaseError),
229
230    /// Redis error
231    #[cfg(feature = "cache")]
232    #[error("Redis error: {0}")]
233    Redis(Box<redis::RedisError>),
234
235    /// NATS error
236    #[cfg(feature = "events")]
237    #[error("NATS error: {0}")]
238    Nats(String),
239
240    /// ClickHouse error
241    #[cfg(feature = "clickhouse")]
242    #[error("ClickHouse error: {0}")]
243    ClickHouse(String),
244
245    /// PASETO error (default token format)
246    #[error("PASETO error: {0}")]
247    Paseto(String),
248
249    /// Authentication error (password hashing, token generation, etc.)
250    #[cfg(feature = "auth")]
251    #[error("Auth error: {0}")]
252    Auth(String),
253
254    /// JWT error (requires `jwt` feature)
255    #[cfg(feature = "jwt")]
256    #[error("JWT error: {0}")]
257    Jwt(Box<jsonwebtoken::errors::Error>),
258
259    /// HTTP error
260    #[error("HTTP error: {0}")]
261    Http(Box<axum::http::Error>),
262
263    /// I/O error
264    #[error("I/O error: {0}")]
265    Io(#[from] std::io::Error),
266
267    /// Authentication error
268    #[error("Authentication failed: {0}")]
269    Unauthorized(String),
270
271    /// Authorization error
272    #[error("Forbidden: {0}")]
273    Forbidden(String),
274
275    /// Resource not found
276    #[error("Not found: {0}")]
277    NotFound(String),
278
279    /// Bad request
280    #[error("Bad request: {0}")]
281    BadRequest(String),
282
283    /// Rate limit exceeded (HTTP 429).
284    ///
285    /// The response always carries `Retry-After: retry_after_secs`, so a
286    /// client that honors it waits exactly as long as the limiter needs and
287    /// no longer. Build it with [`Error::rate_limited`] from the limiter's
288    /// wait, which rounds up and never answers 0.
289    #[error("Rate limit exceeded: retry after {retry_after_secs}s")]
290    RateLimitExceeded {
291        /// Whole seconds until the request would be admitted; at least 1.
292        retry_after_secs: u64,
293    },
294
295    /// Resource conflict (409)
296    #[error("Conflict: {0}")]
297    Conflict(String),
298
299    /// Validation error (422)
300    #[error("Validation error: {0}")]
301    ValidationError(String),
302
303    /// Not supported error (501)
304    #[error("Not supported: {0}")]
305    NotSupported(String),
306
307    /// External service error (502)
308    #[error("External service error: {0}")]
309    External(String),
310
311    /// Internal server error
312    #[error("Internal server error: {0}")]
313    Internal(String),
314
315    /// TLS material could not be loaded, parsed or validated
316    ///
317    /// These are operator configuration mistakes — an unreadable path, an
318    /// unparseable PEM, a certificate file with no certificates in it — and
319    /// they surface at boot, not while serving. `Internal` would tell an
320    /// operator to suspect the service instead of their own `cert_path`.
321    ///
322    /// [`Config`](Self::Config) cannot carry them: it wraps a
323    /// [`figment::Error`], and none of these originate from figment.
324    #[cfg(feature = "tls")]
325    #[error("TLS configuration error: {0}")]
326    Tls(String),
327
328    /// Generic error
329    #[error("{0}")]
330    Other(String),
331
332    /// Session error
333    #[cfg(feature = "session")]
334    #[error("Session error: {0}")]
335    Session(String),
336
337    /// Audit logging error
338    #[cfg(feature = "audit")]
339    #[error("Audit error: {0}")]
340    Audit(String),
341
342    /// Account locked due to repeated login failures
343    #[cfg(feature = "login-lockout")]
344    #[error("Account locked: {message}")]
345    AccountLocked {
346        /// Human-readable message
347        message: String,
348        /// Seconds until the lockout expires
349        retry_after_secs: u64,
350    },
351}
352
353/// Error response body
354#[derive(Debug, Serialize, Deserialize)]
355pub struct ErrorResponse {
356    /// Error message
357    pub error: String,
358
359    /// Optional error code
360    #[serde(skip_serializing_if = "Option::is_none")]
361    pub code: Option<String>,
362
363    /// HTTP status code
364    pub status: u16,
365}
366
367impl ErrorResponse {
368    /// Create a new error response
369    pub fn new(status: StatusCode, error: impl Into<String>) -> Self {
370        Self {
371            error: error.into(),
372            code: None,
373            status: status.as_u16(),
374        }
375    }
376
377    /// Create error response with a code
378    pub fn with_code(
379        status: StatusCode,
380        code: impl Into<String>,
381        error: impl Into<String>,
382    ) -> Self {
383        Self {
384            error: error.into(),
385            code: Some(code.into()),
386            status: status.as_u16(),
387        }
388    }
389}
390
391impl Error {
392    /// A rate-limit refusal for a caller that must wait `wait` before retrying.
393    ///
394    /// `Retry-After` counts whole seconds, so the wait is rounded up, never
395    /// down: a client told to come back sooner than the limiter admits it is
396    /// refused again. A zero or sub-second wait still answers 1, because
397    /// `Retry-After: 0` invites an immediate retry into the same refusal.
398    pub fn rate_limited(wait: std::time::Duration) -> Self {
399        Error::RateLimitExceeded {
400            retry_after_secs: retry_after_secs(wait),
401        }
402    }
403}
404
405/// A wait as a `Retry-After` value: whole seconds, rounded up, and at least 1
406/// (`Retry-After: 0` invites an immediate retry into the same refusal).
407pub(crate) fn retry_after_secs(wait: std::time::Duration) -> u64 {
408    let whole = wait.as_secs();
409    let rounded = if wait.subsec_nanos() > 0 {
410        whole.saturating_add(1)
411    } else {
412        whole
413    };
414    rounded.max(1)
415}
416
417impl IntoResponse for Error {
418    fn into_response(self) -> Response {
419        let (status, error_response) = match self {
420            Error::Config(e) => (
421                StatusCode::INTERNAL_SERVER_ERROR,
422                ErrorResponse::with_code(
423                    StatusCode::INTERNAL_SERVER_ERROR,
424                    "CONFIG_ERROR",
425                    e.to_string(),
426                ),
427            ),
428
429            #[cfg(any(
430                feature = "database",
431                feature = "mssql",
432                feature = "turso",
433                feature = "surrealdb"
434            ))]
435            Error::Database(ref e) => {
436                // Log with structured context
437                tracing::error!(
438                    operation = %e.operation,
439                    kind = %e.kind,
440                    context = ?e.context,
441                    retriable = e.is_retriable(),
442                    "Database error: {}", e.message
443                );
444
445                // Map error kind to HTTP status code
446                let status = match e.kind {
447                    DatabaseErrorKind::NotFound => StatusCode::NOT_FOUND,
448                    DatabaseErrorKind::ConstraintViolation => StatusCode::CONFLICT,
449                    DatabaseErrorKind::Timeout => StatusCode::GATEWAY_TIMEOUT,
450                    DatabaseErrorKind::PermissionDenied => StatusCode::FORBIDDEN,
451                    _ => StatusCode::INTERNAL_SERVER_ERROR,
452                };
453
454                // Generate error code from kind
455                let code = format!("DATABASE_{}", e.kind.to_string().to_uppercase());
456
457                // User-facing message (don't expose internal details)
458                let user_message = match e.kind {
459                    DatabaseErrorKind::NotFound => "Resource not found",
460                    DatabaseErrorKind::ConstraintViolation => {
461                        "Operation conflicts with existing data"
462                    }
463                    DatabaseErrorKind::Timeout => "Database operation timed out",
464                    DatabaseErrorKind::PermissionDenied => "Database permission denied",
465                    _ => "Database operation failed",
466                };
467
468                (status, ErrorResponse::with_code(status, code, user_message))
469            }
470
471            #[cfg(feature = "cache")]
472            Error::Redis(e) => {
473                tracing::error!("Redis error: {}", e);
474                (
475                    StatusCode::INTERNAL_SERVER_ERROR,
476                    ErrorResponse::with_code(
477                        StatusCode::INTERNAL_SERVER_ERROR,
478                        "CACHE_ERROR",
479                        "Cache operation failed",
480                    ),
481                )
482            }
483
484            #[cfg(feature = "events")]
485            Error::Nats(e) => {
486                tracing::error!("NATS error: {}", e);
487                (
488                    StatusCode::INTERNAL_SERVER_ERROR,
489                    ErrorResponse::with_code(
490                        StatusCode::INTERNAL_SERVER_ERROR,
491                        "NATS_ERROR",
492                        "Event system error",
493                    ),
494                )
495            }
496
497            #[cfg(feature = "clickhouse")]
498            Error::ClickHouse(e) => {
499                tracing::error!("ClickHouse error: {}", e);
500                (
501                    StatusCode::INTERNAL_SERVER_ERROR,
502                    ErrorResponse::with_code(
503                        StatusCode::INTERNAL_SERVER_ERROR,
504                        "ANALYTICS_ERROR",
505                        "Analytics operation failed",
506                    ),
507                )
508            }
509
510            Error::Paseto(msg) => (
511                StatusCode::UNAUTHORIZED,
512                ErrorResponse::with_code(StatusCode::UNAUTHORIZED, "INVALID_TOKEN", msg),
513            ),
514
515            #[cfg(feature = "auth")]
516            Error::Auth(msg) => (
517                StatusCode::UNAUTHORIZED,
518                ErrorResponse::with_code(StatusCode::UNAUTHORIZED, "AUTH_ERROR", msg),
519            ),
520
521            #[cfg(feature = "jwt")]
522            Error::Jwt(e) => (
523                StatusCode::UNAUTHORIZED,
524                ErrorResponse::with_code(StatusCode::UNAUTHORIZED, "INVALID_TOKEN", e.to_string()),
525            ),
526
527            Error::Http(e) => (
528                StatusCode::BAD_REQUEST,
529                ErrorResponse::with_code(StatusCode::BAD_REQUEST, "HTTP_ERROR", e.to_string()),
530            ),
531
532            Error::Io(e) => {
533                tracing::error!("I/O error: {}", e);
534                (
535                    StatusCode::INTERNAL_SERVER_ERROR,
536                    ErrorResponse::with_code(
537                        StatusCode::INTERNAL_SERVER_ERROR,
538                        "IO_ERROR",
539                        "I/O operation failed",
540                    ),
541                )
542            }
543
544            Error::Unauthorized(msg) => (
545                StatusCode::UNAUTHORIZED,
546                ErrorResponse::with_code(StatusCode::UNAUTHORIZED, "UNAUTHORIZED", msg),
547            ),
548
549            Error::Forbidden(msg) => (
550                StatusCode::FORBIDDEN,
551                ErrorResponse::with_code(StatusCode::FORBIDDEN, "FORBIDDEN", msg),
552            ),
553
554            Error::NotFound(msg) => (
555                StatusCode::NOT_FOUND,
556                ErrorResponse::with_code(StatusCode::NOT_FOUND, "NOT_FOUND", msg),
557            ),
558
559            Error::BadRequest(msg) => (
560                StatusCode::BAD_REQUEST,
561                ErrorResponse::with_code(StatusCode::BAD_REQUEST, "BAD_REQUEST", msg),
562            ),
563
564            Error::RateLimitExceeded { retry_after_secs } => {
565                let error_response = ErrorResponse::with_code(
566                    StatusCode::TOO_MANY_REQUESTS,
567                    "RATE_LIMIT_EXCEEDED",
568                    "Too many requests",
569                );
570                let mut response =
571                    (StatusCode::TOO_MANY_REQUESTS, Json(error_response)).into_response();
572                response.headers_mut().insert(
573                    axum::http::header::RETRY_AFTER,
574                    axum::http::header::HeaderValue::from(retry_after_secs.max(1)),
575                );
576                return response;
577            }
578
579            Error::Conflict(msg) => (
580                StatusCode::CONFLICT,
581                ErrorResponse::with_code(StatusCode::CONFLICT, "CONFLICT", msg),
582            ),
583
584            Error::ValidationError(msg) => (
585                StatusCode::UNPROCESSABLE_ENTITY,
586                ErrorResponse::with_code(StatusCode::UNPROCESSABLE_ENTITY, "VALIDATION_ERROR", msg),
587            ),
588
589            Error::NotSupported(msg) => (
590                StatusCode::NOT_IMPLEMENTED,
591                ErrorResponse::with_code(StatusCode::NOT_IMPLEMENTED, "NOT_SUPPORTED", msg),
592            ),
593
594            Error::External(msg) => {
595                tracing::error!("External service error: {}", msg);
596                (
597                    StatusCode::BAD_GATEWAY,
598                    ErrorResponse::with_code(
599                        StatusCode::BAD_GATEWAY,
600                        "EXTERNAL_ERROR",
601                        "External service unavailable",
602                    ),
603                )
604            }
605
606            Error::Internal(msg) => {
607                tracing::error!("Internal error: {}", msg);
608                (
609                    StatusCode::INTERNAL_SERVER_ERROR,
610                    ErrorResponse::with_code(
611                        StatusCode::INTERNAL_SERVER_ERROR,
612                        "INTERNAL_ERROR",
613                        "Internal server error",
614                    ),
615                )
616            }
617
618            // A TLS material failure is a boot-time configuration fault, so it
619            // normally refuses startup and never reaches a response at all. If
620            // one somehow surfaces mid-request it is a 500 like any other
621            // server-side fault, and the operator-facing detail stays in the
622            // log rather than going out on the wire.
623            #[cfg(feature = "tls")]
624            Error::Tls(msg) => {
625                tracing::error!("TLS configuration error: {}", msg);
626                (
627                    StatusCode::INTERNAL_SERVER_ERROR,
628                    ErrorResponse::with_code(
629                        StatusCode::INTERNAL_SERVER_ERROR,
630                        "INTERNAL_ERROR",
631                        "Internal server error",
632                    ),
633                )
634            }
635
636            Error::Other(msg) => {
637                tracing::error!("Unexpected error: {}", msg);
638                (
639                    StatusCode::INTERNAL_SERVER_ERROR,
640                    ErrorResponse::new(
641                        StatusCode::INTERNAL_SERVER_ERROR,
642                        "An unexpected error occurred",
643                    ),
644                )
645            }
646
647            #[cfg(feature = "session")]
648            Error::Session(msg) => {
649                tracing::error!("Session error: {}", msg);
650                (
651                    StatusCode::INTERNAL_SERVER_ERROR,
652                    ErrorResponse::with_code(
653                        StatusCode::INTERNAL_SERVER_ERROR,
654                        "SESSION_ERROR",
655                        "Session operation failed",
656                    ),
657                )
658            }
659
660            #[cfg(feature = "audit")]
661            Error::Audit(msg) => {
662                tracing::error!("Audit error: {}", msg);
663                (
664                    StatusCode::INTERNAL_SERVER_ERROR,
665                    ErrorResponse::with_code(
666                        StatusCode::INTERNAL_SERVER_ERROR,
667                        "AUDIT_ERROR",
668                        "Audit operation failed",
669                    ),
670                )
671            }
672
673            #[cfg(feature = "login-lockout")]
674            Error::AccountLocked {
675                ref message,
676                retry_after_secs,
677            } => {
678                // HTTP 423 Locked with Retry-After header
679                let error_response =
680                    ErrorResponse::with_code(StatusCode::LOCKED, "ACCOUNT_LOCKED", message.clone());
681                let mut response = (StatusCode::LOCKED, Json(error_response)).into_response();
682                if let Ok(value) =
683                    axum::http::header::HeaderValue::from_str(&retry_after_secs.to_string())
684                {
685                    response
686                        .headers_mut()
687                        .insert(axum::http::header::RETRY_AFTER, value);
688                }
689                return response;
690            }
691        };
692
693        (status, Json(error_response)).into_response()
694    }
695}
696
697impl fmt::Display for ErrorResponse {
698    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
699        write!(f, "{}", self.error)
700    }
701}
702
703// Manual From implementations for boxed errors
704impl From<figment::Error> for Error {
705    fn from(err: figment::Error) -> Self {
706        Error::Config(Box::new(err))
707    }
708}
709
710// Conversion from sqlx::Error to DatabaseError
711#[cfg(feature = "database")]
712impl From<sqlx::Error> for DatabaseError {
713    fn from(error: sqlx::Error) -> Self {
714        acton_service_postgres::database_error(error).into()
715    }
716}
717
718#[cfg(feature = "database")]
719impl From<sqlx::Error> for Error {
720    fn from(err: sqlx::Error) -> Self {
721        Error::Database(DatabaseError::from(err))
722    }
723}
724
725#[cfg(feature = "mssql")]
726impl From<tiberius::error::Error> for DatabaseError {
727    fn from(error: tiberius::error::Error) -> Self {
728        acton_service_mssql::database_error(error).into()
729    }
730}
731
732#[cfg(feature = "mssql")]
733impl From<tiberius::error::Error> for Error {
734    fn from(err: tiberius::error::Error) -> Self {
735        Error::Database(DatabaseError::from(err))
736    }
737}
738
739// Conversion from DatabaseError to Error
740#[cfg(any(
741    feature = "database",
742    feature = "mssql",
743    feature = "turso",
744    feature = "surrealdb"
745))]
746impl From<DatabaseError> for Error {
747    fn from(err: DatabaseError) -> Self {
748        Error::Database(err)
749    }
750}
751
752#[cfg(feature = "cache")]
753impl From<redis::RedisError> for Error {
754    fn from(err: redis::RedisError) -> Self {
755        Error::Redis(Box::new(err))
756    }
757}
758
759#[cfg(feature = "clickhouse")]
760impl From<clickhouse::error::Error> for Error {
761    fn from(err: clickhouse::error::Error) -> Self {
762        Error::ClickHouse(err.to_string())
763    }
764}
765
766// Conversion from libsql::Error to DatabaseError
767#[cfg(feature = "turso")]
768impl From<libsql::Error> for DatabaseError {
769    fn from(error: libsql::Error) -> Self {
770        acton_service_turso::database_error(error).into()
771    }
772}
773
774#[cfg(feature = "turso")]
775impl From<libsql::Error> for Error {
776    fn from(err: libsql::Error) -> Self {
777        Error::Database(DatabaseError::from(err))
778    }
779}
780
781// Conversion from surrealdb::Error to DatabaseError
782#[cfg(feature = "surrealdb")]
783impl From<surrealdb::Error> for DatabaseError {
784    fn from(error: surrealdb::Error) -> Self {
785        acton_service_surrealdb::database_error(error).into()
786    }
787}
788
789#[cfg(feature = "surrealdb")]
790impl From<surrealdb::Error> for Error {
791    fn from(err: surrealdb::Error) -> Self {
792        Error::Database(DatabaseError::from(err))
793    }
794}
795
796#[cfg(feature = "jwt")]
797impl From<jsonwebtoken::errors::Error> for Error {
798    fn from(err: jsonwebtoken::errors::Error) -> Self {
799        Error::Jwt(Box::new(err))
800    }
801}
802
803impl From<axum::http::Error> for Error {
804    fn from(err: axum::http::Error) -> Self {
805        Error::Http(Box::new(err))
806    }
807}
808
809// Conversion from DatabaseError to RepositoryError
810#[cfg(all(
811    feature = "repository",
812    any(
813        feature = "database",
814        feature = "mssql",
815        feature = "turso",
816        feature = "surrealdb"
817    )
818))]
819impl From<DatabaseError> for crate::repository::RepositoryError {
820    fn from(err: DatabaseError) -> Self {
821        use crate::repository::{RepositoryErrorKind, RepositoryOperation};
822
823        let kind = match err.kind {
824            DatabaseErrorKind::NotFound => RepositoryErrorKind::NotFound,
825            DatabaseErrorKind::ConstraintViolation => RepositoryErrorKind::ConstraintViolation,
826            DatabaseErrorKind::ConnectionFailed => RepositoryErrorKind::ConnectionFailed,
827            DatabaseErrorKind::Timeout => RepositoryErrorKind::Timeout,
828            DatabaseErrorKind::PoolExhausted => RepositoryErrorKind::ConnectionFailed,
829            _ => RepositoryErrorKind::DatabaseError,
830        };
831
832        let operation = match err.operation {
833            DatabaseOperation::Query => RepositoryOperation::FindAll,
834            DatabaseOperation::Insert => RepositoryOperation::Create,
835            DatabaseOperation::Update => RepositoryOperation::Update,
836            DatabaseOperation::Delete => RepositoryOperation::Delete,
837            _ => RepositoryOperation::FindById,
838        };
839
840        Self {
841            operation,
842            kind,
843            message: err.message,
844            entity_type: None,
845            entity_id: None,
846        }
847    }
848}
849
850impl From<acton_service_core::StorageError> for Error {
851    fn from(error: acton_service_core::StorageError) -> Self {
852        use acton_service_core::StorageError;
853        match error {
854            StorageError::Internal(message) => Self::Internal(message),
855            StorageError::Io(error) => Self::Io(error),
856            StorageError::Database(error) => {
857                #[cfg(any(
858                    feature = "database",
859                    feature = "mssql",
860                    feature = "turso",
861                    feature = "surrealdb"
862                ))]
863                {
864                    Self::Database(DatabaseError {
865                        operation: error.operation,
866                        kind: error.kind,
867                        message: error.message,
868                        context: error.context,
869                    })
870                }
871                #[cfg(not(any(
872                    feature = "database",
873                    feature = "mssql",
874                    feature = "turso",
875                    feature = "surrealdb"
876                )))]
877                {
878                    Self::Internal(error.to_string())
879                }
880            }
881            StorageError::ClickHouse(message) => {
882                #[cfg(feature = "clickhouse")]
883                {
884                    Self::ClickHouse(message)
885                }
886                #[cfg(not(feature = "clickhouse"))]
887                {
888                    Self::Internal(message)
889                }
890            }
891        }
892    }
893}
894
895#[cfg(any(
896    feature = "database",
897    feature = "mssql",
898    feature = "turso",
899    feature = "surrealdb"
900))]
901impl From<acton_service_core::DatabaseError> for DatabaseError {
902    fn from(error: acton_service_core::DatabaseError) -> Self {
903        Self {
904            operation: error.operation,
905            kind: error.kind,
906            message: error.message,
907            context: error.context,
908        }
909    }
910}
911
912#[cfg(test)]
913mod tests {
914    use super::*;
915
916    #[test]
917    fn rate_limited_rounds_the_wait_up_to_whole_seconds() {
918        use std::time::Duration;
919        let secs = |wait| match Error::rate_limited(wait) {
920            Error::RateLimitExceeded { retry_after_secs } => retry_after_secs,
921            other => panic!("rate_limited built {other:?}"),
922        };
923        assert_eq!(secs(Duration::ZERO), 1, "a zero wait still answers 1");
924        assert_eq!(secs(Duration::from_millis(1)), 1);
925        assert_eq!(secs(Duration::from_secs(1)), 1);
926        assert_eq!(
927            secs(Duration::from_millis(1001)),
928            2,
929            "rounded up, never down"
930        );
931        assert_eq!(secs(Duration::from_secs(30)), 30);
932        assert_eq!(secs(Duration::MAX), u64::MAX, "saturates rather than wraps");
933    }
934
935    #[test]
936    fn rate_limit_exceeded_is_429_with_retry_after() {
937        let response = Error::RateLimitExceeded {
938            retry_after_secs: 7,
939        }
940        .into_response();
941        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
942        assert_eq!(
943            response
944                .headers()
945                .get(axum::http::header::RETRY_AFTER)
946                .and_then(|v| v.to_str().ok()),
947            Some("7"),
948            "every 429 carries Retry-After"
949        );
950    }
951
952    #[test]
953    fn rate_limit_exceeded_never_advertises_a_zero_wait() {
954        let response = Error::RateLimitExceeded {
955            retry_after_secs: 0,
956        }
957        .into_response();
958        assert_eq!(
959            response
960                .headers()
961                .get(axum::http::header::RETRY_AFTER)
962                .and_then(|v| v.to_str().ok()),
963            Some("1")
964        );
965    }
966
967    #[test]
968    fn test_error_response() {
969        let err = ErrorResponse::new(StatusCode::NOT_FOUND, "User not found");
970        assert_eq!(err.status, 404);
971        assert_eq!(err.error, "User not found");
972        assert!(err.code.is_none());
973    }
974
975    #[test]
976    fn test_error_response_with_code() {
977        let err = ErrorResponse::with_code(
978            StatusCode::BAD_REQUEST,
979            "INVALID_EMAIL",
980            "Email format is invalid",
981        );
982        assert_eq!(err.status, 400);
983        assert_eq!(err.error, "Email format is invalid");
984        assert_eq!(err.code, Some("INVALID_EMAIL".to_string()));
985    }
986
987    // =========================================================================
988    // DatabaseError Tests
989    // =========================================================================
990
991    #[cfg(any(
992        feature = "database",
993        feature = "mssql",
994        feature = "turso",
995        feature = "surrealdb"
996    ))]
997    mod database_error_tests {
998        use super::*;
999
1000        #[test]
1001        fn test_database_error_new() {
1002            let err = DatabaseError::new(
1003                DatabaseOperation::Query,
1004                DatabaseErrorKind::QueryFailed,
1005                "Query failed",
1006            );
1007            assert_eq!(err.operation, DatabaseOperation::Query);
1008            assert_eq!(err.kind, DatabaseErrorKind::QueryFailed);
1009            assert_eq!(err.message, "Query failed");
1010            assert!(err.context.is_none());
1011        }
1012
1013        #[test]
1014        fn test_database_error_with_context() {
1015            let err = DatabaseError::with_context(
1016                DatabaseOperation::Insert,
1017                DatabaseErrorKind::ConstraintViolation,
1018                "Unique constraint violated",
1019                "users.email",
1020            );
1021            assert_eq!(err.operation, DatabaseOperation::Insert);
1022            assert_eq!(err.kind, DatabaseErrorKind::ConstraintViolation);
1023            assert_eq!(err.message, "Unique constraint violated");
1024            assert_eq!(err.context, Some("users.email".to_string()));
1025        }
1026
1027        #[test]
1028        fn test_not_found_convenience() {
1029            let err = DatabaseError::not_found(DatabaseOperation::Query, "User not found");
1030            assert_eq!(err.operation, DatabaseOperation::Query);
1031            assert_eq!(err.kind, DatabaseErrorKind::NotFound);
1032            assert_eq!(err.message, "User not found");
1033        }
1034
1035        #[test]
1036        fn test_connection_failed_convenience() {
1037            let err = DatabaseError::connection_failed("Connection refused");
1038            assert_eq!(err.operation, DatabaseOperation::Connect);
1039            assert_eq!(err.kind, DatabaseErrorKind::ConnectionFailed);
1040            assert_eq!(err.message, "Connection refused");
1041        }
1042
1043        #[test]
1044        fn test_constraint_violation_convenience() {
1045            let err =
1046                DatabaseError::constraint_violation(DatabaseOperation::Update, "FK constraint");
1047            assert_eq!(err.operation, DatabaseOperation::Update);
1048            assert_eq!(err.kind, DatabaseErrorKind::ConstraintViolation);
1049        }
1050
1051        #[test]
1052        fn test_query_failed_convenience() {
1053            let err = DatabaseError::query_failed("Syntax error");
1054            assert_eq!(err.operation, DatabaseOperation::Query);
1055            assert_eq!(err.kind, DatabaseErrorKind::QueryFailed);
1056        }
1057
1058        #[test]
1059        fn test_timeout_convenience() {
1060            let err = DatabaseError::timeout(DatabaseOperation::Query, "Query timed out");
1061            assert_eq!(err.operation, DatabaseOperation::Query);
1062            assert_eq!(err.kind, DatabaseErrorKind::Timeout);
1063        }
1064
1065        #[test]
1066        fn test_pool_exhausted_convenience() {
1067            let err = DatabaseError::pool_exhausted("No connections available");
1068            assert_eq!(err.operation, DatabaseOperation::PoolAcquire);
1069            assert_eq!(err.kind, DatabaseErrorKind::PoolExhausted);
1070        }
1071
1072        #[test]
1073        fn test_transaction_failed_convenience() {
1074            let err = DatabaseError::transaction_failed("Commit failed");
1075            assert_eq!(err.operation, DatabaseOperation::Transaction);
1076            assert_eq!(err.kind, DatabaseErrorKind::TransactionFailed);
1077        }
1078
1079        #[test]
1080        fn test_sync_failed_convenience() {
1081            let err = DatabaseError::sync_failed("Sync with remote failed");
1082            assert_eq!(err.operation, DatabaseOperation::Sync);
1083            assert_eq!(err.kind, DatabaseErrorKind::SyncFailed);
1084        }
1085
1086        #[test]
1087        fn test_is_retriable_transient_errors() {
1088            // Transient errors should be retriable
1089            assert!(DatabaseError::connection_failed("refused").is_retriable());
1090            assert!(DatabaseError::timeout(DatabaseOperation::Query, "timeout").is_retriable());
1091            assert!(DatabaseError::pool_exhausted("exhausted").is_retriable());
1092            assert!(DatabaseError::sync_failed("sync error").is_retriable());
1093        }
1094
1095        #[test]
1096        fn test_is_retriable_permanent_errors() {
1097            // Permanent errors should not be retriable
1098            assert!(
1099                !DatabaseError::not_found(DatabaseOperation::Query, "not found").is_retriable()
1100            );
1101            assert!(
1102                !DatabaseError::constraint_violation(DatabaseOperation::Insert, "unique")
1103                    .is_retriable()
1104            );
1105            assert!(!DatabaseError::query_failed("syntax error").is_retriable());
1106            assert!(!DatabaseError::transaction_failed("rollback").is_retriable());
1107            assert!(!DatabaseError::new(
1108                DatabaseOperation::Query,
1109                DatabaseErrorKind::PermissionDenied,
1110                "denied"
1111            )
1112            .is_retriable());
1113            assert!(!DatabaseError::new(
1114                DatabaseOperation::Query,
1115                DatabaseErrorKind::TypeConversion,
1116                "type error"
1117            )
1118            .is_retriable());
1119            assert!(!DatabaseError::new(
1120                DatabaseOperation::Connect,
1121                DatabaseErrorKind::Configuration,
1122                "bad config"
1123            )
1124            .is_retriable());
1125        }
1126
1127        #[test]
1128        fn test_add_context() {
1129            let err =
1130                DatabaseError::query_failed("Query failed").add_context("SELECT * FROM users");
1131            assert_eq!(err.context, Some("SELECT * FROM users".to_string()));
1132        }
1133
1134        #[test]
1135        fn test_display_formatting() {
1136            let err = DatabaseError::new(
1137                DatabaseOperation::Query,
1138                DatabaseErrorKind::QueryFailed,
1139                "Syntax error near 'FROM'",
1140            );
1141            let display = format!("{}", err);
1142            assert!(display.contains("query_failed"));
1143            assert!(display.contains("query"));
1144            assert!(display.contains("Syntax error near 'FROM'"));
1145        }
1146
1147        #[test]
1148        fn test_display_formatting_with_context() {
1149            let err = DatabaseError::with_context(
1150                DatabaseOperation::Insert,
1151                DatabaseErrorKind::ConstraintViolation,
1152                "Unique constraint violated",
1153                "users.email",
1154            );
1155            let display = format!("{}", err);
1156            assert!(display.contains("[context: users.email]"));
1157        }
1158
1159        #[test]
1160        fn test_database_operation_display() {
1161            assert_eq!(format!("{}", DatabaseOperation::Connect), "connect");
1162            assert_eq!(format!("{}", DatabaseOperation::Query), "query");
1163            assert_eq!(format!("{}", DatabaseOperation::Insert), "insert");
1164            assert_eq!(format!("{}", DatabaseOperation::Update), "update");
1165            assert_eq!(format!("{}", DatabaseOperation::Delete), "delete");
1166            assert_eq!(format!("{}", DatabaseOperation::Transaction), "transaction");
1167            assert_eq!(format!("{}", DatabaseOperation::Sync), "sync");
1168            assert_eq!(format!("{}", DatabaseOperation::Migration), "migration");
1169            assert_eq!(
1170                format!("{}", DatabaseOperation::PoolAcquire),
1171                "pool_acquire"
1172            );
1173        }
1174
1175        #[test]
1176        fn test_database_error_kind_display() {
1177            assert_eq!(
1178                format!("{}", DatabaseErrorKind::ConnectionFailed),
1179                "connection_failed"
1180            );
1181            assert_eq!(format!("{}", DatabaseErrorKind::NotFound), "not_found");
1182            assert_eq!(
1183                format!("{}", DatabaseErrorKind::ConstraintViolation),
1184                "constraint_violation"
1185            );
1186            assert_eq!(
1187                format!("{}", DatabaseErrorKind::QueryFailed),
1188                "query_failed"
1189            );
1190            assert_eq!(
1191                format!("{}", DatabaseErrorKind::TransactionFailed),
1192                "transaction_failed"
1193            );
1194            assert_eq!(
1195                format!("{}", DatabaseErrorKind::TypeConversion),
1196                "type_conversion"
1197            );
1198            assert_eq!(format!("{}", DatabaseErrorKind::SyncFailed), "sync_failed");
1199            assert_eq!(
1200                format!("{}", DatabaseErrorKind::Configuration),
1201                "configuration"
1202            );
1203            assert_eq!(format!("{}", DatabaseErrorKind::Timeout), "timeout");
1204            assert_eq!(
1205                format!("{}", DatabaseErrorKind::PermissionDenied),
1206                "permission_denied"
1207            );
1208            assert_eq!(
1209                format!("{}", DatabaseErrorKind::PoolExhausted),
1210                "pool_exhausted"
1211            );
1212            assert_eq!(format!("{}", DatabaseErrorKind::Other), "other");
1213        }
1214
1215        #[test]
1216        fn test_sanitize_url_postgres() {
1217            let url = "postgres://admin:secret123@localhost:5432/mydb";
1218            let sanitized = sanitize_url(url);
1219            assert_eq!(sanitized, "postgres://<redacted>@localhost:5432/mydb");
1220            assert!(!sanitized.contains("admin"));
1221            assert!(!sanitized.contains("secret123"));
1222        }
1223
1224        #[test]
1225        fn test_sanitize_url_turso() {
1226            let url = "libsql://my-db-org.turso.io?authToken=eyJ0eXAi";
1227            let sanitized = sanitize_url(url);
1228            assert_eq!(
1229                sanitized,
1230                "libsql://my-db-org.turso.io?<credentials redacted>"
1231            );
1232            assert!(!sanitized.contains("eyJ0eXAi"));
1233        }
1234
1235        #[test]
1236        fn test_sanitize_url_no_credentials() {
1237            let url = "libsql://localhost:8080";
1238            let sanitized = sanitize_url(url);
1239            assert_eq!(sanitized, "libsql://localhost:8080");
1240        }
1241
1242        #[test]
1243        fn test_database_error_equality() {
1244            let err1 = DatabaseError::new(
1245                DatabaseOperation::Query,
1246                DatabaseErrorKind::NotFound,
1247                "Not found",
1248            );
1249            let err2 = DatabaseError::new(
1250                DatabaseOperation::Query,
1251                DatabaseErrorKind::NotFound,
1252                "Not found",
1253            );
1254            assert_eq!(err1, err2);
1255        }
1256
1257        #[test]
1258        fn test_database_error_clone() {
1259            let err = DatabaseError::with_context(
1260                DatabaseOperation::Insert,
1261                DatabaseErrorKind::ConstraintViolation,
1262                "Duplicate key",
1263                "users.id",
1264            );
1265            let cloned = err.clone();
1266            assert_eq!(err, cloned);
1267        }
1268    }
1269}