footing 0.1.1

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
//! PostgreSQL connection, bootstrap, migration, health, and transaction runtime.

use std::{
    borrow::Cow,
    fmt,
    future::Future,
    str::FromStr,
    time::{Duration, Instant},
};

use sqlx::{
    PgPool, Postgres, Transaction,
    migrate::{MigrateDatabase, MigrateError, Migrator},
    pool::PoolConnection,
    postgres::{PgConnectOptions, PgPoolOptions},
};
use thiserror::Error;

use crate::{
    result::{ClassifyError, ErrorDescriptor, ErrorKind},
    secret::ExposeSecret,
};

use super::{
    config::{PostgresBootstrapConfig, PostgresPoolConfig, PostgresStartupRetryConfig},
    diagnostics::{
        MigrationFailureKind, PostgresBootstrapError, PostgresOperation, PostgresPoolError,
        diagnose_migration_error, diagnose_pool_error, diagnose_sqlx_error,
    },
};

/// Connects a PostgreSQL pool using validated configuration.
pub async fn connect_pool(
    database_url: &str,
    config: PostgresPoolConfig,
) -> Result<PgPool, PostgresPoolError> {
    Ok(pool_options(config).connect(database_url).await?)
}

/// Creates a lazily connected PostgreSQL pool using validated configuration.
pub fn connect_lazy_pool(
    database_url: &str,
    config: PostgresPoolConfig,
) -> Result<PgPool, PostgresPoolError> {
    Ok(pool_options(config).connect_lazy(database_url)?)
}

/// Converts validated pool configuration into SQLx pool options.
#[must_use]
pub fn pool_options(config: PostgresPoolConfig) -> PgPoolOptions {
    let mut options = PgPoolOptions::new()
        .max_connections(config.max_connections)
        .min_connections(config.min_connections)
        .acquire_timeout(config.acquire_timeout)
        .test_before_acquire(config.test_before_acquire);

    if let Some(idle_timeout) = config.idle_timeout {
        options = options.idle_timeout(idle_timeout);
    }

    if let Some(max_lifetime) = config.max_lifetime {
        options = options.max_lifetime(max_lifetime);
    }

    options
}

/// Creates, connects, and optionally migrates a PostgreSQL database.
pub async fn bootstrap_database(
    config: PostgresBootstrapConfig,
    migrator: Option<&Migrator>,
) -> Result<PgPool, PostgresBootstrapError> {
    let migrator = if config.migrate_on_startup {
        Some(migrator.ok_or(PostgresBootstrapError::MissingMigrator)?)
    } else {
        None
    };
    let database_url = config.database_url.expose_secret();

    if config.create_on_startup {
        tracing::info!(
            database = %display_database_name(database_url),
            "ensuring PostgreSQL database exists"
        );
        ensure_database_exists_with_retry(database_url, config.startup_retry)
            .await
            .map_err(|source| PostgresBootstrapError::EnsureDatabase {
                diagnosis: diagnose_sqlx_error(
                    PostgresOperation::EnsureDatabase,
                    database_url,
                    &source,
                ),
                source: Box::new(source),
            })?;
    }

    let pool = connect_pool_with_retry(database_url, config.pool_config, config.startup_retry)
        .await
        .map_err(|source| PostgresBootstrapError::Connect {
            diagnosis: diagnose_pool_error(PostgresOperation::Connect, database_url, &source),
            source: Box::new(source),
        })?;

    if let Some(migrator) = migrator {
        tracing::info!(
            database = %display_database_name(database_url),
            "running PostgreSQL database migrations"
        );
        if let Some(key) = config.migration_lock_key {
            if let Err(error) = run_migrations_with_advisory_lock(&pool, migrator, key).await {
                return Err(bootstrap_migration_run_error(database_url, error));
            }
        } else {
            run_migrations(&pool, migrator).await.map_err(|source| {
                PostgresBootstrapError::Migration {
                    diagnosis: diagnose_migration_error(database_url, &source),
                    kind: MigrationFailureKind::from_error(&source),
                    source: Box::new(source),
                }
            })?;
        }
    }

    Ok(pool)
}

