footing 0.1.12

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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
//! PostgreSQL connection, bootstrap, migration, health, and transaction runtime.

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

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

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

use super::{
    config::{
        DEFAULT_POSTGRES_ADVISORY_LOCK_TIMEOUT, DEFAULT_POSTGRES_MIGRATION_TIMEOUT,
        PostgresBootstrapConfig, PostgresPoolConfig, PostgresStartupRetryConfig,
    },
    diagnostics::{
        PostgresBootstrapError, PostgresOperation, PostgresPoolError, diagnose_migration_error,
        diagnose_migration_lock_timeout, diagnose_operation_timeout, diagnose_pool_error,
        diagnose_sqlx_error,
    },
    identity::{database_name, schema_maintenance_advisory_lock_key},
};

/// 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 {
    PgPoolOptions::new()
        .max_connections(config.max_connections)
        .min_connections(config.min_connections)
        .acquire_timeout(config.acquire_timeout)
        .test_before_acquire(config.test_before_acquire)
        .idle_timeout(config.idle_timeout)
        .max_lifetime(config.max_lifetime)
}

/// 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 Err(error) = run_migrations_for_database(
            &pool,
            migrator,
            database_name(database_url).as_deref(),
            config.migration_lock_key,
            config.migration_lock_timeout,
            config.migration_timeout,
        )
        .await
        {
            return Err(bootstrap_migration_run_error(database_url, error));
        }
    }

    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, "postgres_ensure_database_failed", || {
        ensure_database_exists(database_url)
    })
    .await
}

/// Runs migrations under the database-scoped schema-maintenance lock.
///
/// Both lock acquisition and migration execution have non-zero default
/// deadlines. Use [`run_migrations_with_timeouts`] to configure them.
pub async fn run_migrations(
    pool: &PgPool,
    migrator: &Migrator,
) -> Result<(), PostgresMigrationRunError> {
    run_migrations_with_timeouts(
        pool,
        migrator,
        None,
        DEFAULT_POSTGRES_ADVISORY_LOCK_TIMEOUT,
        DEFAULT_POSTGRES_MIGRATION_TIMEOUT,
    )
    .await
}

#[derive(Error)]
#[non_exhaustive]
/// Errors that can occur while handling PostgreSQL migration run.
pub enum PostgresMigrationRunError {
    #[error("failed to acquire PostgreSQL schema-maintenance lock for migrations")]
    /// Indicates lock.
    Lock(#[source] sqlx::Error),
    #[error("timed out waiting for PostgreSQL schema-maintenance lock after {timeout:?}")]
    /// The lock remained busy beyond the configured deadline.
    LockTimeout {
        /// Configured lock wait deadline.
        timeout: Duration,
    },
    #[error("failed to run PostgreSQL migrations")]
    /// Indicates migration.
    Migration {
        /// The kind value.
        kind: MigrationFailureKind,
        #[source]
        /// The source value.
        source: Box<MigrateError>,
    },
    #[error("timed out while running PostgreSQL migrations after {timeout:?}")]
    /// Migration execution exceeded its configured deadline.
    MigrationTimeout {
        /// Configured migration execution deadline.
        timeout: Duration,
    },
}

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 {
        match self {
            Self::LockTimeout { .. } | Self::MigrationTimeout { .. } => ErrorKind::Timeout,
            Self::Lock(_) | Self::Migration { .. } => ErrorKind::Dependency,
        }
    }

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

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

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::LockTimeout { timeout } => {
            PostgresBootstrapError::MigrationLockTimeout {
                diagnosis: diagnose_migration_lock_timeout(database_url, timeout),
                timeout,
            }
        }
        PostgresMigrationRunError::Migration { kind, source } => {
            PostgresBootstrapError::Migration {
                diagnosis: diagnose_migration_error(database_url, &source),
                kind,
                source,
            }
        }
        PostgresMigrationRunError::MigrationTimeout { timeout } => {
            PostgresBootstrapError::MigrationTimeout {
                diagnosis: diagnose_operation_timeout(
                    PostgresOperation::Migrate,
                    database_url,
                    timeout,
                ),
                timeout,
            }
        }
    }
}

/// Runs migrations with an additional advisory lock.
pub async fn run_migrations_with_advisory_lock(
    pool: &PgPool,
    migrator: &Migrator,
    lock_key: i64,
) -> Result<(), PostgresMigrationRunError> {
    run_migrations_with_advisory_lock_timeout(
        pool,
        migrator,
        lock_key,
        DEFAULT_POSTGRES_ADVISORY_LOCK_TIMEOUT,
    )
    .await
}

