footing 0.6.5

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
//! Explicitly gated destructive PostgreSQL administration operations.

use std::{fmt, time::Duration};

use serde::{Deserialize, Serialize};
use sqlx::{
    Connection,
    migrate::{MigrateError, Migrator},
};
use thiserror::Error;

use crate::{
    result::{ClassifyError, ErrorDescriptor, ErrorKind},
    secret::{ExposeSecret, SecretString},
    settings::{SettingsIssues, SettingsValidationError, field_path},
};

use super::{
    PostgresConnectionConfig,
    config::{
        DEFAULT_POSTGRES_ADVISORY_LOCK_TIMEOUT, DEFAULT_POSTGRES_MIGRATION_TIMEOUT,
        PostgresPoolConfig, PostgresPoolSettings, default_ensure_database_timeout,
    },
    diagnostics::{
        PostgresDiagnostic, PostgresDiagnosticKind, PostgresOperation, PostgresPoolError,
        diagnose_migration_error, diagnose_operation_timeout, diagnose_pool_error,
        diagnose_sqlx_error,
    },
    identity::{connect_options, database_name},
    runtime::{
        SessionAdvisoryLockError, acquire_schema_maintenance_session_lock, connect_pool,
        ensure_database_exists,
    },
};

const SYSTEM_DATABASES: &[&str] = &["postgres", "template0", "template1"];

/// Default maximum time spent resetting the PostgreSQL public schema.
pub const DEFAULT_POSTGRES_RESET_SCHEMA_TIMEOUT: Duration = Duration::from_secs(60);

/// Default maximum time spent migrating immediately after a reset.
pub const DEFAULT_POSTGRES_RESET_MIGRATION_TIMEOUT: Duration = DEFAULT_POSTGRES_MIGRATION_TIMEOUT;

#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
/// Unvalidated settings for an explicit PostgreSQL reset operation.
///
/// The default secret representation is [`SecretString`], so the default type
/// intentionally does not implement [`serde::Serialize`]. A configuration
/// integration may opt into a serializable input representation through the
/// generic parameter. [`Self::build`] consumes a representation convertible to
/// [`SecretString`] and validates the converted value before building the reset
/// request.
pub struct PostgresResetSettings<S = SecretString> {
    /// PostgreSQL connection URL. Debug output always redacts this value.
    #[cfg_attr(feature = "tier", tier(secret, leaf))]
    pub database_url: S,
    /// Pool settings used during reset.
    pub pool: PostgresPoolSettings,
    /// Whether to create a missing database before resetting it.
    pub create_on_startup: bool,
    #[serde(
        default = "default_ensure_database_timeout",
        with = "crate::settings::human_duration"
    )]
    /// Maximum total time for checking or creating the database before reset.
    pub ensure_database_timeout: Duration,
    /// Whether to run migrations after resetting the schema.
    pub migrate_after_reset: bool,
    #[serde(
        default = "default_reset_lock_timeout",
        with = "crate::settings::human_duration"
    )]
    /// Maximum time for acquiring the schema-maintenance lock and, separately, releasing it.
    pub reset_lock_timeout: Duration,
    #[serde(
        default = "default_reset_schema_timeout",
        with = "crate::settings::human_duration"
    )]
    /// Maximum time to execute the transactional schema reset.
    pub reset_schema_timeout: Duration,
    #[serde(
        default = "default_post_reset_migration_timeout",
        with = "crate::settings::human_duration"
    )]
    /// Maximum time to run migrations after the schema reset.
    pub post_reset_migration_timeout: Duration,
}

impl<S> fmt::Debug for PostgresResetSettings<S> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("PostgresResetSettings")
            .field("database_url", &"[REDACTED]")
            .field("pool", &self.pool)
            .field("create_on_startup", &self.create_on_startup)
            .field("ensure_database_timeout", &self.ensure_database_timeout)
            .field("migrate_after_reset", &self.migrate_after_reset)
            .field("reset_lock_timeout", &self.reset_lock_timeout)
            .field("reset_schema_timeout", &self.reset_schema_timeout)
            .field(
                "post_reset_migration_timeout",
                &self.post_reset_migration_timeout,
            )
            .finish()
    }
}

impl<S> PostgresResetSettings<S> {
    /// Creates reset settings from an explicit secret representation.
    #[must_use]
    pub fn from_secret(database_url: S) -> Self {
        Self {
            database_url,
            pool: PostgresPoolSettings {
                max_connections: 1,
                ..PostgresPoolSettings::default()
            },
            create_on_startup: false,
            ensure_database_timeout: default_ensure_database_timeout(),
            migrate_after_reset: false,
            reset_lock_timeout: default_reset_lock_timeout(),
            reset_schema_timeout: default_reset_schema_timeout(),
            post_reset_migration_timeout: default_post_reset_migration_timeout(),
        }
    }