/// Ensures database exists.
pub async fn ensure_database_exists(database_url: &str) -> Result<(), sqlx::Error> {
    if Postgres::database_exists(database_url).await? {
        return Ok(());
    }

    match Postgres::create_database(database_url).await {
        Ok(()) => Ok(()),
        Err(error) => match Postgres::database_exists(database_url).await {
            Ok(true) => Ok(()),
            Ok(false) | Err(_) => Err(error),
        },
    }
}

/// Ensures database exists with retry.
pub async fn ensure_database_exists_with_retry(
    database_url: &str,
    retry: PostgresStartupRetryConfig,
) -> Result<(), sqlx::Error> {
    retry_async(retry, || ensure_database_exists(database_url)).await
}

/// Runs migrations.
pub async fn run_migrations(pool: &PgPool, migrator: &Migrator) -> Result<(), MigrateError> {
    migrator.run(pool).await
}

#[derive(Error)]
#[non_exhaustive]
/// Errors that can occur while handling PostgreSQL migration run.
pub enum PostgresMigrationRunError {
    #[error("failed to acquire PostgreSQL migration advisory lock")]
    /// Indicates lock.
    Lock(#[source] sqlx::Error),
    #[error("failed to run PostgreSQL migrations")]
    /// Indicates migration.
    Migration {
        /// The kind value.
        kind: MigrationFailureKind,
        #[source]
        /// The source value.
        source: Box<MigrateError>,
    },
}

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

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

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::Lock(_) => "postgres_migration_lock_failed",
            Self::Migration { .. } => "postgres_migration_failed",
        })
    }

    fn error_descriptor(&self) -> ErrorDescriptor {
        ErrorDescriptor::new(self.error_kind(), self.error_code(), self.to_string())
            .with_retryable(matches!(self, Self::Lock(_)))
    }
}

impl From<PostgresMigrationRunError> for PostgresBootstrapError {
    fn from(error: PostgresMigrationRunError) -> Self {
        bootstrap_migration_run_error("", error)
    }
}

fn bootstrap_migration_run_error(
    database_url: &str,
    error: PostgresMigrationRunError,
) -> PostgresBootstrapError {
    match error {
        PostgresMigrationRunError::Lock(source) => PostgresBootstrapError::MigrationLock {
            diagnosis: diagnose_sqlx_error(PostgresOperation::MigrationLock, database_url, &source),
            source: Box::new(source),
        },
        PostgresMigrationRunError::Migration { kind, source } => {
            PostgresBootstrapError::Migration {
                diagnosis: diagnose_migration_error(database_url, &source),
                kind,
                source,
            }
        }
    }
}

/// Runs migrations with advisory lock.
pub async fn run_migrations_with_advisory_lock(
    pool: &PgPool,
    migrator: &Migrator,
    lock_key: i64,
) -> Result<(), PostgresMigrationRunError> {
    let mut connection = pool
        .acquire()
        .await
        .map_err(PostgresMigrationRunError::Lock)?;
    let mut lock_guard = SessionAdvisoryLockGuard::new(&mut connection);
    sqlx::query("SELECT pg_advisory_lock($1)")
        .bind(lock_key)
        .execute(&mut **lock_guard.connection())
        .await
        .map_err(PostgresMigrationRunError::Lock)?;

    let migration_result = migrator.run(&mut **lock_guard.connection()).await;
    let unlock_result = sqlx::query("SELECT pg_advisory_unlock($1)")
        .bind(lock_key)
        .execute(&mut **lock_guard.connection())
        .await;
    if unlock_result.is_ok() {
        lock_guard.disarm();
    }

    if let Err(source) = migration_result {
        return Err(PostgresMigrationRunError::Migration {
            kind: MigrationFailureKind::from_error(&source),
            source: Box::new(source),
        });
    }
    unlock_result.map_err(PostgresMigrationRunError::Lock)?;
    Ok(())
}

struct SessionAdvisoryLockGuard<'a> {
    connection: &'a mut PoolConnection<Postgres>,
    armed: bool,
}

impl<'a> SessionAdvisoryLockGuard<'a> {
    fn new(connection: &'a mut PoolConnection<Postgres>) -> Self {
        Self {
            connection,
            armed: true,
        }
    }