/// Runs migrations with an additional advisory lock and bounded lock wait.
///
/// The supplied key is additional to the mandatory database-scoped
/// schema-maintenance lock. A duplicate key is acquired only once.
pub async fn run_migrations_with_advisory_lock_timeout(
    pool: &PgPool,
    migrator: &Migrator,
    lock_key: i64,
    lock_timeout: Duration,
) -> Result<(), PostgresMigrationRunError> {
    run_migrations_with_timeouts(
        pool,
        migrator,
        Some(lock_key),
        lock_timeout,
        DEFAULT_POSTGRES_MIGRATION_TIMEOUT,
    )
    .await
}

/// Runs migrations with independently bounded lock and execution deadlines.
///
/// `additional_lock_key` is optional coordination with an external lock
/// domain. The database-scoped schema-maintenance lock is always held.
pub async fn run_migrations_with_timeouts(
    pool: &PgPool,
    migrator: &Migrator,
    additional_lock_key: Option<i64>,
    lock_timeout: Duration,
    migration_timeout: Duration,
) -> Result<(), PostgresMigrationRunError> {
    run_migrations_for_database(
        pool,
        migrator,
        None,
        additional_lock_key,
        lock_timeout,
        migration_timeout,
    )
    .await
}

async fn run_migrations_for_database(
    pool: &PgPool,
    migrator: &Migrator,
    known_database_name: Option<&str>,
    additional_lock_key: Option<i64>,
    lock_timeout: Duration,
    migration_timeout: Duration,
) -> Result<(), PostgresMigrationRunError> {
    if migration_timeout.is_zero() || Instant::now().checked_add(migration_timeout).is_none() {
        return Err(PostgresMigrationRunError::MigrationTimeout {
            timeout: migration_timeout,
        });
    }
    let mut lock_guard = acquire_schema_maintenance_session_lock(
        pool,
        known_database_name,
        additional_lock_key,
        lock_timeout,
    )
    .await
    .map_err(map_migration_lock_error)?;

    let migration_result = tokio::time::timeout(
        migration_timeout,
        migrator.run(&mut **lock_guard.connection()),
    )
    .await;
    match migration_result {
        Ok(Ok(())) => lock_guard
            .release_with_timeout(lock_timeout)
            .await
            .map_err(PostgresMigrationRunError::Lock),
        Ok(Err(source)) => Err(PostgresMigrationRunError::Migration {
            kind: MigrationFailureKind::from_error(&source),
            source: Box::new(source),
        }),
        Err(_) => Err(PostgresMigrationRunError::MigrationTimeout {
            timeout: migration_timeout,
        }),
    }
}

fn map_migration_lock_error(error: SessionAdvisoryLockAcquireError) -> PostgresMigrationRunError {
    match error {
        SessionAdvisoryLockAcquireError::Sqlx(source) => PostgresMigrationRunError::Lock(source),
        SessionAdvisoryLockAcquireError::Timeout { timeout } => {
            PostgresMigrationRunError::LockTimeout { timeout }
        }
    }
}

#[derive(Debug)]
pub(super) enum SessionAdvisoryLockAcquireError {
    Sqlx(sqlx::Error),
    Timeout { timeout: Duration },
}

pub(super) struct SessionAdvisoryLockGuard {
    connection: PoolConnection<Postgres>,
    lock_keys: Vec<i64>,
    armed: bool,
}

impl SessionAdvisoryLockGuard {
    fn new(connection: PoolConnection<Postgres>) -> Self {
        Self {
            connection,
            lock_keys: Vec::with_capacity(2),
            armed: false,
        }
    }

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

    pub(super) async fn release_with_timeout(
        mut self,
        timeout: Duration,
    ) -> Result<(), sqlx::Error> {
        let started = Instant::now();
        while let Some(lock_key) = self.lock_keys.pop() {
            let remaining = timeout
                .checked_sub(started.elapsed())
                .filter(|remaining| !remaining.is_zero())
                .ok_or(sqlx::Error::PoolTimedOut)?;
            let result: Result<bool, sqlx::Error> = tokio::time::timeout(
                remaining,
                sqlx::query_scalar("SELECT pg_advisory_unlock($1)")
                    .bind(lock_key)
                    .fetch_one(&mut *self.connection),
            )
            .await
            .map_err(|_| sqlx::Error::PoolTimedOut)?;
            match result {
                Ok(true) => {}
                Ok(false) => {
                    return Err(sqlx::Error::Protocol(
                        "PostgreSQL advisory lock ownership was lost before release".to_owned(),
                    ));
                }
                Err(error) => return Err(error),
            }
        }
        self.armed = false;
        Ok(())
    }
}

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

