footing 0.5.4

Feature-gated foundations for Rust backend services
Documentation
//! PostgreSQL connection identity and per-session startup settings.

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

use serde::{Deserialize, Serialize};

use crate::{
    secret::{ExposeSecret, SecretString},
    settings::{SettingsIssues, SettingsValidationError, field_path},
};

/// Validated PostgreSQL connection settings, separate from pool sizing and recycling.
///
/// Debug output redacts the URL. Conversion to SQLx options through
/// [`super::connect_options`] exposes credentials to the driver; the resulting
/// SQLx value must not be logged.
#[derive(Clone)]
#[non_exhaustive]
pub struct PostgresConnectionConfig {
    pub(super) database_url: SecretString,
    pub(super) statement_timeout: Option<Duration>,
    pub(super) idle_in_transaction_session_timeout: Option<Duration>,
}

impl fmt::Debug for PostgresConnectionConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PostgresConnectionConfig")
            .field("database_url", &self.database_url)
            .field("statement_timeout", &self.statement_timeout)
            .field(
                "idle_in_transaction_session_timeout",
                &self.idle_in_transaction_session_timeout,
            )
            .finish()
    }
}

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

    /// Returns the explicit per-statement deadline, or `None` to inherit it.
    #[must_use]
    pub const fn statement_timeout(&self) -> Option<Duration> {
        self.statement_timeout
    }

    /// Returns the explicit idle-in-transaction deadline, or `None` to inherit it.
    #[must_use]
    pub const fn idle_in_transaction_session_timeout(&self) -> Option<Duration> {
        self.idle_in_transaction_session_timeout
    }
}

#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
/// Connection URL and optional server-side PostgreSQL session deadlines.
///
/// `None` preserves URL options and database/role defaults. `Some(Duration::ZERO)`
/// explicitly disables that server deadline. Explicit values override matching
/// URL options and must be whole milliseconds in `0..=i32::MAX`; fractional or
/// out-of-range durations are rejected rather than rounded or truncated.
/// These deadlines are independent of pool acquisition, idle connection recycling,
/// and the client's total migration deadline.
///
/// Use separate connection configurations for runtime queries and migrations.
/// Settings do not create connections, run migrations, or install tasks.
/// SQLx parsing may consult its environment and password file defaults.
/// The default secret representation cannot be serialized; configuration loaders
/// can opt into another representation through `S`, as with
/// [`super::PostgresBootstrapSettings`]. Debug always redacts the URL.
///
/// ```compile_fail
/// use footing::db::postgres::PostgresConnectionSettings;
/// let settings = PostgresConnectionSettings::new("postgres://localhost/app");
/// let _ = serde_json::to_string(&settings);
/// ```
pub struct PostgresConnectionSettings<S = SecretString> {
    /// PostgreSQL URL. SQLx environment defaults apply to omitted connection fields.
    #[cfg_attr(feature = "tier", tier(secret, leaf))]
    pub database_url: S,
    #[serde(default, with = "crate::settings::human_duration::option")]
    /// Maximum execution time of each statement on the server, including lock waits.
    /// `None` inherits the configured default; zero disables the limit.
    pub statement_timeout: Option<Duration>,
    #[serde(default, with = "crate::settings::human_duration::option")]
    /// Maximum idle time inside an open transaction before the server closes the session.
    /// This is not the idle lifetime of an unused pool connection.
    /// `None` inherits the configured default; zero disables the limit.
    pub idle_in_transaction_session_timeout: Option<Duration>,
}

impl<S> fmt::Debug for PostgresConnectionSettings<S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PostgresConnectionSettings")
            .field("database_url", &"[REDACTED]")
            .field("statement_timeout", &self.statement_timeout)
            .field(
                "idle_in_transaction_session_timeout",
                &self.idle_in_transaction_session_timeout,
            )
            .finish()
    }
}

