footing 0.4.3

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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
//! PostgreSQL connection, bootstrap, migration, health, and transaction runtime.

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

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

use crate::{
    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::{connect_options, 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_with(connect_options(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_with(connect_options(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.
/// Before migrations, the connected database must match the configured name;
/// PostgreSQL's truncated startup-name aliases are rejected.
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.ensure_database_timeout,
            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 a database exists within one total deadline covering connection,
/// existence checks and creation. A timeout cancels the local operation;
/// the database may already have been created on the server.
/// Names exceeding the server's identifier limit are rejected before creation.
pub async fn ensure_database_exists(
    database_url: &str,
    timeout: Duration,
) -> Result<(), sqlx::Error> {
    ensure_database_exists_with_retry(
        database_url,
        timeout,
        PostgresStartupRetryConfig::disabled(),
    )
    .await
}

async fn ensure_database_with_options(
    options: sqlx::postgres::PgConnectOptions,
) -> Result<(), sqlx::Error> {
    let database = options
        .get_database()
        .unwrap_or(options.get_username())
        .to_owned();
    let options = options.database(if database == "postgres" {
        "template1"
    } else {
        "postgres"
    });
    let mut connection = options.connect().await?;
    // CREATE DATABASE silently truncates identifiers. Validate using the
    // server's encoding and configured limit so creation cannot target an alias.
    let name_fits: bool = sqlx::query_scalar(
        "SELECT octet_length($1::text) <= current_setting('max_identifier_length')::int4",
    )
    .bind(&database)
    .fetch_one(&mut connection)
    .await?;
    if !name_fits {
        return Err(sqlx::Error::Configuration(
            "database name exceeds the server identifier limit".into(),
        ));
    }
    let exists = "SELECT EXISTS(SELECT 1 FROM pg_database WHERE datname = $1)";
    if sqlx::query_scalar::<_, bool>(exists)
        .bind(&database)
        .fetch_one(&mut connection)
        .await?
    {
        return Ok(());
    }

    // PostgreSQL identifiers cannot be bound; double each embedded quote and
    // quote the entire identifier before marking this statement as audited.
    let create = format!("CREATE DATABASE \"{}\"", database.replace('"', "\"\""));
    match sqlx::query(sqlx::AssertSqlSafe(create))
        .execute(&mut connection)
        .await
    {
        Ok(_) => Ok(()),
        Err(error) => match sqlx::query_scalar::<_, bool>(exists)
            .bind(&database)
            .fetch_one(&mut connection)
            .await
        {
            Ok(true) => Ok(()),
            Ok(false) | Err(_) => Err(error),
        },
    }
}

/// Ensures a database exists, retrying only transient failures.
///
/// The total deadline includes all attempts and retry delays. It must be
/// nonzero and fit the runtime timer range.
pub async fn ensure_database_exists_with_retry(
    database_url: &str,
    timeout: Duration,
    retry: PostgresStartupRetryConfig,
) -> Result<(), sqlx::Error> {
    let options = connect_options(database_url)?;
    let deadline = tokio::time::Instant::now()
        .checked_add(timeout)
        .filter(|_| !timeout.is_zero())
        .ok_or_else(|| {
            sqlx::Error::Configuration(
                "database creation timeout must be nonzero and fit the runtime timer range".into(),
            )
        })?;
    tokio::time::timeout_at(
        deadline,
        retry_async(
            database_url,
            retry,
            PostgresOperation::EnsureDatabase,
            || ensure_database_with_options(options.clone()),
        ),
    )
    .await
    .map_err(|_| {
        sqlx::Error::Io(std::io::Error::new(
            std::io::ErrorKind::TimedOut,
            "PostgreSQL database creation deadline elapsed",
        ))
    })?
}

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

/// 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(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 remaining = remaining_timeout(started, timeout)?;
    guard.armed = true;
    let resolved_database_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)?;
    // Startup database names can be silently truncated before connection.
    // Never use an unverified URL name for the schema-maintenance lock or
    // permit destructive maintenance against a different connected database.
    if known_database_name.is_some_and(|name| name != resolved_database_name) {
        return Err(SessionAdvisoryLockAcquireError::Sqlx(
            sqlx::Error::Configuration(
                "configured database name does not match the connected database".into(),
            ),
        ));
    }
    guard.armed = false;
    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 {
        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> {
    let options = connect_options(database_url)?;
    retry_async(database_url, retry, PostgresOperation::Connect, || {
        pool_options(config).connect_with(options.clone())
    })
    .await
    .map_err(PostgresPoolError::Sqlx)
}

/// 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, F, Fut>(
    database_url: &str,
    retry: PostgresStartupRetryConfig,
    operation: PostgresOperation,
    mut run: F,
) -> Result<T, sqlx::Error>
where
    F: FnMut() -> Fut,
    Fut: Future<Output = Result<T, sqlx::Error>>,
{
    let max_attempts = retry.max_attempts;
    let mut attempt = 1_u32;
    let mut delay = retry.initial_delay;

    loop {
        match run().await {
            Ok(value) => return Ok(value),
            Err(error)
                if attempt >= max_attempts
                    || !diagnose_sqlx_error(operation, database_url, &error).retryable() =>
            {
                return Err(error);
            }
            Err(_) => {
                let retry_delay = if retry.jitter {
                    crate::jitter::retry_delay(delay)
                } else {
                    delay
                };
                tracing::warn!(
                    attempt,
                    max_attempts,
                    retry_after_ms = retry_delay.as_millis(),
                    operation = operation.as_str(),
                    "PostgreSQL startup operation failed; retrying"
                );
                tokio::time::sleep(retry_delay).await;
                attempt += 1;
                delay = delay.saturating_mul(2).min(retry.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
}

#[cfg(test)]
mod retry_tests {
    use super::*;

    #[tokio::test(start_paused = true)]
    async fn jitter_preserves_attempt_limits_error_classification_and_exponential_progression() {
        let retry = super::super::PostgresStartupRetrySettings::default()
            .with_max_attempts(5)
            .with_initial_delay(Duration::from_secs(1))
            .with_max_delay(Duration::from_secs(3))
            .with_jitter(true)
            .build()
            .unwrap();
        for permanent in [true, false] {
            let mut starts = Vec::new();
            let result: Result<(), _> = retry_async(
                "postgres://localhost/app",
                retry,
                PostgresOperation::Connect,
                || {
                    starts.push(tokio::time::Instant::now());
                    std::future::ready(Err(if permanent {
                        sqlx::Error::Configuration("invalid configuration".into())
                    } else {
                        sqlx::Error::Io(std::io::ErrorKind::ConnectionRefused.into())
                    }))
                },
            )
            .await;
            assert!(result.is_err());
            assert_eq!(starts.len(), if permanent { 1 } else { 5 });
            for (pair, base_secs) in starts.windows(2).zip([1, 2, 3, 3]) {
                let base = Duration::from_secs(base_secs);
                let gap = pair[1] - pair[0];
                // Tokio may round a sampled nanosecond delay up to a millisecond.
                let upper = base + Duration::from_millis(1);
                assert!(
                    (base / 2..=upper).contains(&gap),
                    "gap: {gap:?}, base: {base:?}"
                );
            }
        }
    }

    #[tokio::test(start_paused = true)]
    async fn permanent_startup_failures_do_not_retry_but_transient_failures_do() {
        let retry = super::super::PostgresStartupRetrySettings::default()
            .with_max_attempts(3)
            .build()
            .unwrap();
        for permanent in [true, false] {
            let mut attempts = 0;
            let start = tokio::time::Instant::now();
            let result: Result<(), _> = retry_async(
                "postgres://localhost/app",
                retry,
                PostgresOperation::Connect,
                || {
                    attempts += 1;
                    std::future::ready(Err(if permanent {
                        sqlx::Error::Configuration("invalid configuration".into())
                    } else {
                        sqlx::Error::Io(std::io::ErrorKind::ConnectionRefused.into())
                    }))
                },
            )
            .await;
            assert!(result.is_err());
            assert_eq!(attempts, if permanent { 1 } else { 3 });
            assert_eq!(
                start.elapsed(),
                if permanent {
                    Duration::ZERO
                } else {
                    Duration::from_millis(750)
                }
            );
        }
    }

    #[tokio::test(start_paused = true)]
    async fn server_restarts_retry_and_recover_but_authentication_and_permissions_do_not() {
        use super::super::{PostgresDiagnosticKind, tests::TestDatabaseError};

        let retry = super::super::PostgresStartupRetrySettings::default()
            .with_max_attempts(3)
            .build()
            .unwrap();
        for code in ["57P01", "57P02", "57P03", "28P01", "28000", "42501"] {
            let transient = code.starts_with("57");
            let mut attempts = 0;
            let started = tokio::time::Instant::now();
            let result = retry_async(
                "postgres://localhost/app",
                retry,
                PostgresOperation::EnsureDatabase,
                || {
                    attempts += 1;
                    let result = if attempts == 1 {
                        let error = sqlx::Error::Database(Box::new(TestDatabaseError {
                            code,
                            message: "private server error detail",
                        }));
                        let diagnostic = diagnose_sqlx_error(
                            PostgresOperation::EnsureDatabase,
                            "postgres://localhost/app",
                            &error,
                        );
                        assert_eq!(diagnostic.retryable(), transient);
                        if transient {
                            assert_eq!(
                                diagnostic.kind(),
                                PostgresDiagnosticKind::ConnectionUnavailable
                            );
                        }
                        Err(error)
                    } else {
                        Ok(())
                    };
                    std::future::ready(result)
                },
            )
            .await;
            assert_eq!(result.is_ok(), transient);
            assert_eq!(attempts, if transient { 2 } else { 1 });
            assert_eq!(
                started.elapsed(),
                if transient {
                    retry.initial_delay
                } else {
                    Duration::ZERO
                }
            );
        }
    }

    #[tokio::test(start_paused = true)]
    async fn invalid_url_is_not_retried() {
        let retry = super::super::PostgresStartupRetrySettings::default()
            .with_max_attempts(3)
            .build()
            .unwrap();
        let start = tokio::time::Instant::now();
        assert!(
            connect_pool_with_retry("sqlite::memory:", PostgresPoolConfig::default(), retry)
                .await
                .is_err()
        );
        assert!(
            ensure_database_exists_with_retry("sqlite::memory:", Duration::from_secs(1), retry)
                .await
                .is_err()
        );
        assert_eq!(start.elapsed(), Duration::ZERO);
    }

    #[tokio::test]
    async fn database_creation_deadline_covers_a_stalled_handshake_and_all_retries() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let url = format!(
            "postgres://app:secret@{}/app?sslmode=disable",
            listener.local_addr().unwrap()
        );
        let server = tokio::spawn(async move {
            let (_socket, _) = listener.accept().await.unwrap();
            std::future::pending::<()>().await;
        });
        let retry = super::super::PostgresStartupRetrySettings::default()
            .with_max_attempts(3)
            .build()
            .unwrap();
        let error = tokio::time::timeout(
            Duration::from_secs(2),
            ensure_database_exists_with_retry(&url, Duration::from_millis(30), retry),
        )
        .await
        .expect("the complete operation must be bounded")
        .unwrap_err();
        assert!(
            matches!(error, sqlx::Error::Io(ref io) if io.kind() == std::io::ErrorKind::TimedOut)
        );
        server.abort();
    }

    #[tokio::test(start_paused = true)]
    async fn creation_deadline_includes_retry_delay() {
        // A bound, non-listening TCP socket reserves a port while refusing
        // connections, so no other test can take the address between attempts.
        let socket = tokio::net::TcpSocket::new_v4().unwrap();
        socket.bind("127.0.0.1:0".parse().unwrap()).unwrap();
        let url = format!(
            "postgres://app@{}/app?sslmode=disable",
            socket.local_addr().unwrap()
        );
        let retry = super::super::PostgresStartupRetrySettings::default()
            .with_max_attempts(3)
            .build()
            .unwrap();
        let started = tokio::time::Instant::now();
        let error = ensure_database_exists_with_retry(&url, Duration::from_millis(30), retry)
            .await
            .unwrap_err();
        assert!(
            matches!(error, sqlx::Error::Io(ref io) if io.kind() == std::io::ErrorKind::TimedOut)
        );
        assert_eq!(started.elapsed(), Duration::from_millis(30));
    }
}