pub(super) async fn acquire_schema_maintenance_session_lock(
    pool: &PgPool,
    known_database_name: Option<&str>,
    additional_lock_key: Option<i64>,
    timeout: Duration,
) -> Result<SessionAdvisoryLockGuard, SessionAdvisoryLockAcquireError> {
    if timeout.is_zero() || Instant::now().checked_add(timeout).is_none() {
        return Err(SessionAdvisoryLockAcquireError::Timeout { timeout });
    }

    let started = Instant::now();
    let remaining = remaining_timeout(started, timeout)?;
    let connection = tokio::time::timeout(remaining, pool.acquire())
        .await
        .map_err(|_| SessionAdvisoryLockAcquireError::Timeout { timeout })?
        .map_err(SessionAdvisoryLockAcquireError::Sqlx)?;
    let mut guard = SessionAdvisoryLockGuard::new(connection);

    let resolved_database_name = if let Some(name) = known_database_name {
        name.to_owned()
    } else {
        let remaining = remaining_timeout(started, timeout)?;
        guard.armed = true;
        let name: String = tokio::time::timeout(
            remaining,
            sqlx::query_scalar("SELECT current_database()").fetch_one(&mut **guard.connection()),
        )
        .await
        .map_err(|_| SessionAdvisoryLockAcquireError::Timeout { timeout })?
        .map_err(SessionAdvisoryLockAcquireError::Sqlx)?;
        guard.armed = false;
        name
    };
    let lock_keys = schema_maintenance_lock_keys(&resolved_database_name, additional_lock_key);
    acquire_locks_on_guard(guard, &lock_keys, started, timeout).await
}

pub(super) fn schema_maintenance_lock_keys(
    database_name: &str,
    additional_lock_key: Option<i64>,
) -> Vec<i64> {
    let maintenance_key = schema_maintenance_advisory_lock_key(database_name);
    let mut lock_keys = Vec::with_capacity(2);
    lock_keys.push(maintenance_key);
    if let Some(additional_key) = additional_lock_key
        && additional_key != maintenance_key
    {
        lock_keys.push(additional_key);
    }
    lock_keys
}

async fn acquire_locks_on_guard(
    mut guard: SessionAdvisoryLockGuard,
    lock_keys: &[i64],
    started: Instant,
    timeout: Duration,
) -> Result<SessionAdvisoryLockGuard, SessionAdvisoryLockAcquireError> {
    for &lock_key in lock_keys {
        if guard.lock_keys.contains(&lock_key) {
            continue;
        }

        loop {
            let remaining = remaining_timeout(started, timeout)?;

            // Once the query is sent, cancellation is ambiguous: PostgreSQL
            // may have acquired the session lock even if the response misses
            // our client deadline. Keep the guard armed on every ambiguous
            // exit so dropping it closes the session.
            guard.armed = true;
            let acquired = tokio::time::timeout(
                remaining,
                sqlx::query_scalar("SELECT pg_try_advisory_lock($1)")
                    .bind(lock_key)
                    .fetch_one(&mut **guard.connection()),
            )
            .await
            .map_err(|_| SessionAdvisoryLockAcquireError::Timeout { timeout })?
            .map_err(SessionAdvisoryLockAcquireError::Sqlx)?;
            if acquired {
                guard.lock_keys.push(lock_key);
                break;
            }
            guard.armed = !guard.lock_keys.is_empty();

            let remaining = remaining_timeout(started, timeout)?;
            tokio::time::sleep(remaining.min(Duration::from_millis(50))).await;
        }
    }
    Ok(guard)
}

fn remaining_timeout(
    started: Instant,
    timeout: Duration,
) -> Result<Duration, SessionAdvisoryLockAcquireError> {
    timeout
        .checked_sub(started.elapsed())
        .filter(|remaining| !remaining.is_zero())
        .ok_or(SessionAdvisoryLockAcquireError::Timeout { timeout })
}

/// 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, "postgres_connect_failed", || {
        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";

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,
    error_code: &'static str,
    mut operation: F,
) -> Result<T, E>
where
    F: FnMut() -> Fut,
    Fut: Future<Output = Result<T, E>>,
{
    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(),
                    error_code,
                    "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>;

/// 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
}