impl PostgresConnectionSettings {
    /// Wraps the URL in a redacted secret without overriding server deadlines.
    #[must_use]
    pub fn new(database_url: impl Into<String>) -> Self {
        Self::from_secret(SecretString::new(database_url))
    }

    /// Replaces the URL, preserving explicitly configured session deadlines.
    #[must_use]
    pub fn with_database_url(mut self, database_url: impl Into<String>) -> Self {
        self.database_url = SecretString::new(database_url);
        self
    }
}

impl<S> PostgresConnectionSettings<S> {
    /// Uses an explicit secret representation without overriding server deadlines.
    #[must_use]
    pub const fn from_secret(database_url: S) -> Self {
        Self {
            database_url,
            statement_timeout: None,
            idle_in_transaction_session_timeout: None,
        }
    }

    /// Converts the URL representation without exposing it.
    #[must_use]
    pub fn map_database_url<T>(self, map: impl FnOnce(S) -> T) -> PostgresConnectionSettings<T> {
        PostgresConnectionSettings {
            database_url: map(self.database_url),
            statement_timeout: self.statement_timeout,
            idle_in_transaction_session_timeout: self.idle_in_transaction_session_timeout,
        }
    }

    /// Sets the server-side per-statement deadline; zero explicitly disables it.
    #[must_use]
    pub const fn with_statement_timeout(mut self, timeout: Option<Duration>) -> Self {
        self.statement_timeout = timeout;
        self
    }

    /// Sets the idle-in-transaction deadline; zero explicitly disables it.
    #[must_use]
    pub const fn with_idle_in_transaction_session_timeout(
        mut self,
        timeout: Option<Duration>,
    ) -> Self {
        self.idle_in_transaction_session_timeout = timeout;
        self
    }

    /// Converts the secret representation and validates before producing runtime configuration.
    pub fn build(self) -> Result<PostgresConnectionConfig, SettingsValidationError>
    where
        S: Into<SecretString>,
    {
        let settings = self.map_database_url(Into::into);
        settings.validate()?;
        Ok(settings.into_config())
    }
}

impl<S: ExposeSecret<str>> PostgresConnectionSettings<S> {
    /// Validates under the default `postgres.connection` path.
    pub fn validate(&self) -> Result<(), SettingsValidationError> {
        self.validate_at("postgres.connection")
    }

    /// Validates under an application field path. An empty path produces bare field names.
    pub fn validate_at(&self, path: &str) -> Result<(), SettingsValidationError> {
        let mut issues = SettingsIssues::new();
        let url = self.database_url.expose_secret();
        issues.require_non_empty(field_path(path, "database_url"), url);
        if !url.trim().is_empty() {
            issues.require(
                super::identity::connect_options(url).is_ok(),
                field_path(path, "database_url"),
                "must be a valid PostgreSQL URL",
            );
        }
        for (field, timeout) in [
            ("statement_timeout", self.statement_timeout),
            (
                "idle_in_transaction_session_timeout",
                self.idle_in_transaction_session_timeout,
            ),
        ] {
            issues.require(
                timeout.is_none_or(|value| {
                    value.subsec_nanos().is_multiple_of(1_000_000)
                        && value.as_millis() <= i32::MAX as u128
                }),
                field_path(path, field),
                "must be omitted or a whole number of milliseconds between 0 and 2147483647",
            );
        }
        issues.into_result()
    }
}

impl PostgresConnectionSettings {
    pub(super) fn into_config(self) -> PostgresConnectionConfig {
        PostgresConnectionConfig {
            database_url: self.database_url,
            statement_timeout: self.statement_timeout,
            idle_in_transaction_session_timeout: self.idle_in_transaction_session_timeout,
        }
    }
}

impl From<PostgresConnectionConfig> for PostgresConnectionSettings {
    fn from(config: PostgresConnectionConfig) -> Self {
        Self {
            database_url: config.database_url,
            statement_timeout: config.statement_timeout,
            idle_in_transaction_session_timeout: config.idle_in_transaction_session_timeout,
        }
    }
}