    fn connection(&mut self) -> &mut PoolConnection<Postgres> {
        self.connection
    }

    fn disarm(&mut self) {
        self.armed = false;
    }
}

impl Drop for SessionAdvisoryLockGuard<'_> {
    fn drop(&mut self) {
        if self.armed {
            self.connection.close_on_drop();
        }
    }
}

/// Verifies that a pool can execute a simple query.
pub async fn ping_pool(pool: &PgPool) -> Result<(), sqlx::Error> {
    sqlx::query("SELECT 1").execute(pool).await?;
    Ok(())
}

/// Connects a PostgreSQL pool using the configured retry policy.
pub async fn connect_pool_with_retry(
    database_url: &str,
    config: PostgresPoolConfig,
    retry: PostgresStartupRetryConfig,
) -> Result<PgPool, PostgresPoolError> {
    retry_async(retry, || connect_pool(database_url, config)).await
}

/// Checks pool connectivity and returns a redacted health result.
pub async fn check_pool_health(pool: &PgPool) -> PostgresHealth {
    let started = Instant::now();
    match ping_pool(pool).await {
        Ok(()) => PostgresHealth {
            status: PostgresHealthStatus::Ready,
            latency: started.elapsed(),
        },
        Err(_) => PostgresHealth {
            status: PostgresHealthStatus::Unavailable,
            latency: started.elapsed(),
        },
    }
}

pub(super) const POSTGRES_HEALTH_ERROR: &str = "database health check failed";

#[must_use]
/// Extracts the database name from a PostgreSQL URL.
pub fn database_name(database_url: &str) -> Option<String> {
    PgConnectOptions::from_str(database_url)
        .ok()
        .and_then(|options| options.get_database().map(ToOwned::to_owned))
        .filter(|database| !database.trim().is_empty())
}

#[must_use]
/// Returns a redacted representation of database URL.
pub fn redact_database_url(database_url: &str) -> String {
    let Some((scheme, rest)) = database_url.split_once("://") else {
        return "<invalid-postgres-url>".to_owned();
    };

    let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
    let (authority, suffix) = rest.split_at(authority_end);
    let redacted_authority = match authority.rsplit_once('@') {
        Some((userinfo, host)) => {
            let redacted_userinfo = userinfo
                .split_once(':')
                .map(|(user, _)| format!("{user}:****"))
                .unwrap_or_else(|| "****".to_owned());
            format!("{redacted_userinfo}@{host}")
        }
        None => authority.to_owned(),
    };

    format!(
        "{scheme}://{redacted_authority}{}",
        redact_database_url_suffix(suffix)
    )
}

fn redact_database_url_suffix(suffix: &str) -> String {
    let (without_fragment, fragment) = suffix
        .split_once('#')
        .map_or((suffix, None), |(value, _)| (value, Some("#****")));
    let Some((path, query)) = without_fragment.split_once('?') else {
        return format!("{without_fragment}{}", fragment.unwrap_or_default());
    };

    let redacted_query = query
        .split('&')
        .map(|parameter| {
            parameter
                .split_once('=')
                .map_or_else(|| parameter.to_owned(), |(key, _)| format!("{key}=****"))
        })
        .collect::<Vec<_>>()
        .join("&");
    format!("{path}?{redacted_query}{}", fragment.unwrap_or_default())
}

fn display_database_name(database_url: &str) -> Cow<'_, str> {
    database_name(database_url)
        .map(Cow::Owned)
        .unwrap_or(Cow::Borrowed("<unknown>"))
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
/// Status of PostgreSQL health.
pub enum PostgresHealthStatus {
    /// Indicates ready.
    Ready,
    /// Indicates unavailable.
    Unavailable,
}

#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Represents PostgreSQL health.
pub struct PostgresHealth {
    pub(super) status: PostgresHealthStatus,
    pub(super) latency: Duration,
}

impl fmt::Debug for PostgresHealth {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("PostgresHealth")
            .field("status", &self.status)
            .field("latency", &self.latency)
            .field("has_error", &!self.ready())
            .finish()
    }
}

