use std::{
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
time::Duration,
};
use rstest::{fixture, rstest};
use tokio::time::{advance, timeout};
use super::helpers::test_with_client;
use crate::{
client::{ClientError, ClientPoolConfig, pool::managed::ManagedClientConnection},
serializer::BincodeSerializer,
test_helpers::{
Ping,
Pong,
PoolServerBehavior,
PoolTestServer,
TestClientPool,
build_pooled_client,
},
};
type TestResult = Result<(), Box<dyn std::error::Error + Send + Sync>>;
type ManagedFixture = (
ManagedClientConnection<BincodeSerializer, ()>,
Arc<AtomicUsize>,
);
const GRACE: Duration = Duration::from_secs(1);
#[track_caller]
fn assert_teardown_once(teardown_count: &AtomicUsize) {
assert_eq!(
teardown_count.load(Ordering::SeqCst),
1,
"pooled connection teardown callback must run exactly once"
);
}
#[fixture]
async fn managed_connection_with_teardown() -> super::helpers::TestResult<ManagedFixture> {
let teardown_count = Arc::new(AtomicUsize::new(0));
let teardown_callback_count = Arc::clone(&teardown_count);
let client = test_with_client(|builder| {
builder
.on_connection_setup(|| async {})
.on_connection_teardown(move |()| {
let callback_count = Arc::clone(&teardown_callback_count);
async move {
callback_count.fetch_add(1, Ordering::SeqCst);
}
})
})
.await?;
Ok((ManagedClientConnection::new(client), teardown_count))
}
#[derive(Debug, Clone, Copy)]
enum DropSite {
ActiveRuntime,
DetachedThread,
}
enum DropCompletion {
Inline,
Detached {
worker: std::thread::JoinHandle<()>,
finished: tokio::sync::oneshot::Receiver<()>,
},
}
impl DropCompletion {
async fn wait(self, grace: Duration) -> TestResult {
let Self::Detached { worker, finished } = self else {
return Ok(());
};
if timeout(grace, finished).await.is_err() {
return Err(std::io::Error::other(
"pooled connection drop did not finish within the grace period",
)
.into());
}
join_worker(worker)
}
}
fn join_worker(worker: std::thread::JoinHandle<()>) -> TestResult {
worker
.join()
.map_err(|_| -> Box<dyn std::error::Error + Send + Sync> {
std::io::Error::other("pooled connection drop thread panicked").into()
})
}
impl DropSite {
fn drop_managed(
self,
managed: ManagedClientConnection<BincodeSerializer, ()>,
) -> DropCompletion {
match self {
Self::ActiveRuntime => {
drop(managed);
DropCompletion::Inline
}
Self::DetachedThread => {
let (sender, finished) = tokio::sync::oneshot::channel();
let worker = std::thread::spawn(move || {
drop(managed);
let _send_result = sender.send(());
});
DropCompletion::Detached { worker, finished }
}
}
}
}
#[rstest]
#[case::active_runtime(DropSite::ActiveRuntime)]
#[case::detached_thread(DropSite::DetachedThread)]
#[tokio::test]
async fn managed_connection_drop_runs_teardown_once(
#[case] drop_site: DropSite,
#[future] managed_connection_with_teardown: super::helpers::TestResult<ManagedFixture>,
) -> TestResult {
let (mut managed, teardown_count) = managed_connection_with_teardown.await?;
let (sender, receiver) = tokio::sync::oneshot::channel();
managed.notify_after_close(sender);
drop_site.drop_managed(managed).wait(GRACE).await?;
timeout(GRACE, receiver).await??;
assert_teardown_once(&teardown_count);
Ok(())
}
#[rustfmt::skip]
#[fixture]
fn client_pool_config() -> ClientPoolConfig {
ClientPoolConfig::default()
}
async fn run_ping_round_trip(pool: &TestClientPool, ping: u8) -> Result<(), ClientError> {
let lease = pool.acquire().await?;
let reply: Pong = lease.call(&Ping(ping)).await?;
assert_eq!(reply, Pong(ping), "reply should equal Pong(ping)");
Ok(())
}
struct TwoLeaseParams {
first_ping: u8,
second_ping: u8,
expected_preamble_count: usize,
expected_connection_count: usize,
}
async fn run_two_lease_scenario<F, Fut>(
config: ClientPoolConfig,
preamble_callback_count: Arc<AtomicUsize>,
between_leases: F,
params: TwoLeaseParams,
) -> TestResult
where
F: FnOnce() -> Fut,
Fut: std::future::Future<Output = ()>,
{
let server = PoolTestServer::start().await?;
let pool = build_pooled_client(server.addr, config, preamble_callback_count.clone()).await?;
run_ping_round_trip(&pool, params.first_ping).await?;
between_leases().await;
run_ping_round_trip(&pool, params.second_ping).await?;
assert_eq!(
preamble_callback_count.load(Ordering::SeqCst),
params.expected_preamble_count,
"preamble_callback_count.load(Ordering::SeqCst) should equal \
params.expected_preamble_count"
);
assert_eq!(
server.preamble_count(),
params.expected_preamble_count,
"server.preamble_count() should equal params.expected_preamble_count"
);
assert_eq!(
server.connection_count(),
params.expected_connection_count,
"server.connection_count() should equal params.expected_connection_count"
);
Ok(())
}
#[rstest]
#[tokio::test]
async fn pooled_reuse_preserves_preamble_state(client_pool_config: ClientPoolConfig) -> TestResult {
run_two_lease_scenario(
client_pool_config.pool_size(1),
Arc::new(AtomicUsize::new(0)),
|| async {},
TwoLeaseParams {
first_ping: 7,
second_ping: 8,
expected_preamble_count: 1,
expected_connection_count: 1,
},
)
.await
}
#[rstest]
#[tokio::test]
async fn pool_enforces_per_socket_in_flight_limit(
client_pool_config: ClientPoolConfig,
) -> TestResult {
let server = PoolTestServer::start().await?;
let pool = build_pooled_client(
server.addr,
client_pool_config.pool_size(1).max_in_flight_per_socket(2),
Arc::new(AtomicUsize::new(0)),
)
.await?;
let first = pool.acquire().await?;
let second = pool.acquire().await?;
let third = timeout(Duration::from_millis(25), pool.acquire()).await;
assert!(third.is_err(), "third acquire should wait for a permit");
drop(first);
let third_attempt = timeout(Duration::from_millis(100), pool.acquire()).await?;
let _third = third_attempt?;
drop(second);
Ok(())
}
#[rstest]
#[tokio::test(start_paused = true)]
async fn idle_timeout_recycles_socket_and_replays_preamble(
client_pool_config: ClientPoolConfig,
) -> TestResult {
let idle_timeout = Duration::from_millis(50);
run_two_lease_scenario(
client_pool_config.pool_size(1).idle_timeout(idle_timeout),
Arc::new(AtomicUsize::new(0)),
|| async move {
advance(idle_timeout + idle_timeout).await;
tokio::task::yield_now().await;
},
TwoLeaseParams {
first_ping: 1,
second_ping: 2,
expected_preamble_count: 2,
expected_connection_count: 2,
},
)
.await
}
#[rstest]
#[tokio::test]
async fn protocol_error_marks_connection_broken_and_reconnects(
client_pool_config: ClientPoolConfig,
) -> TestResult {
let server =
PoolTestServer::start_with_behavior(PoolServerBehavior::MalformedFirstResponse).await?;
let preamble_callback_count = Arc::new(AtomicUsize::new(0));
let pool = build_pooled_client(
server.addr,
client_pool_config.pool_size(1),
preamble_callback_count.clone(),
)
.await?;
let lease = pool.acquire().await?;
let error = lease
.call::<Ping, Pong>(&Ping(1))
.await
.expect_err("malformed response should fail decoding");
assert!(
error.should_recycle_connection(),
"assertion failed: error.should_recycle_connection()"
);
drop(lease);
let reconnected_lease = pool.acquire().await?;
let reply: Pong = reconnected_lease.call(&Ping(2)).await?;
assert_eq!(reply, Pong(2), "reply should equal Pong(2)");
assert_eq!(
preamble_callback_count.load(Ordering::SeqCst),
2,
"preamble_callback_count.load(Ordering::SeqCst) should equal 2"
);
assert_eq!(
server.preamble_count(),
2,
"server.preamble_count() should equal 2"
);
assert_eq!(
server.connection_count(),
2,
"server.connection_count() should equal 2"
);
Ok(())
}