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;
let returning = self.connection.return_to_pool();
drop(self);
let closing = pool.close_event();
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();
}
}
}