servlet 1.2.0

A small application runtime with an explicit operational contract
Documentation
//! Register cleanup before any connection work, then initialize under startup's cutoff.

use super::{
    PgConfig, PgError, PgLimits, PgPool, PgReadiness, lease::Lease, postgres::PgPoolOptions,
};
use crate::setup::SetupContext;
use std::{
    future::poll_fn,
    pin::pin,
    sync::{Arc, Mutex},
    time::Duration,
};
use tokio::{
    task::JoinHandle,
    time::{Instant, sleep, timeout_at},
};

struct ManagedPool {
    pool: PgPool,
    maintenance: Option<JoinHandle<()>>,
}

impl SetupContext {
    /// Connect a named PostgreSQL pool under managed startup and shutdown ownership.
    ///
    /// Pool closure runs after accepted work and application cleanup, within the
    /// remaining shutdown budget. Checked-out connections may delay closure and
    /// cause a reported cleanup timeout. The returned pool is native SQLx.
    /// Servlet maintains the configured minimum itself. SQLx reports a minimum
    /// of zero in its native options to keep its detached replenishment disabled.
    /// Local size/idle/non-idle gauges use this bounded resource name as `pool`.
    /// They share the app registry's definition/series allowance (three each).
    ///
    /// Configured `PG*` variables consumed by SQLx are rejected (values are never
    /// reported). Password files are not read. Native query errors remain native;
    /// callers decide what details to expose. No application queries are retried.
    pub async fn postgres(
        &mut self,
        name: impl Into<String>,
        config: PgConfig,
    ) -> Result<PgPool, PgError> {
        let options = config.options()?;
        let name = name.into();
        let slot = Arc::new(Mutex::new(None::<ManagedPool>));
        let owner = slot.clone();
        self.cleanup(name.clone(), move || async move {
            let pool = owner
                .lock()
                .unwrap_or_else(|error| error.into_inner())
                .take();
            if let Some(owned) = pool {
                owned.pool.close().await;
                if let Some(task) = owned.maintenance {
                    task.await?;
                }
            }
            Ok(())
        })
        .map_err(|_| PgError::Registration)?;
        if let PgReadiness::Required(policy) = config.readiness {
            let probe = slot.clone();
            self.readiness(name.clone(), policy, move || {
                let pool = probe
                    .lock()
                    .unwrap_or_else(|error| error.into_inner())
                    .as_ref()
                    .map(|owned| owned.pool.clone());
                async move {
                    let pool = pool.ok_or(PgError::Initialization)?;
                    let connection = pool.acquire().await.map_err(|_| PgError::Initialization)?;
                    let mut lease = Lease::new(connection);
                    sqlx::query("SELECT 1")
                        .execute(lease.connection())
                        .await
                        .map_err(|_| PgError::Initialization)?;
                    lease.recycle(&pool);
                    Ok(())
                }
            })
            .map_err(|_| PgError::Registration)?;
        }
        let limits = config.limits;
        let pool = PgPoolOptions::new()
            .max_connections(limits.max_connections)
            // SQLx's detached minimum maintenance uses a separate five-minute deadline.
            .min_connections(0)
            .acquire_timeout(limits.acquire_timeout)
            .idle_timeout(limits.idle_timeout)
            .max_lifetime(limits.max_lifetime)
            .connect_lazy_with(options);
        *slot.lock().unwrap_or_else(|error| error.into_inner()) = Some(ManagedPool {
            pool: pool.clone(),
            maintenance: None,
        });
        super::metrics::register(&self.metrics(), name, pool.clone())?;
        let deadline = self.deadline().min(Instant::now() + limits.startup_timeout);
        let shutdown = self.shutdown();
        tokio::select! {
            biased;
            () = shutdown.cancelled() => Err(PgError::Cancelled),
            result = timeout_at(deadline, async {
                let mut connections = Vec::new();
                for _ in 0..limits.min_connections.max(1) {
                    connections.push(Lease::new(
                        pool.acquire().await.map_err(|_| PgError::Initialization)?,
                    ));
                }
                for connection in connections {
                    connection.recycle(&pool);
                }
                Ok::<(), PgError>(())
            }) => {
                result.map_err(|_| PgError::StartupTimeout)??;
                if limits.min_connections > 0 {
                    let mut owned = slot.lock().unwrap_or_else(|error| error.into_inner());
                    if let Some(owned) = owned.as_mut() {
                        owned.maintenance = Some(tokio::spawn(maintain_minimum(pool.clone(), limits)));
                    }
                }
                Ok(pool)
            }
        }
    }
}

async fn maintain_minimum(pool: PgPool, limits: PgLimits) {
    let closing = pool.close_event();
    if pool.is_closed() {
        return;
    }

    // A short delay also discovers capacity lost by native queries and idle reaping.
    let interval = limits
        .acquire_timeout
        .clamp(Duration::from_millis(10), Duration::from_millis(250));
    tokio::select! {
        biased;
        () = closing => {}
        () = async {
            loop {
                sleep(interval).await;
                if pool.size() >= limits.min_connections {
                    continue;
                }

                let deadline = Instant::now() + limits.acquire_timeout;
                let _ = timeout_at(deadline, async {
                    loop {
                        let size = pool.size();
                        if size >= limits.min_connections {
                            break;
                        }
                        acquire_replacement(&pool, limits.min_connections).await?;
                        if pool.size() <= size {
                            break;
                        }
                    }
                    Ok::<(), sqlx::Error>(())
                }).await;
            }
        } => {}
    }
}

async fn acquire_replacement(pool: &PgPool, minimum: u32) -> Result<(), sqlx::Error> {
    // SQLx prefers idle connections, so take them out of the queue for the
    // first poll. If a handshake starts, it owns its permit from then on.
    // Return the other connections before waiting on network I/O.
    let mut idle: Vec<_> = std::iter::from_fn(|| pool.try_acquire())
        .take(minimum as usize)
        .collect();
    let mut acquiring = pin!(pool.acquire());
    let connection = poll_fn(|cx| {
        let result = acquiring.as_mut().poll(cx);
        for connection in idle.drain(..) {
            Lease::new(connection).recycle(pool);
        }
        result
    })
    .await?;
    Lease::new(connection).recycle(pool);
    Ok(())
}