servlet 1.1.0

A small application runtime with an explicit operational contract
Documentation
//! One absolute cutoff covers acquisition and application execution; cancelled leases close.
use super::{
    OperationFuture, PgConnection, PgOperation, PgOperationError, lease::Lease,
    operation_metrics::Observation,
};
use std::time::Duration;
use tokio::time::{Instant, timeout_at};
use tracing::Instrument;

impl PgOperation {
    /// Acquire and execute once under an absolute deadline, at most 24 hours away.
    ///
    /// Pass `RequestDeadline::instant()` to preserve time already spent in a request.
    /// Pool acquisition also retains the pool's own shorter allowance. An expired
    /// deadline never invokes the callback. The callback may run multiple native
    /// queries and explicitly begin/commit/rollback a transaction; it is never retried.
    ///
    /// Timeout, cancellation, and panic close the checked-out connection rather than
    /// recycling it. Native SQLx owns that asynchronous close and retains the pool
    /// permit until it completes. A completed callback returns its result while
    /// the connection recycles in the background, within the pool acquisition
    /// allowance. Pool closure or expiry discards a connection still recycling.
    /// Server work may continue until disconnect or the configured session timeout.
    /// A client timeout does not prove a write failed
    /// to commit. Awaited native errors are available through `PgOperationError`.
    /// Synchronous blocking work cannot be preempted by this cooperative deadline.
    pub async fn run<T, F>(&self, deadline: Instant, operation: F) -> Result<T, PgOperationError>
    where
        T: Send,
        F: for<'connection> FnOnce(
                &'connection mut PgConnection,
            ) -> OperationFuture<'connection, T>
            + Send,
    {
        let span = tracing::info_span!("postgresql.operation", pool = %self.pool_name,
            operation = %self.name, "db.system.name" = "postgresql", "otel.kind" = "client",
            outcome = tracing::field::Empty, "otel.status_code" = tracing::field::Empty);
        let observation = span.clone();
        async move {
            let mut observed = Observation::new(self.metrics.clone(), observation);
            if deadline.saturating_duration_since(Instant::now()) > Duration::from_secs(86400) {
                observed.invalid_deadline();
                return Err(PgOperationError::InvalidDeadline);
            }
            if Instant::now() >= deadline {
                observed.acquired(2);
                observed.finish(3);
                return Err(PgOperationError::Deadline);
            }
            let acquired = timeout_at(deadline, async {
                self.pool.acquire().await.map(Lease::new)
            })
            .await;
            if Instant::now() >= deadline || acquired.is_err() {
                observed.acquired(2);
                observed.finish(3);
                return Err(PgOperationError::Deadline);
            }
            let mut lease = match acquired.expect("timeout handled above") {
                Ok(lease) => {
                    observed.acquired(0);
                    lease
                }
                Err(error) => {
                    observed.acquired(1);
                    observed.finish(2);
                    return Err(PgOperationError::Acquire(error));
                }
            };
            let result = timeout_at(deadline, operation(lease.connection())).await;
            if Instant::now() >= deadline || result.is_err() {
                observed.finish(3);
                return Err(PgOperationError::Deadline);
            }
            lease.recycle(&self.pool);
            match result.expect("timeout handled above") {
                Ok(value) => {
                    observed.finish(0);
                    Ok(value)
                }
                Err(error) => {
                    observed.finish(1);
                    Err(PgOperationError::Query(error))
                }
            }
        }
        .instrument(span)
        .await
    }
}