    /// Converts the database URL representation without exposing it.
    #[must_use]
    pub fn map_database_url<T>(self, map: impl FnOnce(S) -> T) -> PostgresResetSettings<T> {
        PostgresResetSettings {
            database_url: map(self.database_url),
            pool: self.pool,
            create_on_startup: self.create_on_startup,
            ensure_database_timeout: self.ensure_database_timeout,
            migrate_after_reset: self.migrate_after_reset,
            reset_lock_timeout: self.reset_lock_timeout,
            reset_schema_timeout: self.reset_schema_timeout,
            post_reset_migration_timeout: self.post_reset_migration_timeout,
        }
    }

    /// Replaces the reset pool settings.
    #[must_use]
    pub fn with_pool(mut self, pool: PostgresPoolSettings) -> Self {
        self.pool = pool;
        self
    }

    /// Enables or disables creation of a missing database.
    #[must_use]
    pub const fn with_create_on_startup(mut self, enabled: bool) -> Self {
        self.create_on_startup = enabled;
        self
    }

    /// Configures the total deadline for checking or creating the database.
    #[must_use]
    pub const fn with_ensure_database_timeout(mut self, timeout: Duration) -> Self {
        self.ensure_database_timeout = timeout;
        self
    }

    /// Enables or disables migrations after reset.
    #[must_use]
    pub const fn with_migrate_after_reset(mut self, enabled: bool) -> Self {
        self.migrate_after_reset = enabled;
        self
    }

    /// Sets the budget used separately for acquiring and releasing the schema-maintenance lock.
    #[must_use]
    pub const fn with_reset_lock_timeout(mut self, timeout: Duration) -> Self {
        self.reset_lock_timeout = timeout;
        self
    }

    /// Configures the maximum transactional schema reset time.
    #[must_use]
    pub const fn with_reset_schema_timeout(mut self, timeout: Duration) -> Self {
        self.reset_schema_timeout = timeout;
        self
    }

    /// Configures the maximum migration time after reset.
    #[must_use]
    pub const fn with_post_reset_migration_timeout(mut self, timeout: Duration) -> Self {
        self.post_reset_migration_timeout = timeout;
        self
    }

    /// Converts the secret representation and builds a reset request after all safety checks.
    pub fn build(self) -> Result<PostgresResetConfig, SettingsValidationError>
    where
        S: Into<SecretString>,
    {
        let settings: PostgresResetSettings = self.map_database_url(Into::into);
        settings.validate()?;
        let Some(database_name) = database_name(settings.database_url.expose_secret()) else {
            return Err(SettingsValidationError::single(
                "postgres.reset.database_url",
                "must contain a database name",
            ));
        };
        Ok(PostgresResetConfig {
            connection: PostgresConnectionConfig {
                database_url: settings.database_url,
                statement_timeout: None,
                idle_in_transaction_session_timeout: None,
            },
            database_name,
            pool_config: settings.pool.into_config(),
            create_on_startup: settings.create_on_startup,
            ensure_database_timeout: settings.ensure_database_timeout,
            migrate_after_reset: settings.migrate_after_reset,
            reset_lock_timeout: settings.reset_lock_timeout,
            reset_schema_timeout: settings.reset_schema_timeout,
            post_reset_migration_timeout: settings.post_reset_migration_timeout,
        })
    }
}

impl<S> PostgresResetSettings<S>
where
    S: ExposeSecret<str>,
{
    /// Validates the complete reset request.
    pub fn validate(&self) -> Result<(), SettingsValidationError> {
        self.validate_at("postgres.reset")
    }

    /// Validates settings using their location in the application configuration.
    ///
    /// `path` prefixes every reported field. An empty path reports fields at the
    /// document root; the supplied path is otherwise used unchanged.
    pub fn validate_at(&self, path: &str) -> Result<(), SettingsValidationError> {
        let mut issues = SettingsIssues::new();
        let database_url = self.database_url.expose_secret();
        issues.require_non_empty(field_path(path, "database_url"), database_url);
        issues.extend_result(self.pool.validate_at(&field_path(path, "pool")));
        match database_name(database_url) {
            Some(name) => {
                issues.require(
                    connect_options(database_url).is_ok(),
                    field_path(path, "database_url"),
                    "must be a valid PostgreSQL connection URL",
                );
                issues.require(
                    !SYSTEM_DATABASES.contains(&name.as_str()),
                    field_path(path, "database_url"),
                    "must not target a PostgreSQL system database",
                );
            }
            None if !database_url.trim().is_empty() => issues.push(
                field_path(path, "database_url"),
                "must contain a database name",
            ),
            None => {}
        }
        for (field, timeout) in [
            ("ensure_database_timeout", self.ensure_database_timeout),
            ("reset_lock_timeout", self.reset_lock_timeout),
            ("reset_schema_timeout", self.reset_schema_timeout),
            (
                "post_reset_migration_timeout",
                self.post_reset_migration_timeout,
            ),
        ] {
            issues.require(
                !timeout.is_zero() && std::time::Instant::now().checked_add(timeout).is_some(),
                field_path(path, field),
                "must be greater than zero and fit the runtime timer range",
            );
        }
        issues.into_result()
    }
}

