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

use std::fmt;

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

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

use super::{
    config::{PostgresPoolConfig, PostgresPoolSettings},
    diagnostics::{
        MigrationFailureKind, PostgresDiagnostic, PostgresOperation, PostgresPoolError,
        diagnose_migration_error, diagnose_pool_error, diagnose_sqlx_error,
    },
    runtime::{connect_pool, database_name, ensure_database_exists, run_migrations},
};

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

#[cfg(feature = "postgres-admin")]
#[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 and convert it 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,
    /// Whether to run migrations after resetting the schema.
    pub migrate_after_reset: bool,
}

#[cfg(feature = "postgres-admin")]
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("migrate_after_reset", &self.migrate_after_reset)
            .finish()
    }
}

#[cfg(feature = "postgres-admin")]
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,
            migrate_after_reset: false,
        }
    }

    /// 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,
            migrate_after_reset: self.migrate_after_reset,
        }
    }

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

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

#[cfg(feature = "postgres-admin")]
impl<S> PostgresResetSettings<S>
where
    S: ExposeSecret<str>,
{
    /// Validates the complete reset request.
    pub fn validate(&self) -> Result<(), SettingsValidationError> {
        let mut issues = SettingsIssues::new();
        let database_url = self.database_url.expose_secret();
        issues.require_non_empty("postgres.reset.database_url", database_url);
        issues.extend_result(self.pool.validate_at("postgres.reset.pool"));
        match database_name(database_url) {
            Some(name) => issues.require(
                !SYSTEM_DATABASES.contains(&name.as_str()),
                "postgres.reset.database_url",
                "must not target a PostgreSQL system database",
            ),
            None if !database_url.trim().is_empty() => issues.push(
                "postgres.reset.database_url",
                "must contain a database name",
            ),
            None => {}
        }
        issues.into_result()
    }
}

#[cfg(feature = "postgres-admin")]
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))
    }

    /// Builds an immutable reset request after all safety checks pass.
    pub fn build(self) -> Result<PostgresResetConfig, SettingsValidationError> {
        self.validate()?;
        let Some(database_name) = database_name(self.database_url.expose_secret()) else {
            return Err(SettingsValidationError::single(
                "postgres.reset.database_url",
                "must contain a database name",
            ));
        };
        Ok(PostgresResetConfig {
            database_url: self.database_url,
            database_name,
            pool_config: PostgresPoolConfig {
                max_connections: self.pool.max_connections,
                min_connections: self.pool.min_connections,
                acquire_timeout: self.pool.acquire_timeout,
                idle_timeout: self.pool.idle_timeout,
                max_lifetime: self.pool.max_lifetime,
                test_before_acquire: self.pool.test_before_acquire,
            },
            create_on_startup: self.create_on_startup,
            migrate_after_reset: self.migrate_after_reset,
        })
    }
}

/// Validated immutable PostgreSQL reset request.
#[cfg(feature = "postgres-admin")]
#[derive(Clone)]
#[non_exhaustive]
pub struct PostgresResetConfig {
    database_url: SecretString,
    database_name: String,
    pool_config: PostgresPoolConfig,
    create_on_startup: bool,
    migrate_after_reset: bool,
}

#[cfg(feature = "postgres-admin")]
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("migrate_after_reset", &self.migrate_after_reset)
            .finish()
    }
}

#[cfg(feature = "postgres-admin")]
impl PostgresResetConfig {
    #[must_use]
    /// Returns the redacting database URL wrapper.
    pub const fn database_url(&self) -> &SecretString {
        &self.database_url
    }

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

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

#[cfg(feature = "postgres-admin")]
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
    }
}

#[cfg(feature = "postgres-admin")]
#[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("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("failed to run PostgreSQL migrations after reset: {diagnosis}")]
    /// Indicates migration.
    Migration {
        /// The diagnosis value.
        diagnosis: PostgresDiagnostic,
        /// The kind value.
        kind: MigrationFailureKind,
        #[source]
        /// The source value.
        source: Box<MigrateError>,
    },
}

#[cfg(feature = "postgres-admin")]
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()
    }
}

#[cfg(feature = "postgres-admin")]
impl ClassifyError for PostgresResetError {
    fn error_kind(&self) -> ErrorKind {
        match self {
            Self::MissingMigrator => ErrorKind::Validation,
            Self::EnsureDatabase { .. }
            | Self::Connect { .. }
            | 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::ResetSchema { .. } => "postgres_reset_schema_failed",
            Self::Migration { .. } => "postgres_migration_failed",
        })
    }
}

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

/// Resets a non-system PostgreSQL database according to the supplied policy.
#[cfg(feature = "postgres-admin")]
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.database_url.expose_secret();
    let database_name = config.database_name.clone();

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

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

    sqlx::query("DROP SCHEMA IF EXISTS public CASCADE")
        .execute(&pool)
        .await
        .map_err(|source| PostgresResetError::ResetSchema {
            diagnosis: diagnose_sqlx_error(PostgresOperation::ResetSchema, database_url, &source),
            source: Box::new(source),
        })?;
    sqlx::query("CREATE SCHEMA public")
        .execute(&pool)
        .await
        .map_err(|source| PostgresResetError::ResetSchema {
            diagnosis: diagnose_sqlx_error(PostgresOperation::ResetSchema, database_url, &source),
            source: Box::new(source),
        })?;
    sqlx::query("GRANT ALL ON SCHEMA public TO CURRENT_USER")
        .execute(&pool)
        .await
        .map_err(|source| PostgresResetError::ResetSchema {
            diagnosis: diagnose_sqlx_error(PostgresOperation::ResetSchema, database_url, &source),
            source: Box::new(source),
        })?;

    if let Some(migrator) = migrator {
        run_migrations(&pool, migrator)
            .await
            .map_err(|source| PostgresResetError::Migration {
                diagnosis: diagnose_migration_error(database_url, &source),
                kind: MigrationFailureKind::from_error(&source),
                source: Box::new(source),
            })?;
    }

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