footing 0.1.9

Feature-gated foundations for Rust backend services
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
//! Redacted SQLite errors and operational diagnostics.

use std::fmt;

use sqlx::migrate::MigrateError;
use thiserror::Error;

use crate::{
    db::MigrationFailureKind,
    result::{ClassifyError, Diagnostic, DiagnosticKind, ErrorDescriptor, ErrorKind},
};

#[derive(Error)]
#[non_exhaustive]
/// Errors that can occur while opening or using a SQLite pool.
pub enum SqlitePoolError {
    #[error("SQLite operation failed")]
    /// The underlying SQLx error.
    Sqlx(#[from] sqlx::Error),
}

impl fmt::Debug for SqlitePoolError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SqlitePoolError")
            .field("error_code", &self.error_code())
            .field("source", &"[REDACTED]")
            .finish()
    }
}

impl ClassifyError for SqlitePoolError {
    fn error_kind(&self) -> ErrorKind {
        ErrorKind::Dependency
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal("sqlite_unavailable")
    }
}

#[derive(Error)]
#[non_exhaustive]
/// Errors that can occur while bootstrapping SQLite.
pub enum SqliteBootstrapError {
    #[error("migrate_on_startup requires a SQLx migrator")]
    /// The required migrator is missing.
    MissingMigrator,
    #[error("failed to connect to SQLite: {diagnosis}")]
    /// Connecting to SQLite failed.
    Connect {
        /// Stable operational diagnosis.
        diagnosis: SqliteDiagnostic,
        #[source]
        /// Redacted source error.
        source: Box<SqlitePoolError>,
    },
    #[error("failed to run SQLite migrations: {diagnosis}")]
    /// Applying migrations failed.
    Migration {
        /// Stable operational diagnosis.
        diagnosis: SqliteDiagnostic,
        /// Stable migration failure classification.
        kind: MigrationFailureKind,
        #[source]
        /// Redacted source error.
        source: Box<MigrateError>,
    },
}

impl fmt::Debug for SqliteBootstrapError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SqliteBootstrapError")
            .field("error_code", &self.error_code())
            .field("diagnosis", &self.diagnosis())
            .field("source", &"[REDACTED]")
            .finish()
    }
}

impl ClassifyError for SqliteBootstrapError {
    fn error_kind(&self) -> ErrorKind {
        match self {
            Self::MissingMigrator => ErrorKind::Validation,
            Self::Connect { .. } | Self::Migration { .. } => ErrorKind::Dependency,
        }
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::MissingMigrator => "sqlite_migrator_required",
            Self::Connect { .. } => "sqlite_connect_failed",
            Self::Migration { .. } => "sqlite_migration_failed",
        })
    }

    fn error_descriptor(&self) -> ErrorDescriptor {
        ErrorDescriptor::new(self.error_kind(), self.error_code(), self.to_string())
            .with_retryable(self.diagnosis().is_some_and(SqliteDiagnostic::retryable))
    }
}

impl SqliteBootstrapError {
    #[must_use]
    /// Returns the stable diagnosis when the failure reached the database boundary.
    pub const fn diagnosis(&self) -> Option<&SqliteDiagnostic> {
        match self {
            Self::Connect { diagnosis, .. } | Self::Migration { diagnosis, .. } => Some(diagnosis),
            Self::MissingMigrator => None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
/// SQLite operation represented by a diagnosis.
pub enum SqliteOperation {
    /// Open the database and initialize the pool.
    Connect,
    /// Apply database migrations.
    Migrate,
}

impl SqliteOperation {
    #[must_use]
    /// Returns the stable operation identifier.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Connect => "connect",
            Self::Migrate => "migrate",
        }
    }
}

impl fmt::Display for SqliteOperation {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
/// Stable classification of a SQLite diagnosis.
pub enum SqliteDiagnosticKind {
    /// The SQLite connection configuration is invalid.
    InvalidConfiguration,
    /// The configured database file does not exist.
    DatabaseMissing,
    /// The process lacks permission for the database or its directory.
    PermissionDenied,
    /// The database is locked by another operation.
    DatabaseBusy,
    /// The database storage is full.
    StorageExhausted,
    /// The database file is corrupt or is not a SQLite database.
    DatabaseCorrupt,
    /// A database constraint rejected an operation.
    ConstraintViolation,
    /// A pooled connection could not be acquired before the timeout.
    PoolExhausted,
    /// The database or pool is unavailable.
    Unavailable,
    /// Migration sources could not be resolved.
    MigrationSourceInvalid,
    /// An expected migration is missing.
    MigrationMissing,
    /// An applied migration checksum differs from the source.
    MigrationChecksumMismatch,
    /// A migration is partially applied.
    MigrationDirty,
    /// Applied and resolved migration versions conflict.
    MigrationVersionConflict,
    /// A migration failed while executing.
    MigrationExecutionFailed,
    /// The failure is not classified by this version of Footing.
    Unknown,
}

impl SqliteDiagnosticKind {
    #[must_use]
    /// Returns the stable diagnostic identifier.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::InvalidConfiguration => "invalid_configuration",
            Self::DatabaseMissing => "database_missing",
            Self::PermissionDenied => "permission_denied",
            Self::DatabaseBusy => "database_busy",
            Self::StorageExhausted => "storage_exhausted",
            Self::DatabaseCorrupt => "database_corrupt",
            Self::ConstraintViolation => "constraint_violation",
            Self::PoolExhausted => "pool_exhausted",
            Self::Unavailable => "unavailable",
            Self::MigrationSourceInvalid => "migration_source_invalid",
            Self::MigrationMissing => "migration_missing",
            Self::MigrationChecksumMismatch => "migration_checksum_mismatch",
            Self::MigrationDirty => "migration_dirty",
            Self::MigrationVersionConflict => "migration_version_conflict",
            Self::MigrationExecutionFailed => "migration_execution_failed",
            Self::Unknown => "unknown",
        }
    }
}

