servlet 1.1.0

A small application runtime with an explicit operational contract
Documentation
//! Effect-free managed PostgreSQL policy with redacted endpoint diagnostics.

use super::{PgError, PgSession, endpoint::Endpoint};
use crate::health::CheckPolicy;
use std::time::Duration;

/// Explicit transport policy. Unverified TLS and silent plaintext fallback are absent.
#[derive(Clone)]
pub enum PgTls {
    /// Verify the server hostname and certificate against public roots.
    VerifyFull,
    /// Verify hostname and certificate with an additional PEM root (at most 64 KiB).
    VerifyFullWithRoot(Vec<u8>),
    /// Explicit local-lab plaintext, restricted to literal loopback IP addresses.
    PlaintextLoopback,
}
impl std::fmt::Debug for PgTls {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::VerifyFull => "VerifyFull",
            Self::VerifyFullWithRoot(_) => "VerifyFullWithRoot([redacted])",
            Self::PlaintextLoopback => "PlaintextLoopback",
        })
    }
}
/// Whether loss of this initialized pool withdraws application readiness.
#[derive(Clone, Copy, Debug)]
pub enum PgReadiness {
    /// Cached serial `SELECT 1` checks gate startup and ongoing readiness.
    Required(CheckPolicy),
    /// Connect at startup, but do not make pool availability a readiness condition.
    NotRequired,
}
/// Native pool bounds and a separate allowance for initializing it during setup.
#[derive(Clone, Copy, Debug)]
pub struct PgLimits {
    /// Maximum simultaneous connections, in 1..=1024. Size across all replicas.
    pub max_connections: u32,
    /// Minimum connections Servlet warms at startup and replenishes in the background.
    /// Must be no larger than the maximum. Idle or expired connections can be
    /// retired below this target and are restored on a later bounded attempt.
    pub min_connections: u32,
    /// Total initialization allowance, capped by the remaining startup deadline.
    pub startup_timeout: Duration,
    /// Native acquisition limit, including capacity wait, connection and TLS setup.
    pub acquire_timeout: Duration,
    /// Retire idle connections after this duration.
    pub idle_timeout: Duration,
    /// Retire connections after this age.
    pub max_lifetime: Duration,
}
impl Default for PgLimits {
    fn default() -> Self {
        Self {
            max_connections: 16,
            min_connections: 1,
            startup_timeout: Duration::from_secs(5),
            acquire_timeout: Duration::from_secs(2),
            idle_timeout: Duration::from_secs(300),
            max_lifetime: Duration::from_secs(1800),
        }
    }
}
/// Validated explicit connection settings. Construction performs no I/O or discovery.
#[derive(Clone)]
pub struct PgConfig {
    pub(super) endpoint: Endpoint,
    pub(super) application_name: String,
    pub(super) tls: PgTls,
    pub(super) limits: PgLimits,
    pub(super) readiness: PgReadiness,
    pub(super) session: PgSession,
}
impl std::fmt::Debug for PgConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PgConfig")
            .field("endpoint", &"[redacted]")
            .field("application_name", &"[redacted]")
            .field("tls", &self.tls)
            .field("limits", &self.limits)
            .field("readiness", &self.readiness)
            .field("session", &self.session)
            .finish()
    }
}
impl PgConfig {
    /// Parse a postgres/postgresql URL with an explicit host, user, and database.
    /// Query parameters and fragments are rejected. Password omission means empty;
    /// neither `PG*` variables nor `.pgpass` supply missing values.
    pub fn new(url: &str, application_name: impl Into<String>) -> Result<Self, PgError> {
        let application_name = application_name.into();
        if application_name.trim().is_empty()
            || application_name.len() > 63
            || application_name.chars().any(char::is_control)
        {
            return Err(PgError::Configuration);
        }
        Ok(Self {
            endpoint: Endpoint::parse(url)?,
            application_name,
            tls: PgTls::VerifyFull,
            limits: PgLimits::default(),
            readiness: PgReadiness::Required(CheckPolicy::default()),
            session: PgSession::default(),
        })
    }
    /// Select explicit TLS policy; plaintext only permits a literal loopback address.
    pub fn with_tls(mut self, tls: PgTls) -> Result<Self, PgError> {
        if matches!(&tls, PgTls::VerifyFullWithRoot(root) if root.is_empty() || root.len() > 65536)
            || matches!(tls, PgTls::PlaintextLoopback) && !self.endpoint.loopback()
        {
            return Err(PgError::Configuration);
        }
        self.tls = tls;
        Ok(self)
    }
    /// Set finite pool bounds; time allowances must be positive and at most 24 hours.
    pub fn with_limits(mut self, limits: PgLimits) -> Result<Self, PgError> {
        if limits.max_connections == 0
            || limits.max_connections > 1024
            || limits.min_connections > limits.max_connections
            || [
                limits.startup_timeout,
                limits.acquire_timeout,
                limits.idle_timeout,
                limits.max_lifetime,
            ]
            .iter()
            .any(|duration| !valid_duration(*duration))
        {
            return Err(PgError::Configuration);
        }
        self.limits = limits;
        Ok(self)
    }
    /// Apply explicit database-side statement, lock, and idle-transaction limits.
    pub fn with_session(mut self, session: PgSession) -> Result<Self, PgError> {
        session.validate()?;
        self.session = session;
        Ok(self)
    }
    /// Set readiness criticality. All registrations still connect during startup.
    pub fn with_readiness(mut self, readiness: PgReadiness) -> Result<Self, PgError> {
        if let PgReadiness::Required(policy) = readiness
            && (!valid_duration(policy.timeout) || !valid_duration(policy.interval))
        {
            return Err(PgError::Configuration);
        }
        self.readiness = readiness;
        Ok(self)
    }
}
fn valid_duration(duration: Duration) -> bool {
    !duration.is_zero() && duration <= Duration::from_secs(86400)
}

#[cfg(test)]
#[path = "config_test.rs"]
mod config_test;