footing 0.6.6

Feature-gated foundations for Rust backend services
Documentation
#![cfg(feature = "postgres")]

use std::time::Duration;

use footing::{
    db::postgres::{
        PostgresBootstrapSettings, PostgresConnectionSettings, PostgresPoolSettings,
        PostgresStartupRetrySettings, connect_lazy_pool, connect_options, connect_pool,
        connect_pool_with_retry, run_migrations_with_timeouts,
    },
    secret::{ExposeSecret, SecretString},
};
use serde_json::json;
use sqlx::{
    PgPool, SqlSafeStr,
    migrate::{Migration, MigrationType, Migrator},
};

const TEST_URL: &str = "postgres://private-user:private-password@localhost/app";

#[test]
fn session_deadlines_distinguish_inheritance_zero_and_integer_millisecond_limits() {
    for timeout in [
        None,
        Some(Duration::ZERO),
        Some(Duration::from_millis(1)),
        Some(Duration::from_millis(i32::MAX as u64)),
    ] {
        let config = PostgresConnectionSettings::new(TEST_URL)
            .with_statement_timeout(timeout)
            .with_idle_in_transaction_session_timeout(timeout)
            .build()
            .unwrap();
        assert_eq!(config.statement_timeout(), timeout);
        assert_eq!(config.idle_in_transaction_session_timeout(), timeout);
        let restored = PostgresConnectionSettings::from(config.clone())
            .build()
            .unwrap();
        assert_eq!(restored.database_url().expose_secret(), TEST_URL);
        assert_eq!(restored.statement_timeout(), timeout);
        assert_eq!(restored.idle_in_transaction_session_timeout(), timeout);
    }
}

#[test]
fn invalid_deadlines_are_rejected_without_rounding_and_report_application_paths() {
    for timeout in [
        Duration::from_nanos(1),
        Duration::from_micros(999),
        Duration::from_micros(1_001),
        Duration::from_millis(i32::MAX as u64 + 1),
        Duration::MAX,
    ] {
        let settings = PostgresConnectionSettings::new(TEST_URL)
            .with_statement_timeout(Some(timeout))
            .with_idle_in_transaction_session_timeout(Some(timeout));
        for prefix in ["", "jobs.database"] {
            let error = settings.validate_at(prefix).unwrap_err();
            let paths: Vec<_> = error.issues().iter().map(|issue| issue.path()).collect();
            let prefix = if prefix.is_empty() {
                String::new()
            } else {
                format!("{prefix}.")
            };
            assert_eq!(
                paths,
                [
                    format!("{prefix}statement_timeout"),
                    format!("{prefix}idle_in_transaction_session_timeout"),
                ]
            );
        }
        assert_eq!(
            settings.clone().build().unwrap_err(),
            settings.validate().unwrap_err()
        );
    }
}

#[test]
fn settings_deserialize_optional_deadlines_and_roundtrip_explicit_secret_representations() {
    let defaults: PostgresConnectionSettings =
        serde_json::from_value(json!({ "database_url": TEST_URL })).unwrap();
    assert_eq!(defaults.database_url.expose_secret(), TEST_URL);
    assert_eq!(defaults.statement_timeout, None);
    assert_eq!(defaults.idle_in_transaction_session_timeout, None);

    let settings: PostgresConnectionSettings<String> = serde_json::from_value(json!({
        "database_url": TEST_URL,
        "statement_timeout": "250ms",
        "idle_in_transaction_session_timeout": "0s"
    }))
    .unwrap();
    let restored: PostgresConnectionSettings<String> =
        serde_json::from_value(serde_json::to_value(&settings).unwrap()).unwrap();
    let config = restored.build().unwrap();
    assert_eq!(config.statement_timeout(), Some(Duration::from_millis(250)));
    assert_eq!(
        config.idle_in_transaction_session_timeout(),
        Some(Duration::ZERO)
    );
    assert!(serde_json::from_value::<PostgresConnectionSettings>(json!({})).is_err());
    assert!(
        serde_json::from_value::<PostgresConnectionSettings>(json!({
            "database_url": TEST_URL,
            "statment_timeout": "1s"
        }))
        .is_err()
    );
}