impl PostgresResetSettings {
    /// Creates reset settings for a database URL.
    #[must_use]
    pub fn new(database_url: impl Into<String>) -> Self {
        Self::from_secret(SecretString::new(database_url))
    }
}

impl From<PostgresResetConfig> for PostgresResetSettings {
    fn from(value: PostgresResetConfig) -> Self {
        Self {
            database_url: value.connection.database_url,
            pool: PostgresPoolSettings::from(value.pool_config),
            create_on_startup: value.create_on_startup,
            ensure_database_timeout: value.ensure_database_timeout,
            migrate_after_reset: value.migrate_after_reset,
            reset_lock_timeout: value.reset_lock_timeout,
            reset_schema_timeout: value.reset_schema_timeout,
            post_reset_migration_timeout: value.post_reset_migration_timeout,
        }
    }
}

/// Validated immutable PostgreSQL reset request.
#[derive(Clone)]
#[non_exhaustive]
pub struct PostgresResetConfig {
    connection: PostgresConnectionConfig,
    database_name: String,
    pool_config: PostgresPoolConfig,
    create_on_startup: bool,
    ensure_database_timeout: Duration,
    migrate_after_reset: bool,
    reset_lock_timeout: Duration,
    reset_schema_timeout: Duration,
    post_reset_migration_timeout: Duration,
}

impl fmt::Debug for PostgresResetConfig {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("PostgresResetConfig")
            .field("database_url", &"[REDACTED]")
            .field("database_name", &self.database_name)
            .field("pool_config", &self.pool_config)
            .field("create_on_startup", &self.create_on_startup)
            .field("ensure_database_timeout", &self.ensure_database_timeout)
            .field("migrate_after_reset", &self.migrate_after_reset)
            .field("reset_lock_timeout", &self.reset_lock_timeout)
            .field("reset_schema_timeout", &self.reset_schema_timeout)
            .field(
                "post_reset_migration_timeout",
                &self.post_reset_migration_timeout,
            )
            .finish()
    }
}

impl PostgresResetConfig {
    #[must_use]
    /// Returns the total deadline for checking or creating the database.
    pub const fn ensure_database_timeout(&self) -> Duration {
        self.ensure_database_timeout
    }

    #[must_use]
    /// Returns the redacting database URL wrapper.
    pub const fn database_url(&self) -> &SecretString {
        self.connection.database_url()
    }

    #[must_use]
    /// Returns the migrate after reset.
    pub const fn migrate_after_reset(&self) -> bool {
        self.migrate_after_reset
    }

    #[must_use]
    /// Returns the budget used separately for acquiring and releasing the schema-maintenance lock.
    pub const fn reset_lock_timeout(&self) -> Duration {
        self.reset_lock_timeout
    }

    #[must_use]
    /// Returns the maximum transactional schema reset time.
    pub const fn reset_schema_timeout(&self) -> Duration {
        self.reset_schema_timeout
    }