impl From<SqliteDiagnosticKind> for DiagnosticKind {
    fn from(value: SqliteDiagnosticKind) -> Self {
        match value {
            SqliteDiagnosticKind::InvalidConfiguration => Self::InvalidConfiguration,
            SqliteDiagnosticKind::DatabaseMissing | SqliteDiagnosticKind::MigrationMissing => {
                Self::ResourceMissing
            }
            SqliteDiagnosticKind::PermissionDenied => Self::PermissionDenied,
            SqliteDiagnosticKind::DatabaseBusy => Self::ResourceConflict,
            SqliteDiagnosticKind::StorageExhausted | SqliteDiagnosticKind::PoolExhausted => {
                Self::CapacityExhausted
            }
            SqliteDiagnosticKind::DatabaseCorrupt
            | SqliteDiagnosticKind::MigrationChecksumMismatch
            | SqliteDiagnosticKind::MigrationDirty
            | SqliteDiagnosticKind::MigrationVersionConflict => Self::StateMismatch,
            SqliteDiagnosticKind::Unavailable => Self::Unavailable,
            SqliteDiagnosticKind::ConstraintViolation
            | SqliteDiagnosticKind::MigrationSourceInvalid
            | SqliteDiagnosticKind::MigrationExecutionFailed => Self::ExecutionFailed,
            SqliteDiagnosticKind::Unknown => Self::Unknown,
        }
    }
}

impl fmt::Display for SqliteDiagnosticKind {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Redacted SQLite operational diagnosis.
pub struct SqliteDiagnostic {
    operation: SqliteOperation,
    kind: SqliteDiagnosticKind,
    message: String,
    hint: String,
    retryable: bool,
}

impl fmt::Debug for SqliteDiagnostic {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SqliteDiagnostic")
            .field("operation", &self.operation)
            .field("kind", &self.kind)
            .field("message", &"[REDACTED]")
            .field("hint", &"[REDACTED]")
            .field("retryable", &self.retryable)
            .finish()
    }
}

impl SqliteDiagnostic {
    #[must_use]
    /// Creates a stable SQLite diagnosis.
    pub fn new(
        operation: SqliteOperation,
        kind: SqliteDiagnosticKind,
        message: impl Into<String>,
        hint: impl Into<String>,
        retryable: bool,
    ) -> Self {
        Self {
            operation,
            kind,
            message: message.into(),
            hint: hint.into(),
            retryable,
        }
    }

    #[must_use]
    /// Returns the operation.
    pub const fn operation(&self) -> SqliteOperation {
        self.operation
    }

    #[must_use]
    /// Returns the diagnostic classification.
    pub const fn kind(&self) -> SqliteDiagnosticKind {
        self.kind
    }

    #[must_use]
    /// Returns the stable operator message.
    pub fn message(&self) -> &str {
        &self.message
    }

    #[must_use]
    /// Returns the stable remediation hint.
    pub fn hint(&self) -> &str {
        &self.hint
    }

    #[must_use]
    /// Returns whether retrying may succeed.
    pub const fn retryable(&self) -> bool {
        self.retryable
    }