#[test]
fn settings_configs_and_validation_errors_never_log_credentials() {
    let settings = PostgresConnectionSettings::from_secret(TEST_URL.to_owned());
    let config = settings.clone().build().unwrap();
    let invalid =
        PostgresConnectionSettings::new(format!("{TEST_URL}?sslmode=private-query-secret"))
            .build()
            .unwrap_err();
    let output = format!("{settings:?} {config:?} {invalid} {invalid:?}");
    assert!(output.contains("[REDACTED]"));
    for secret in [
        TEST_URL,
        "private-user",
        "private-password",
        "private-query-secret",
    ] {
        assert!(!output.contains(secret));
    }
}

#[test]
fn building_validates_the_converted_secret() {
    struct ConvertedUrl;
    impl ExposeSecret<str> for ConvertedUrl {
        fn expose_secret(&self) -> &str {
            TEST_URL
        }
    }
    impl From<ConvertedUrl> for SecretString {
        fn from(_: ConvertedUrl) -> Self {
            Self::new("not-a-postgres-url")
        }
    }
    let settings = PostgresConnectionSettings::from_secret(ConvertedUrl);
    settings.validate().unwrap();
    let error = settings.build().unwrap_err();
    assert_eq!(error.issues()[0].path(), "postgres.connection.database_url");
}

#[test]
fn bootstrap_embeds_connection_settings_and_url_changes_preserve_deadlines() {
    let connection = PostgresConnectionSettings::new(TEST_URL)
        .with_statement_timeout(Some(Duration::from_millis(123)));
    let settings = PostgresBootstrapSettings::new("postgres://localhost/old")
        .with_connection(connection)
        .with_database_url("postgres://localhost/new");
    assert_eq!(
        settings.connection.database_url.expose_secret(),
        "postgres://localhost/new"
    );
    assert_eq!(
        settings.connection.statement_timeout,
        Some(Duration::from_millis(123))
    );
    let loaded: PostgresBootstrapSettings = serde_json::from_value(json!({
        "connection": {
            "database_url": TEST_URL,
            "statement_timeout": "123ms"
        }
    }))
    .unwrap();
    assert_eq!(
        loaded.connection.statement_timeout,
        settings.connection.statement_timeout
    );
    loaded.build().unwrap();
    settings.build().unwrap();
}

#[test]
fn connect_options_keep_url_parameters_and_append_explicit_deadlines_last() {
    let mut url = url::Url::parse(TEST_URL).unwrap();
    url.query_pairs_mut()
        .append_pair("application_name", "connection-test")
        .append_pair("sslmode", "require")
        .append_pair("options[statement_timeout]", "7000")
        .append_pair("options[statement_timeout]", "8000")
        .append_pair("options[idle_in_transaction_session_timeout]", "9000")
        .append_pair("options[search_path]", "pg_catalog");
    let inherited = PostgresConnectionSettings::new(url.as_str())
        .build()
        .unwrap();
    let defaults = connect_options(&inherited).unwrap();
    assert_eq!(defaults.get_application_name(), Some("connection-test"));
    assert!(matches!(
        defaults.get_ssl_mode(),
        sqlx::postgres::PgSslMode::Require
    ));
    let original_options = defaults.get_options().unwrap();
    assert!(original_options.ends_with("-c search_path=pg_catalog"));
    assert!(original_options.contains("-c statement_timeout=7000 -c statement_timeout=8000"));

    let explicit = PostgresConnectionSettings::from(inherited)
        .with_statement_timeout(Some(Duration::from_millis(250)))
        .with_idle_in_transaction_session_timeout(Some(Duration::ZERO))
        .build()
        .unwrap();
    let options = connect_options(&explicit).unwrap();
    assert_eq!(
        options.get_application_name(),
        defaults.get_application_name()
    );
    assert!(matches!(
        options.get_ssl_mode(),
        sqlx::postgres::PgSslMode::Require
    ));
    let extended = options.get_options().unwrap();
    assert!(extended.starts_with(original_options));
    let overrides = &extended[original_options.len()..];
    assert!(overrides.contains("statement_timeout=250"));
    assert!(overrides.contains("idle_in_transaction_session_timeout=0"));
}

#[cfg(feature = "tier")]
#[test]
fn tier_supports_secret_metadata_loading_and_application_validation_paths() {
    use tier::{ConfigLoader, TierMetadata};

    type Input = PostgresConnectionSettings<tier::Secret<String>>;
    assert_eq!(Input::metadata().secret_paths(), ["database_url"]);
    let loaded = ConfigLoader::<Input>::from_value(json!({
        "database_url": TEST_URL,
        "statement_timeout": "125ms"
    }))
    .derive_metadata()
    .validator("postgres", |settings| {
        settings.validate_at("").map_err(Into::into)
    })
    .load()
    .unwrap();
    let config = loaded.into_inner().build().unwrap();
    assert_eq!(config.statement_timeout(), Some(Duration::from_millis(125)));
    assert!(!format!("{config:?}").contains("private-password"));
}