impl PostgresHealth {
    #[must_use]
    /// Returns the status.
    pub const fn status(&self) -> PostgresHealthStatus {
        self.status
    }

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

    #[must_use]
    /// Returns the redacted error summary.
    pub fn error(&self) -> Option<&str> {
        (!self.ready()).then_some(POSTGRES_HEALTH_ERROR)
    }

    #[must_use]
    /// Returns the ready.
    pub const fn ready(&self) -> bool {
        matches!(self.status, PostgresHealthStatus::Ready)
    }
}

async fn retry_async<T, E, F, Fut>(
    retry: PostgresStartupRetryConfig,
    mut operation: F,
) -> Result<T, E>
where
    F: FnMut() -> Fut,
    Fut: Future<Output = Result<T, E>>,
    E: std::fmt::Display,
{
    let max_attempts = retry.max_attempts.max(1);
    let mut attempt = 1_u32;
    let mut delay = if retry.initial_delay.is_zero() {
        PostgresStartupRetryConfig::default().initial_delay
    } else {
        retry.initial_delay
    };
    let max_delay = retry.max_delay.max(delay);

    loop {
        match operation().await {
            Ok(value) => return Ok(value),
            Err(error) if attempt >= max_attempts => return Err(error),
            Err(_) => {
                tracing::warn!(
                    attempt,
                    max_attempts,
                    retry_after_ms = delay.as_millis(),
                    "PostgreSQL startup operation failed; retrying"
                );
                tokio::time::sleep(delay).await;
                attempt = attempt.saturating_add(1);
                delay = delay.checked_mul(2).unwrap_or(Duration::MAX).min(max_delay);
            }
        }
    }
}

/// SQLx transaction specialized for PostgreSQL.
pub type PostgresTransaction<'a> = Transaction<'a, Postgres>;

/// Begins transaction.
pub async fn begin_transaction(pool: &PgPool) -> Result<PostgresTransaction<'_>, sqlx::Error> {
    pool.begin().await
}

/// Commits transaction.
pub async fn commit_transaction(transaction: PostgresTransaction<'_>) -> Result<(), sqlx::Error> {
    transaction.commit().await
}

/// Rolls back transaction.
pub async fn rollback_transaction(transaction: PostgresTransaction<'_>) -> Result<(), sqlx::Error> {
    transaction.rollback().await
}

#[must_use]
/// Derives a stable advisory-lock key from a namespace and name.
pub fn advisory_lock_key(namespace: &str, name: &str) -> i64 {
    const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
    const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;

    let mut hash = FNV_OFFSET;
    for byte in namespace
        .trim()
        .bytes()
        .chain([0])
        .chain(name.trim().bytes())
    {
        hash ^= u64::from(byte);
        hash = hash.wrapping_mul(FNV_PRIME);
    }

    i64::from_ne_bytes(hash.to_ne_bytes())
}

/// Acquires advisory transaction lock.
pub async fn acquire_advisory_transaction_lock(
    transaction: &mut PostgresTransaction<'_>,
    key: i64,
) -> Result<(), sqlx::Error> {
    sqlx::query("SELECT pg_advisory_xact_lock($1)")
        .bind(key)
        .execute(&mut **transaction)
        .await?;
    Ok(())
}

/// Acquires a transaction-scoped shared advisory lock.
///
/// Shared holders may proceed concurrently, while an exclusive holder for the
/// same key waits for every shared holder to finish (and vice versa). This is
/// useful for protecting read-side invariants without serializing readers.
pub async fn acquire_shared_advisory_transaction_lock(
    transaction: &mut PostgresTransaction<'_>,
    key: i64,
) -> Result<(), sqlx::Error> {
    sqlx::query("SELECT pg_advisory_xact_lock_shared($1)")
        .bind(key)
        .execute(&mut **transaction)
        .await?;
    Ok(())
}

/// Attempts to acquire advisory transaction lock.
pub async fn try_acquire_advisory_transaction_lock(
    transaction: &mut PostgresTransaction<'_>,
    key: i64,
) -> Result<bool, sqlx::Error> {
    sqlx::query_scalar("SELECT pg_try_advisory_xact_lock($1)")
        .bind(key)
        .fetch_one(&mut **transaction)
        .await
}