    #[must_use]
    /// Converts this value into a generic Footing diagnostic.
    pub fn to_diagnostic(&self) -> Diagnostic {
        Diagnostic::dependency(
            "sqlite",
            self.operation.as_str(),
            DiagnosticKind::from(self.kind),
            self.message.clone(),
        )
        .with_retryable(self.retryable)
        .with_remediation(self.hint.clone())
    }
}

impl fmt::Display for SqliteDiagnostic {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "{} during {}: {}; hint: {}",
            self.kind, self.operation, self.message, self.hint
        )
    }
}

impl From<SqliteDiagnostic> for Diagnostic {
    fn from(value: SqliteDiagnostic) -> Self {
        value.to_diagnostic()
    }
}

impl From<&SqliteDiagnostic> for Diagnostic {
    fn from(value: &SqliteDiagnostic) -> Self {
        value.to_diagnostic()
    }
}

#[must_use]
/// Converts an SQLx error into a stable redacted SQLite diagnosis.
pub fn diagnose_sqlx_error(operation: SqliteOperation, error: &sqlx::Error) -> SqliteDiagnostic {
    let (kind, message, hint, retryable) = match error {
        sqlx::Error::Configuration(_) => (
            SqliteDiagnosticKind::InvalidConfiguration,
            "SQLite connection configuration is invalid",
            "verify database_url syntax and SQLite connection options",
            false,
        ),
        sqlx::Error::Database(error) => classify_database_error(error.as_ref()),
        sqlx::Error::Io(error) => classify_io_error(error.kind()),
        sqlx::Error::PoolTimedOut => (
            SqliteDiagnosticKind::PoolExhausted,
            "timed out while acquiring a SQLite connection",
            "increase acquire_timeout, shorten transactions, or review pool capacity",
            true,
        ),
        sqlx::Error::PoolClosed => (
            SqliteDiagnosticKind::Unavailable,
            "SQLite pool is closed",
            "check application shutdown and pool ownership",
            false,
        ),
        _ => (
            SqliteDiagnosticKind::Unknown,
            "SQLite operation failed with an unclassified error",
            "inspect application logs for the underlying SQLx error",
            false,
        ),
    };

    SqliteDiagnostic::new(operation, kind, message, hint, retryable)
}

#[must_use]
/// Converts a pool error into a stable redacted SQLite diagnosis.
pub fn diagnose_pool_error(
    operation: SqliteOperation,
    error: &SqlitePoolError,
) -> SqliteDiagnostic {
    match error {
        SqlitePoolError::Sqlx(source) => diagnose_sqlx_error(operation, source),
    }
}

#[must_use]
/// Converts a migration error into a stable redacted SQLite diagnosis.
pub fn diagnose_migration_error(error: &MigrateError) -> SqliteDiagnostic {
    match error {
        MigrateError::Execute(source) => {
            let diagnosis = diagnose_sqlx_error(SqliteOperation::Migrate, source);
            if diagnosis.kind != SqliteDiagnosticKind::Unknown {
                return diagnosis;
            }
            migration_diagnostic(
                SqliteDiagnosticKind::MigrationExecutionFailed,
                "SQLite migration execution failed",
                "inspect the failing SQL statement and migration ordering",
            )
        }
        MigrateError::ExecuteMigration(source, version) => {
            let diagnosis = diagnose_sqlx_error(SqliteOperation::Migrate, source);
            if diagnosis.kind != SqliteDiagnosticKind::Unknown {
                return diagnosis;
            }
            migration_diagnostic(
                SqliteDiagnosticKind::MigrationExecutionFailed,
                format!("SQLite migration version {version} failed"),
                "inspect the failing SQL statement and migration ordering",
            )
        }
        _ => diagnose_migration_kind(MigrationFailureKind::from_error(error)),
    }
}