fn test_database_url() -> Option<String> {
    match std::env::var("FOOTING_TEST_POSTGRES_URL") {
        Ok(url) => Some(url),
        Err(error) => {
            assert!(
                std::env::var("FOOTING_REQUIRE_POSTGRES_TESTS").as_deref() != Ok("1"),
                "FOOTING_REQUIRE_POSTGRES_TESTS=1 requires FOOTING_TEST_POSTGRES_URL: {error}"
            );
            None
        }
    }
}

async fn session_deadlines(pool: &PgPool) -> (i32, i32, String) {
    sqlx::query_as(
        "SELECT (SELECT setting::int4 FROM pg_settings WHERE name = 'statement_timeout'), \
         (SELECT setting::int4 FROM pg_settings WHERE name = 'idle_in_transaction_session_timeout'), \
         current_setting('application_name')",
    )
    .fetch_one(pool)
    .await
    .unwrap()
}

#[tokio::test]
async fn pools_apply_independent_session_deadlines_and_longer_migrations_use_their_own_pool() {
    let Some(database_url) = test_database_url() else {
        return;
    };
    let mut url = url::Url::parse(&database_url).unwrap();
    url.query_pairs_mut()
        .append_pair("application_name", "footing-connection-test")
        .append_pair("options[statement_timeout]", "6000")
        .append_pair("options[statement_timeout]", "7000")
        .append_pair("options[idle_in_transaction_session_timeout]", "9000");
    let inherited = PostgresConnectionSettings::new(url.as_str())
        .build()
        .unwrap();
    let runtime = PostgresConnectionSettings::from(inherited.clone())
        .with_statement_timeout(Some(Duration::from_millis(200)))
        .with_idle_in_transaction_session_timeout(Some(Duration::from_millis(750)))
        .build()
        .unwrap();
    let migrations = PostgresConnectionSettings::from(inherited.clone())
        .with_statement_timeout(Some(Duration::from_secs(5)))
        .with_idle_in_transaction_session_timeout(Some(Duration::ZERO))
        .build()
        .unwrap();
    let pool_config = PostgresPoolSettings::default()
        .with_max_connections(1)
        .build()
        .unwrap();
    let inherited_pool = connect_lazy_pool(&inherited, pool_config).unwrap();
    let runtime_pool = connect_pool(&runtime, pool_config).await.unwrap();
    let migration_pool = connect_pool_with_retry(
        &migrations,
        pool_config,
        PostgresStartupRetrySettings::default().build().unwrap(),
    )
    .await
    .unwrap();
    for (pool, statement, idle) in [
        (&inherited_pool, 7000, 9000),
        (&runtime_pool, 200, 750),
        (&migration_pool, 5000, 0),
    ] {
        assert_eq!(
            session_deadlines(pool).await,
            (statement, idle, "footing-connection-test".into())
        );
    }
    let error = sqlx::query("SELECT pg_sleep(0.5)")
        .execute(&runtime_pool)
        .await
        .expect_err("runtime statement deadline must cancel a slow query");
    assert_eq!(
        error.as_database_error().unwrap().code().as_deref(),
        Some("57014")
    );

    // All migration bookkeeping stays in this one connection's temporary schema.
    // No application schema or existing migration table is created or modified.
    let mut migrator = Migrator::with_migrations(vec![Migration::new(
        1,
        "sleep".into(),
        MigrationType::Simple,
        "SELECT pg_sleep(0.5)".into_sql_str(),
        false,
    )]);
    migrator.dangerous_set_table_name("pg_temp.footing_connection_migrations");
    run_migrations_with_timeouts(
        &migration_pool,
        &migrator,
        None,
        Duration::from_secs(10),
        Duration::from_secs(10),
    )
    .await
    .unwrap();
    let applied: i64 = sqlx::query_scalar(
        "SELECT COUNT(*) FROM pg_temp.footing_connection_migrations WHERE success",
    )
    .fetch_one(&migration_pool)
    .await
    .unwrap();
    assert_eq!(applied, 1);
    assert_eq!(session_deadlines(&runtime_pool).await.0, 200);
    inherited_pool.close().await;
    runtime_pool.close().await;
    migration_pool.close().await;
}