footing 0.1.2

Feature-gated foundations for Rust backend services
Documentation
//! Explicitly gated destructive PostgreSQL administration operations.

use std::fmt;

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

use crate::{
    config::{ConfigIssues, ConfigValidationError},
    result::{ClassifyError, ErrorKind},
    secret::{ExposeSecret, SecretString},
};

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")]
#[derive(Clone, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
/// Unvalidated deserializable settings for an explicit PostgreSQL reset operation.
///
/// This type intentionally does not implement [`serde::Serialize`] because it
/// contains a database URL with credentials.
pub struct PostgresResetSettings {
    /// PostgreSQL connection URL. Debug output always redacts this value.
    pub database_url: SecretString,
    /// 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 fmt::Debug for PostgresResetSettings {
    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 PostgresResetSettings {
    /// Creates reset settings for a database URL.
    #[must_use]
    pub fn new(database_url: impl Into<String>) -> Self {
        Self {
            database_url: SecretString::new(database_url),
            pool: PostgresPoolSettings {
                max_connections: 1,
                ..PostgresPoolSettings::default()
            },
            create_on_startup: false,
            migrate_after_reset: false,
        }
    }

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

    /// Validates the complete reset request.
    pub fn validate(&self) -> Result<(), ConfigValidationError> {
        let mut issues = ConfigIssues::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()
    }

    /// Builds an immutable reset request after all safety checks pass.
    pub fn build(self) -> Result<PostgresResetConfig, ConfigValidationError> {
        self.validate()?;
        let Some(database_name) = database_name(self.database_url.expose_secret()) else {
            return Err(ConfigValidationError::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,
    })
}