    #[must_use]
    /// Returns the maximum migration time after reset.
    pub const fn post_reset_migration_timeout(&self) -> Duration {
        self.post_reset_migration_timeout
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Outcome of PostgreSQL reset.
pub struct PostgresResetOutcome {
    database_name: String,
    migrated: bool,
}

impl PostgresResetOutcome {
    #[must_use]
    /// Returns the database name.
    pub fn database_name(&self) -> &str {
        &self.database_name
    }

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

#[derive(Error)]
#[non_exhaustive]
/// Errors that can occur while handling PostgreSQL reset.
pub enum PostgresResetError {
    #[error("migrate_after_reset requires a SQLx migrator")]
    /// The required migrator is missing.
    MissingMigrator,
    #[error("failed to ensure PostgreSQL database exists before reset: {diagnosis}")]
    /// Indicates ensure database.
    EnsureDatabase {
        /// The diagnosis value.
        diagnosis: PostgresDiagnostic,
        #[source]
        /// The source value.
        source: Box<sqlx::Error>,
    },
    #[error("failed to connect to PostgreSQL: {diagnosis}")]
    /// Indicates connect.
    Connect {
        /// The diagnosis value.
        diagnosis: PostgresDiagnostic,
        #[source]
        /// The source value.
        source: Box<PostgresPoolError>,
    },
    #[error("PostgreSQL schema-maintenance lock operation failed for reset: {diagnosis}")]
    /// Acquiring or releasing the lock failed; the reset may already have committed.
    ResetLock {
        /// Redacted operational diagnosis.
        diagnosis: PostgresDiagnostic,
        #[source]
        /// The source value.
        source: Box<sqlx::Error>,
    },
    #[error("PostgreSQL schema-maintenance lock operation timed out for reset: {diagnosis}")]
    /// Acquiring or releasing the lock exceeded its deadline; the reset may have committed.
    ResetLockTimeout {
        /// Redacted operational diagnosis.
        diagnosis: PostgresDiagnostic,
        /// Configured budget for lock acquisition or release.
        timeout: std::time::Duration,
    },
    #[error("failed to reset PostgreSQL public schema: {diagnosis}")]
    /// Indicates reset schema.
    ResetSchema {
        /// The diagnosis value.
        diagnosis: PostgresDiagnostic,
        #[source]
        /// The source value.
        source: Box<sqlx::Error>,
    },
    #[error("timed out while resetting PostgreSQL public schema: {diagnosis}")]
    /// The transactional schema reset exceeded its configured deadline.
    ResetSchemaTimeout {
        /// Redacted operational diagnosis.
        diagnosis: PostgresDiagnostic,
        /// Configured schema reset deadline.
        timeout: Duration,
    },
    #[error("failed to run PostgreSQL migrations after reset: {diagnosis}")]
    /// Indicates migration.
    Migration {
        /// The diagnosis value.
        diagnosis: PostgresDiagnostic,
        #[source]
        /// The source value.
        source: Box<MigrateError>,
    },
    #[error("timed out while running PostgreSQL migrations after reset: {diagnosis}")]
    /// Post-reset migration exceeded its configured deadline.
    MigrationTimeout {
        /// Redacted operational diagnosis.
        diagnosis: PostgresDiagnostic,
        /// Configured post-reset migration deadline.
        timeout: Duration,
    },
}

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

impl ClassifyError for PostgresResetError {
    fn error_kind(&self) -> ErrorKind {
        match self {
            Self::MissingMigrator => ErrorKind::Validation,
            Self::ResetLockTimeout { .. }
            | Self::ResetSchemaTimeout { .. }
            | Self::MigrationTimeout { .. } => ErrorKind::Timeout,
            Self::EnsureDatabase { .. }
            | Self::Connect { .. }
            | Self::ResetLock { .. }
            | Self::ResetSchema { .. }
            | Self::Migration { .. } => ErrorKind::Dependency,
        }
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::MissingMigrator => "postgres_migrator_required",
            Self::EnsureDatabase { .. } => "postgres_ensure_database_failed",
            Self::Connect { .. } => "postgres_connect_failed",
            Self::ResetLock { .. } => "postgres_reset_lock_failed",
            Self::ResetLockTimeout { .. } => "postgres_reset_lock_timeout",
            Self::ResetSchema { .. } => "postgres_reset_schema_failed",
            Self::ResetSchemaTimeout { .. } => "postgres_reset_schema_timeout",
            Self::Migration { .. } => "postgres_migration_failed",
            Self::MigrationTimeout { .. } => "postgres_reset_migration_timeout",
        })
    }

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

impl PostgresResetError {
    #[must_use]
    /// Returns the diagnosis.
    pub const fn diagnosis(&self) -> Option<&PostgresDiagnostic> {
        match self {
            Self::EnsureDatabase { diagnosis, .. }
            | Self::Connect { diagnosis, .. }
            | Self::ResetLock { diagnosis, .. }
            | Self::ResetLockTimeout { diagnosis, .. }
            | Self::ResetSchema { diagnosis, .. }
            | Self::ResetSchemaTimeout { diagnosis, .. }
            | Self::Migration { diagnosis, .. }
            | Self::MigrationTimeout { diagnosis, .. } => Some(diagnosis),
            Self::MissingMigrator => None,
        }
    }
}

/// Resets a non-system PostgreSQL database according to the supplied policy.
pub async fn reset_database(
    config: PostgresResetConfig,
    migrator: Option<&Migrator>,
) -> Result<PostgresResetOutcome, PostgresResetError> {
    let migrator = if config.migrate_after_reset {
        Some(migrator.ok_or(PostgresResetError::MissingMigrator)?)
    } else {
        None
    };
    let database_url = config.connection.database_url.expose_secret();
    let database_name = config.database_name;

    if config.create_on_startup {
        tracing::info!(database = %database_name, "ensuring PostgreSQL database exists before reset");
        ensure_database_exists(database_url, config.ensure_database_timeout)
            .await
            .map_err(|source| PostgresResetError::EnsureDatabase {
                diagnosis: diagnose_sqlx_error(
                    PostgresOperation::EnsureDatabase,
                    database_url,
                    &source,
                ),
                source: Box::new(source),
            })?;
    }

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

    let map_lock_error = |error| match error {
        SessionAdvisoryLockError::Sqlx(source) => PostgresResetError::ResetLock {
            diagnosis: diagnose_sqlx_error(PostgresOperation::ResetSchema, database_url, &source),
            source: Box::new(source),
        },
        SessionAdvisoryLockError::Timeout { timeout } => PostgresResetError::ResetLockTimeout {
            diagnosis: reset_lock_timeout_diagnosis(database_url, timeout),
            timeout,
        },
    };
    let mut reset_guard = acquire_schema_maintenance_session_lock(
        &pool,
        Some(&database_name),
        None,
        config.reset_lock_timeout,
    )
    .await
    .map_err(map_lock_error)?;

    let reset_result = tokio::time::timeout(config.reset_schema_timeout, async {
        let mut transaction = reset_guard.connection().begin().await?;
        sqlx::query("DROP SCHEMA IF EXISTS public CASCADE")
            .execute(&mut *transaction)
            .await?;
        sqlx::query("CREATE SCHEMA public")
            .execute(&mut *transaction)
            .await?;
        sqlx::query("GRANT ALL ON SCHEMA public TO CURRENT_USER")
            .execute(&mut *transaction)
            .await?;
        transaction.commit().await
    })
    .await;
    match reset_result {
        Ok(Ok(())) => {}
        Ok(Err(source)) => {
            return Err(PostgresResetError::ResetSchema {
                diagnosis: diagnose_sqlx_error(
                    PostgresOperation::ResetSchema,
                    database_url,
                    &source,
                ),
                source: Box::new(source),
            });
        }
        Err(_) => {
            return Err(PostgresResetError::ResetSchemaTimeout {
                diagnosis: diagnose_operation_timeout(
                    PostgresOperation::ResetSchema,
                    database_url,
                    config.reset_schema_timeout,
                ),
                timeout: config.reset_schema_timeout,
            });
        }
    }

    if let Some(migrator) = migrator {
        match tokio::time::timeout(
            config.post_reset_migration_timeout,
            migrator.run(&mut **reset_guard.connection()),
        )
        .await
        {
            Ok(Ok(())) => {}
            Ok(Err(source)) => {
                return Err(PostgresResetError::Migration {
                    diagnosis: diagnose_migration_error(database_url, &source),
                    source: Box::new(source),
                });
            }
            Err(_) => {
                return Err(PostgresResetError::MigrationTimeout {
                    diagnosis: diagnose_operation_timeout(
                        PostgresOperation::Migrate,
                        database_url,
                        config.post_reset_migration_timeout,
                    ),
                    timeout: config.post_reset_migration_timeout,
                });
            }
        }
    }
    reset_guard
        .release_with_timeout(config.reset_lock_timeout)
        .await
        .map_err(map_lock_error)?;

    Ok(PostgresResetOutcome {
        database_name,
        migrated: config.migrate_after_reset,
    })
}

fn reset_lock_timeout_diagnosis(database_url: &str, timeout: Duration) -> PostgresDiagnostic {
    PostgresDiagnostic::new(
        PostgresOperation::ResetSchema,
        database_name(database_url),
        PostgresDiagnosticKind::MigrationLockUnavailable,
        format!(
            "PostgreSQL reset lock operation exceeded its {} ms deadline",
            timeout.as_millis()
        ),
        "inspect lock contention and database responsiveness; the reset may already have committed before lock release",
        true,
    )
}

const fn default_reset_lock_timeout() -> Duration {
    DEFAULT_POSTGRES_ADVISORY_LOCK_TIMEOUT
}

const fn default_reset_schema_timeout() -> Duration {
    DEFAULT_POSTGRES_RESET_SCHEMA_TIMEOUT
}

const fn default_post_reset_migration_timeout() -> Duration {
    DEFAULT_POSTGRES_RESET_MIGRATION_TIMEOUT
}