footing 0.1.3

Feature-gated foundations for Rust backend services
Documentation
use crate::{result::DiagnosticKind, secret::ExposeSecret};

#[cfg(feature = "postgres-admin")]
use super::admin::PostgresResetSettings;
use super::{
    MigrationFailureKind, POSTGRES_HEALTH_ERROR, PostgresBootstrapError, PostgresBootstrapSettings,
    PostgresDiagnosticKind, PostgresHealth, PostgresHealthStatus, PostgresOperation,
    PostgresPoolError, PostgresPoolSettings, PostgresStartupRetrySettings, advisory_lock_key,
    database_name, diagnose_migration_error, diagnose_sqlx_error, redact_database_url,
};

#[test]
fn rejects_zero_max_connections() {
    let error = PostgresPoolSettings::default()
        .with_max_connections(0)
        .build()
        .expect_err("zero max connections must be rejected");

    assert_eq!(error.issues()[0].path(), "postgres.pool.max_connections");
}

#[test]
fn rejects_min_connections_above_max() {
    let error = PostgresPoolSettings::default()
        .with_max_connections(2)
        .with_min_connections(3)
        .build()
        .expect_err("min connections above max must be rejected");

    assert_eq!(error.issues()[0].path(), "postgres.pool.min_connections");
}

#[test]
fn rejects_zero_acquire_timeout() {
    let error = PostgresPoolSettings::default()
        .with_acquire_timeout(std::time::Duration::ZERO)
        .build()
        .expect_err("zero acquire timeout must be rejected");

    assert_eq!(error.issues()[0].path(), "postgres.pool.acquire_timeout");
}

#[test]
fn exposes_pool_config_values() {
    let config = PostgresPoolSettings::default()
        .with_max_connections(20)
        .with_min_connections(2)
        .with_test_before_acquire(false)
        .build()
        .expect("pool settings should be valid");

    assert_eq!(config.max_connections(), 20);
    assert_eq!(config.min_connections(), 2);
    assert!(!config.test_before_acquire());
}

#[test]
fn validates_bootstrap_config_before_touching_database() {
    let result = PostgresBootstrapSettings::new(" ")
        .build()
        .expect_err("empty URL should be rejected");

    assert_eq!(result.issues()[0].path(), "postgres.database_url");

    let result = PostgresBootstrapSettings::new("not-a-postgres-url")
        .build()
        .expect_err("invalid URL should be rejected");
    assert_eq!(result.issues()[0].path(), "postgres.database_url");
}

#[tokio::test]
async fn bootstrap_requires_migrator_when_migration_is_enabled() {
    let result = super::bootstrap_database(
        PostgresBootstrapSettings::new("postgres://postgres:postgres@localhost/app")
            .with_migrate_on_startup(true)
            .build()
            .expect("bootstrap settings should be valid"),
        None,
    )
    .await
    .expect_err("missing migrator should be rejected before connecting");

    assert!(matches!(result, PostgresBootstrapError::MissingMigrator));
}

#[test]
fn parses_database_name_without_exposing_credentials() {
    assert_eq!(
        database_name("postgres://app:secret@localhost:5432/app_dev").as_deref(),
        Some("app_dev")
    );
    assert_eq!(database_name("not-a-url"), None);
}

#[test]
#[cfg(feature = "postgres-admin")]
fn postgres_configuration_debug_redacts_database_urls() {
    let database_url =
        "postgres://private-user:private-password@localhost/app?sslpassword=private-query";
    let bootstrap = PostgresBootstrapSettings::new(database_url)
        .build()
        .expect("bootstrap settings should be valid");
    let settings = PostgresBootstrapSettings::new(database_url);
    let reset = PostgresResetSettings::new(database_url)
        .build()
        .expect("reset settings should be valid");

    let output = format!("{bootstrap:?} {settings:?} {reset:?}");
    assert!(output.contains("[REDACTED]"));
    for sensitive in [
        database_url,
        "private-user",
        "private-password",
        "private-query",
    ] {
        assert!(!output.contains(sensitive));
    }
}

#[test]
fn postgres_error_formatting_redacts_urls_and_source_details() {
    let database_url =
        "postgres://private-user:private-password@localhost/app?sslpassword=private-query";
    let source_detail = "private-driver-error-detail";
    let sqlx_error = sqlx::Error::Configuration(Box::new(std::io::Error::other(source_detail)));
    let diagnosis = diagnose_sqlx_error(PostgresOperation::Connect, database_url, &sqlx_error);
    let diagnosis_output = format!("{diagnosis} {diagnosis:?}");
    let pool_error = PostgresPoolError::Sqlx(sqlx_error);
    let pool_output = format!("{pool_error} {pool_error:?}");
    let bootstrap_error = PostgresBootstrapError::Connect {
        diagnosis,
        source: Box::new(pool_error),
    };
    let output = format!("{diagnosis_output} {pool_output} {bootstrap_error} {bootstrap_error:?}");

    assert!(output.contains("[REDACTED]"));
    for sensitive in [
        database_url,
        "private-user",
        "private-password",
        "private-query",
        source_detail,
    ] {
        assert!(!output.contains(sensitive));
    }
}