fn diagnose_migration_kind(kind: MigrationFailureKind) -> SqliteDiagnostic {
    match kind {
        MigrationFailureKind::Source => migration_diagnostic(
            SqliteDiagnosticKind::MigrationSourceInvalid,
            "failed to resolve SQLite migration sources",
            "verify migration paths, file names, and embedded migration assets",
        ),
        MigrationFailureKind::VersionMissing { version }
        | MigrationFailureKind::VersionNotPresent { version } => migration_diagnostic(
            SqliteDiagnosticKind::MigrationMissing,
            format!("SQLite migration version {version} is missing from the application"),
            "restore the migration or deploy a binary containing the complete migration history",
        ),
        MigrationFailureKind::VersionMismatch { version } => migration_diagnostic(
            SqliteDiagnosticKind::MigrationChecksumMismatch,
            format!("SQLite migration version {version} was modified after being applied"),
            "do not edit applied migrations; add a new migration instead",
        ),
        MigrationFailureKind::Dirty { version } => migration_diagnostic(
            SqliteDiagnosticKind::MigrationDirty,
            format!("SQLite migration version {version} is partially applied"),
            "repair the database deliberately before retrying migrations",
        ),
        MigrationFailureKind::VersionTooOld { version, latest }
        | MigrationFailureKind::VersionTooNew { version, latest } => migration_diagnostic(
            SqliteDiagnosticKind::MigrationVersionConflict,
            format!("SQLite migration version {version} conflicts with latest version {latest}"),
            "deploy a binary whose migration history matches the database",
        ),
        MigrationFailureKind::Execute | MigrationFailureKind::ExecuteMigration { .. } => {
            migration_diagnostic(
                SqliteDiagnosticKind::MigrationExecutionFailed,
                "SQLite migration execution failed",
                "inspect the failing SQL statement and migration ordering",
            )
        }
        MigrationFailureKind::Unsupported | MigrationFailureKind::Unknown => migration_diagnostic(
            SqliteDiagnosticKind::Unknown,
            "SQLite migration failed with an unclassified error",
            "inspect application logs for the underlying SQLx migration error",
        ),
    }
}

fn migration_diagnostic(
    kind: SqliteDiagnosticKind,
    message: impl Into<String>,
    hint: &'static str,
) -> SqliteDiagnostic {
    SqliteDiagnostic::new(SqliteOperation::Migrate, kind, message, hint, false)
}

fn classify_database_error(
    error: &dyn sqlx::error::DatabaseError,
) -> (SqliteDiagnosticKind, &'static str, &'static str, bool) {
    let primary_code = error
        .code()
        .and_then(|code| code.parse::<i32>().ok())
        .map(|code| code & 0xff);

    match primary_code {
        Some(5 | 6) => (
            SqliteDiagnosticKind::DatabaseBusy,
            "SQLite database is locked",
            "shorten write transactions, serialize writers, or increase busy_timeout",
            true,
        ),
        Some(8) => (
            SqliteDiagnosticKind::PermissionDenied,
            "SQLite database is read-only",
            "disable writes or grant write access to the database and its directory",
            false,
        ),
        Some(10) => (
            SqliteDiagnosticKind::Unavailable,
            "SQLite storage I/O failed",
            "check the database file, containing directory, and storage health",
            true,
        ),
        Some(11 | 26) => (
            SqliteDiagnosticKind::DatabaseCorrupt,
            "SQLite database is corrupt or has an invalid format",
            "restore a verified backup or run an explicit SQLite recovery procedure",
            false,
        ),
        Some(13) => (
            SqliteDiagnosticKind::StorageExhausted,
            "SQLite storage is full",
            "free storage space and verify filesystem quotas",
            true,
        ),
        Some(14) => (
            SqliteDiagnosticKind::DatabaseMissing,
            "SQLite database could not be opened",
            "verify the database path and enable create_if_missing when creation is intended",
            false,
        ),
        Some(19) => (
            SqliteDiagnosticKind::ConstraintViolation,
            "SQLite rejected an operation because a constraint was violated",
            "validate application data and transaction ordering",
            false,
        ),
        _ => (
            SqliteDiagnosticKind::Unknown,
            "SQLite returned an unclassified database error",
            "inspect application logs for the underlying SQLite error code",
            false,
        ),
    }
}

fn classify_io_error(
    kind: std::io::ErrorKind,
) -> (SqliteDiagnosticKind, &'static str, &'static str, bool) {
    match kind {
        std::io::ErrorKind::NotFound => (
            SqliteDiagnosticKind::DatabaseMissing,
            "SQLite database path does not exist",
            "create the containing directory and enable create_if_missing when intended",
            false,
        ),
        std::io::ErrorKind::PermissionDenied => (
            SqliteDiagnosticKind::PermissionDenied,
            "SQLite database path is not accessible",
            "grant access to the database file and its containing directory",
            false,
        ),
        std::io::ErrorKind::TimedOut
        | std::io::ErrorKind::Interrupted
        | std::io::ErrorKind::WouldBlock => (
            SqliteDiagnosticKind::Unavailable,
            "SQLite storage is temporarily unavailable",
            "retry after checking storage availability and lock contention",
            true,
        ),
        _ => (
            SqliteDiagnosticKind::Unavailable,
            "SQLite storage I/O failed",
            "check the database file, containing directory, and storage health",
            false,
        ),
    }
}