use std::{
ops::{Deref, DerefMut},
sync::{
Arc,
Mutex,
MutexGuard,
atomic::{AtomicBool, AtomicUsize, Ordering},
},
time::Duration,
};
use bb8::{Pool, PooledConnection};
use tokio::{
sync::{OwnedSemaphorePermit, Semaphore},
time::Instant,
};
#[cfg(test)]
use super::test_support::DropProbe;
use super::{manager::WireframeConnectionManager, sync::lock_or_recover};
use crate::{client::ClientError, serializer::Serializer};
pub(crate) struct PoolSlot<S, P, C>
where
S: Serializer + Clone + Send + Sync + 'static,
P: bincode::Encode + Clone + Send + Sync + 'static,
C: Send + 'static,
{
pub(crate) pool: Pool<WireframeConnectionManager<S, P, C>>,
permits: Arc<Semaphore>,
protocol_gate: Arc<Semaphore>,
idle_timeout: Duration,
last_returned_at: Mutex<Option<Instant>>,
discard_on_next_checkout: AtomicBool,
#[cfg(test)]
pub(super) drop_probe: Option<DropProbe>,
}
impl<S, P, C> PoolSlot<S, P, C>
where
S: Serializer + Clone + Send + Sync + 'static,
P: bincode::Encode + Clone + Send + Sync + 'static,
C: Send + 'static,
{
pub(crate) fn new(
pool: Pool<WireframeConnectionManager<S, P, C>>,
max_in_flight_per_socket: usize,
idle_timeout: Duration,
) -> Self {
Self {
pool,
permits: Arc::new(Semaphore::new(max_in_flight_per_socket)),
protocol_gate: Arc::new(Semaphore::new(1)),
idle_timeout,
last_returned_at: Mutex::new(None),
discard_on_next_checkout: AtomicBool::new(false),
#[cfg(test)]
drop_probe: None,
}
}
pub(crate) fn try_acquire_permit(&self) -> Option<OwnedSemaphorePermit> {
Arc::clone(&self.permits).try_acquire_owned().ok()
}
pub(crate) async fn acquire_permit(&self) -> Result<OwnedSemaphorePermit, ClientError> {
Arc::clone(&self.permits)
.acquire_owned()
.await
.map_err(|_| ClientError::disconnected())
}
#[cfg(test)]
pub(super) fn close_admission(&self) { self.permits.close(); }
pub(crate) async fn acquire_protocol_permit(
&self,
) -> Result<OwnedSemaphorePermit, ClientError> {
Arc::clone(&self.protocol_gate)
.acquire_owned()
.await
.map_err(|_| ClientError::disconnected())
}
pub(crate) async fn checkout<'a>(
&'a self,
pending_responses: &'a AtomicUsize,
) -> Result<SlotConnection<'a, S, P, C>, ClientError> {
let mut connection = self.get_connection().await?;
let discard_requested = self.should_discard_lazily();
let is_idle_expired =
pending_responses.load(Ordering::Acquire) == 0 && self.should_recycle_idle();
if discard_requested || is_idle_expired {
connection.mark_broken();
drop(connection);
self.clear_last_returned_at();
connection = self.get_connection().await?;
}
Ok(SlotConnection {
connection,
armed: true,
last_returned_at: &self.last_returned_at,
pending_responses,
})
}
pub(crate) fn discard_next_checkout(&self) {
self.discard_on_next_checkout.store(true, Ordering::Release);
}
fn should_discard_lazily(&self) -> bool {
self.discard_on_next_checkout.swap(false, Ordering::AcqRel)
}
async fn get_connection(
&self,
) -> Result<PooledConnection<'_, WireframeConnectionManager<S, P, C>>, ClientError> {
self.pool.get().await.map_err(|err| match err {
bb8::RunError::User(error) => error,
bb8::RunError::TimedOut => ClientError::from(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"pooled connection checkout timed out",
)),
})
}
fn should_recycle_idle(&self) -> bool {
self.lock_last_returned_at()
.as_ref()
.is_some_and(|returned_at| returned_at.elapsed() >= self.idle_timeout)
}
fn clear_last_returned_at(&self) { *self.lock_last_returned_at() = None; }
fn lock_last_returned_at(&self) -> MutexGuard<'_, Option<Instant>> {
lock_or_recover(&self.last_returned_at)
}
}
pub(crate) struct SlotConnection<'a, S, P, C>
where
S: Serializer + Clone + Send + Sync + 'static,
P: bincode::Encode + Clone + Send + Sync + 'static,
C: Send + 'static,
{
connection: PooledConnection<'a, WireframeConnectionManager<S, P, C>>,
armed: bool,
last_returned_at: &'a Mutex<Option<Instant>>,
pending_responses: &'a AtomicUsize,
}
impl<S, P, C> SlotConnection<'_, S, P, C>
where
S: Serializer + Clone + Send + Sync + 'static,
P: bincode::Encode + Clone + Send + Sync + 'static,
C: Send + 'static,
{
pub(crate) const fn disarm(&mut self) { self.armed = false; }
pub(crate) fn mark_broken(&mut self) { self.connection.mark_broken(); }
}
impl<S, P, C> Deref for SlotConnection<'_, S, P, C>
where
S: Serializer + Clone + Send + Sync + 'static,
P: bincode::Encode + Clone + Send + Sync + 'static,
C: Send + 'static,
{
type Target = super::managed::ManagedClientConnection<S, C>;
fn deref(&self) -> &Self::Target { &self.connection }
}
impl<S, P, C> DerefMut for SlotConnection<'_, S, P, C>
where
S: Serializer + Clone + Send + Sync + 'static,
P: bincode::Encode + Clone + Send + Sync + 'static,
C: Send + 'static,
{
fn deref_mut(&mut self) -> &mut Self::Target { &mut self.connection }
}
impl<S, P, C> Drop for SlotConnection<'_, S, P, C>
where
S: Serializer + Clone + Send + Sync + 'static,
P: bincode::Encode + Clone + Send + Sync + 'static,
C: Send + 'static,
{
fn drop(&mut self) {
if self.armed {
self.connection.mark_broken();
self.pending_responses.store(0, Ordering::Release);
crate::metrics::inc_pool_incomplete_operation_discard();
tracing::debug!(
action = "discard_connection",
pool_operation = "client_operation",
reason = "operation_incomplete",
"discarding pooled client connection after an incomplete operation"
);
}
let mut last_returned_at = lock_or_recover(self.last_returned_at);
if self.connection.is_broken() {
*last_returned_at = None;
} else {
*last_returned_at = Some(Instant::now());
}
}
}
#[cfg(test)]
mod tests {
use std::{
sync::{Arc, Mutex},
thread,
time::Duration,
};
use googletest::{gtest, prelude::*};
use tokio::{runtime::Builder, time::Instant};
use tracing::Level;
use wireframe_testing::ObservabilityHandle;
use super::{
super::test_support::{CaptureWriter, test_pool_slot},
lock_or_recover,
};
#[tokio::test]
async fn try_acquire_permit_reflects_capacity() {
let slot = test_pool_slot(1, Duration::from_secs(30));
let held = slot.try_acquire_permit();
assert!(held.is_some(), "fresh slot must yield an immediate permit");
assert!(
slot.try_acquire_permit().is_none(),
"exhausted slot must refuse an immediate permit"
);
drop(held);
assert!(
slot.try_acquire_permit().is_some(),
"released capacity must be immediately reusable"
);
}
#[tokio::test]
async fn clear_last_returned_at_resets_recycle_decision() {
let slot = test_pool_slot(1, Duration::from_millis(1));
*slot.lock_last_returned_at() = Some(tokio::time::Instant::now() - Duration::from_mins(1));
assert!(
slot.should_recycle_idle(),
"stale timestamp must trigger a recycle"
);
slot.clear_last_returned_at();
assert!(
slot.lock_last_returned_at().is_none(),
"clear must remove the timestamp"
);
assert!(
!slot.should_recycle_idle(),
"cleared timestamp must not trigger a recycle"
);
}
#[gtest]
fn idle_recycle_bookkeeping_recovers_after_timestamp_poison() {
let runtime = Builder::new_current_thread()
.enable_time()
.build()
.expect("slot poison-recovery test runtime should build");
let _runtime_guard = runtime.enter();
let slot = Arc::new(test_pool_slot(1, Duration::from_millis(1)));
let stale_timestamp = Instant::now() - Duration::from_mins(1);
let poisoned_slot = Arc::clone(&slot);
let join_result = thread::spawn(move || {
let mut last_returned_at = poisoned_slot.lock_last_returned_at();
*last_returned_at = Some(stale_timestamp);
panic!("panic after slot timestamp update while holding the lock");
})
.join();
expect_that!(join_result, err(anything()));
expect_that!(slot.last_returned_at.is_poisoned(), eq(true));
let captured_logs = Arc::new(Mutex::new(Vec::new()));
let subscriber = tracing_subscriber::fmt()
.with_ansi(false)
.without_time()
.with_max_level(Level::WARN)
.with_writer(CaptureWriter::new(Arc::clone(&captured_logs)))
.finish();
let mut observability = ObservabilityHandle::new();
metrics::with_local_recorder(observability.recorder(), || {
tracing::subscriber::with_default(subscriber, || {
expect_that!(slot.should_recycle_idle(), eq(true));
slot.clear_last_returned_at();
expect_that!(slot.should_recycle_idle(), eq(false));
});
});
observability.snapshot();
let log_bytes = lock_or_recover(&captured_logs).clone();
let logs = String::from_utf8_lossy(&log_bytes);
expect_that!(
logs.as_ref(),
contains_substring("recovering poisoned client pool bookkeeping lock")
);
expect_that!(
observability
.counter_without_labels(crate::metrics::POOL_BOOKKEEPING_POISON_RECOVERIES),
eq(3)
);
}
}