servlet 1.1.0

A small application runtime with an explicit operational contract
Documentation
//! Bound recycling of completed checkouts and close interrupted ones.
use super::{PgConnection, PgPool, Postgres, pool::PoolConnection};
use tokio::time::{Instant, timeout_at};

pub(super) struct Lease {
    connection: PoolConnection<Postgres>,
    reusable: bool,
}

impl Lease {
    pub(super) fn new(connection: PoolConnection<Postgres>) -> Self {
        Self {
            connection,
            reusable: false,
        }
    }

    pub(super) fn connection(&mut self) -> &mut PgConnection {
        &mut self.connection
    }

    pub(super) fn recycle(mut self, pool: &PgPool) {
        self.reusable = true;
        // In SQLx 0.9.1 this takes the socket and its permit out of the checkout.
        // Dropping the return future closes that socket and restores the permit.
        let returning = self.connection.return_to_pool();
        // The pool has a native minimum of zero, so this empty checkout does
        // not start detached SQLx maintenance.
        drop(self);
        let closing = pool.close_event();
        // Check after registering the listener in case closure raced registration.
        if pool.is_closed() {
            return;
        }

        let deadline = Instant::now() + pool.options().get_acquire_timeout();
        tokio::spawn(async move {
            tokio::select! {
                biased;
                () = closing => {}
                _ = timeout_at(deadline, returning) => {}
            }
        });
    }
}

impl Drop for Lease {
    fn drop(&mut self) {
        if !self.reusable {
            self.connection.close_on_drop();
        }
    }
}