#[test]
fn postgres_settings_deserialize_credentials_and_redact_debug_output() {
    let database_url = "postgres://private-user:private-password@localhost/app";
    let settings: PostgresBootstrapSettings = serde_json::from_value(serde_json::json!({
        "database_url": database_url
    }))
    .expect("settings should deserialize");

    assert_eq!(settings.database_url.expose_secret(), database_url);
    let debug = format!("{settings:?}");
    assert!(debug.contains("[REDACTED]"));
    assert!(!debug.contains("private-user"));
    assert!(!debug.contains("private-password"));
}

#[test]
fn postgres_health_exposes_only_a_stable_redacted_error() {
    let health = PostgresHealth {
        status: PostgresHealthStatus::Unavailable,
        latency: std::time::Duration::from_millis(10),
    };

    assert_eq!(health.error(), Some("database health check failed"));
    let output = format!("{health:?}");
    assert!(output.contains("has_error"));
    assert!(!output.contains(POSTGRES_HEALTH_ERROR));
}

#[test]
fn postgres_settings_convert_to_runtime_config() {
    let settings = PostgresBootstrapSettings {
        database_url: "postgres://app:secret@localhost/app".into(),
        pool: PostgresPoolSettings {
            max_connections: 20,
            ..PostgresPoolSettings::default()
        },
        create_on_startup: true,
        migrate_on_startup: false,
        startup_retry: PostgresStartupRetrySettings::default()
            .with_max_attempts(3)
            .with_initial_delay(std::time::Duration::from_millis(10))
            .with_max_delay(std::time::Duration::from_millis(50)),
        migration_lock_key: Some(42),
    };
    let config = settings.clone().build().expect("settings should convert");

    assert_eq!(
        config.database_url().expose_secret(),
        "postgres://app:secret@localhost/app"
    );
    assert_eq!(config.pool_config().max_connections(), 20);
    assert!(config.create_on_startup());
    assert!(!config.migrate_on_startup());
    assert_eq!(config.startup_retry().max_attempts(), 3);
    assert_eq!(config.migration_lock_key(), Some(42));
}

#[test]
fn postgres_settings_adapt_and_validate_with_stable_paths() {
    let settings = PostgresBootstrapSettings {
        database_url: "postgres://app:secret@localhost/app".into(),
        pool: PostgresPoolSettings {
            max_connections: 0,
            ..PostgresPoolSettings::default()
        },
        ..PostgresBootstrapSettings::new("postgres://app:secret@localhost/app")
    };

    let validation = settings
        .validate_at("database")
        .expect_err("invalid settings should report config paths");
    assert_eq!(
        validation.issues()[0].path(),
        "database.pool.max_connections"
    );

    let error = settings
        .clone()
        .build()
        .expect_err("invalid settings should not build");
    assert_eq!(error.issues()[0].path(), "postgres.pool.max_connections");
    assert!(settings.validate().is_err());
}

#[test]
fn diagnoses_migration_state_failures_for_operators() {
    let missing = sqlx::migrate::MigrateError::VersionMissing(20260428000200);
    let diagnosis = diagnose_migration_error("postgres://app:secret@localhost/app", &missing);

    assert_eq!(diagnosis.kind(), PostgresDiagnosticKind::MigrationMissing);
    assert_eq!(diagnosis.database(), Some("app"));
    assert!(diagnosis.message().contains("20260428000200"));
    assert!(!diagnosis.retryable());
    assert_eq!(
        diagnosis.to_diagnostic().kind(),
        DiagnosticKind::ResourceMissing
    );

    let mismatch = sqlx::migrate::MigrateError::VersionMismatch(20260428000200);
    assert_eq!(
        MigrationFailureKind::from_error(&mismatch),
        MigrationFailureKind::VersionMismatch {
            version: 20260428000200
        }
    );
    assert_eq!(
        diagnose_migration_error("postgres://app:secret@localhost/app", &mismatch).kind(),
        PostgresDiagnosticKind::MigrationChecksumMismatch
    );

    let permission = sqlx::migrate::MigrateError::Execute(sqlx::Error::Io(std::io::Error::new(
        std::io::ErrorKind::PermissionDenied,
        "socket denied",
    )));
    assert_eq!(
        diagnose_migration_error("postgres://app:secret@localhost/app", &permission).kind(),
        PostgresDiagnosticKind::PermissionDenied
    );
}

#[test]
#[cfg(feature = "postgres-admin")]
fn reset_config_rejects_system_databases() {
    let system = PostgresResetSettings::new("postgres://app:secret@localhost/postgres")
        .build()
        .expect_err("system database should be rejected");
    assert_eq!(system.issues()[0].path(), "postgres.reset.database_url");
}

#[test]
fn redacts_database_urls_without_losing_routing_information() {
    assert_eq!(
        redact_database_url("postgres://app:secret@localhost:5432/app"),
        "postgres://app:****@localhost:5432/app"
    );
    assert_eq!(
        redact_database_url(
            "postgres://app:secret@localhost/app?sslmode=require&sslpassword=private-query"
        ),
        "postgres://app:****@localhost/app?sslmode=****&sslpassword=****"
    );
    assert_eq!(
        redact_database_url("postgres://localhost/app?password=private-query#private-fragment"),
        "postgres://localhost/app?password=****#****"
    );
    assert_eq!(redact_database_url("not-a-url"), "<invalid-postgres-url>");
}

#[test]
fn advisory_lock_keys_are_stable_and_namespaced() {
    let left = advisory_lock_key("app", "migrations");
    let same = advisory_lock_key(" app ", " migrations ");
    let other = advisory_lock_key("app", "workers");

    assert_eq!(left, same);
    assert_ne!(left, other);
}