use std::{
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
time::Duration,
};
use rstest::{fixture, rstest};
use tokio::time::timeout;
use crate::{
client::{ClientError, ClientPoolConfig, PoolTaskChurnObserver},
test_helpers::{
LifecycleCounters,
LifecycleTestClientPool,
Ping,
Pong,
PoolServerBehavior,
PoolTestServer,
TestClientPool,
build_lifecycle_pool,
build_pooled_client,
},
};
type TestResult = Result<(), Box<dyn std::error::Error + Send + Sync>>;
const PROMPT: Duration = Duration::from_secs(1);
#[rustfmt::skip]
#[fixture]
fn client_pool_config() -> ClientPoolConfig {
ClientPoolConfig::default()
}
fn is_pool_closed(error: &ClientError) -> bool { matches!(error, ClientError::PoolClosed) }
async fn expect_pool_closed<F, T>(acquisition: F) -> TestResult
where
F: std::future::Future<Output = Result<T, ClientError>>,
{
let result = timeout(PROMPT, acquisition)
.await
.map_err(|_| "a closed pool must resolve pending acquisitions promptly")?;
let Err(error) = result else {
return Err("a closed pool must refuse the acquisition".into());
};
if is_pool_closed(&error) {
Ok(())
} else {
Err(format!("closed pool must report PoolClosed, got {error:?}").into())
}
}
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(())
}
async fn wait_for_serviced_connections(server: &PoolTestServer, expected: usize) -> usize {
let wait = async {
while server.serviced_connection_count() < expected {
tokio::task::yield_now().await;
}
};
drop(timeout(PROMPT, wait).await);
server.serviced_connection_count()
}
async fn wait_for_capacity_waits(observer: &PoolTaskChurnObserver, expected: u64) -> u64 {
let wait = async {
loop {
let waits = observer.snapshot().capacity_waits;
if waits >= expected {
return waits;
}
tokio::task::yield_now().await;
}
};
timeout(PROMPT, wait)
.await
.unwrap_or_else(|_| observer.snapshot().capacity_waits)
}
#[rstest]
#[tokio::test]
async fn close_refuses_later_handle_acquisitions(
client_pool_config: ClientPoolConfig,
) -> TestResult {
let server = PoolTestServer::start().await?;
let pool = build_pooled_client(
server.addr,
client_pool_config.pool_size(1),
Arc::new(AtomicUsize::new(0)),
)
.await?;
let mut handle = pool.handle();
pool.close().await;
expect_pool_closed(handle.acquire()).await
}
#[rstest]
#[tokio::test(flavor = "current_thread")]
async fn slot_rotation_serves_each_pool_connection(
client_pool_config: ClientPoolConfig,
) -> TestResult {
let server = PoolTestServer::start().await?;
let pool = build_pooled_client(
server.addr,
client_pool_config.pool_size(2).max_in_flight_per_socket(1),
Arc::new(AtomicUsize::new(0)),
)
.await?;
for ping in 1..=4 {
run_ping_round_trip(&pool, ping).await?;
tokio::task::yield_now().await;
}
assert_eq!(
wait_for_serviced_connections(&server, 2).await,
2,
"round-robin acquisition must dispatch work on both pool slots"
);
assert_eq!(
server.connection_count(),
2,
"both configured slots must establish a physical connection"
);
Ok(())
}
#[rstest]
#[tokio::test(flavor = "current_thread")]
async fn shutdown_drains_a_queued_waiter(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(1),
Arc::new(AtomicUsize::new(0)),
)
.await?;
let held_lease = pool.acquire().await?;
let churn = pool.task_churn_observer();
let mut first_handle = pool.handle();
let mut second_handle = pool.handle();
let first = tokio::spawn(async move { first_handle.acquire().await.map(|_lease| ()) });
let second = tokio::spawn(async move { second_handle.acquire().await.map(|_lease| ()) });
assert_eq!(
wait_for_capacity_waits(&churn, 2).await,
2,
"both acquisitions must be parked on capacity before shutdown"
);
pool.close().await;
let first_result = timeout(PROMPT, first).await??;
let second_result = timeout(PROMPT, second).await??;
let first_error = first_result.expect_err("first waiter must fail once the pool closes");
let second_error = second_result.expect_err("second waiter must fail once the pool closes");
assert!(
is_pool_closed(&first_error),
"first waiter must report PoolClosed, got {first_error:?}"
);
assert!(
is_pool_closed(&second_error),
"second waiter must report PoolClosed, got {second_error:?}"
);
drop(held_lease);
Ok(())
}
const RECONNECT_WATCHDOG: Duration = Duration::from_secs(5);
async fn receive_teardown_generation(
counters: &mut LifecycleCounters,
) -> Result<usize, Box<dyn std::error::Error + Send + Sync>> {
let received = timeout(PROMPT, counters.teardown_generations.recv())
.await
.map_err(|_| "teardown callback did not run within the grace period")?
.ok_or("teardown channel closed without reporting a generation")?;
Ok(received)
}
async fn fail_first_lease(pool: &LifecycleTestClientPool) -> TestResult {
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(),
"a decode error must recycle the pooled connection"
);
drop(lease);
Ok(())
}
async fn use_replacement_connection(
pool: &LifecycleTestClientPool,
server: &PoolTestServer,
) -> TestResult {
let lease = pool.acquire().await?;
let reply: Pong = lease.call(&Ping(2)).await?;
assert_eq!(reply, Pong(2), "reply should equal Pong(2)");
drop(lease);
assert_eq!(
server.connection_count(),
2,
"reconnect must open a replacement connection rather than reuse the broken one"
);
Ok(())
}
fn assert_hooks_observed(counters: &LifecycleCounters) {
assert_eq!(
counters.setup_count.load(Ordering::SeqCst),
2,
"setup must run on both the original and the replacement connection"
);
assert!(
counters.error_count.load(Ordering::SeqCst) >= 1,
"the decode failure must invoke the error hook"
);
}
async fn assert_next_teardown(
counters: &mut LifecycleCounters,
expected: usize,
connection: &str,
) -> TestResult {
assert_eq!(
receive_teardown_generation(counters).await?,
expected,
"{connection} teardown must receive generation {expected}"
);
Ok(())
}
async fn run_lifecycle_reconnect_scenario(config: ClientPoolConfig) -> TestResult {
let server =
PoolTestServer::start_with_behavior(PoolServerBehavior::MalformedFirstResponse).await?;
let (pool, mut counters) = build_lifecycle_pool(server.addr, config.pool_size(1)).await?;
fail_first_lease(&pool).await?;
assert_next_teardown(&mut counters, 1, "first connection").await?;
use_replacement_connection(&pool, &server).await?;
assert_hooks_observed(&counters);
pool.close().await;
assert_next_teardown(&mut counters, 2, "replacement connection").await?;
Ok(())
}
#[rstest]
#[tokio::test]
async fn lifecycle_hooks_survive_pooled_reconnect(
client_pool_config: ClientPoolConfig,
) -> TestResult {
timeout(
RECONNECT_WATCHDOG,
run_lifecycle_reconnect_scenario(client_pool_config),
)
.await
.map_err(|_| "lifecycle reconnect scenario exceeded its watchdog")?
}