use super::{
operations,
support::{start, stop},
};
use servlet::{
ecosystem::tokio,
health::CheckPolicy,
io::{self, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt},
net::{TcpListener, TcpStream},
sql::{PgConfig, PgLimits, PgOperations, PgReadiness, PgTls, query_scalar},
sync::Notify,
time::{Instant, sleep, timeout},
};
use std::{
net::SocketAddr,
sync::{
Arc,
atomic::{AtomicBool, AtomicUsize, Ordering},
},
time::Duration,
};
use tokio::task::JoinSet;
#[tokio::test]
#[ignore = "requires isolated PostgreSQL; python3 -B scripts/postgres_test.py"]
async fn stalled_readiness_replies_release_pool_capacity() {
let (_proxy, config, stall) =
loopback_proxy(|kind| matches!(kind, b'B' | b'P' | b'Q'), None).await;
let config = config
.with_limits(PgLimits {
max_connections: 1,
min_connections: 0,
..PgLimits::default()
})
.unwrap()
.with_readiness(PgReadiness::Required(CheckPolicy {
interval: Duration::from_millis(100),
timeout: Duration::from_millis(500),
}))
.unwrap();
let (running, pool) = start(config).await;
let handle = running.handle();
assert!(handle.is_ready());
let original_pid: i32 = query_scalar("SELECT pg_backend_pid()")
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(stall.accepted.load(Ordering::Relaxed), 1);
stall.armed.store(true, Ordering::Relaxed);
timeout(Duration::from_secs(5), async {
while handle.is_ready() {
sleep(Duration::from_millis(5)).await;
}
})
.await
.expect("the stalled probe should withdraw readiness");
timeout(Duration::from_secs(5), async {
while !handle.is_ready() {
sleep(Duration::from_millis(5)).await;
}
})
.await
.expect("the pool should replace the interrupted connection and recover readiness");
let replacement_pid: i32 = query_scalar("SELECT pg_backend_pid()")
.fetch_one(&pool)
.await
.unwrap();
assert_ne!(replacement_pid, original_pid);
stop(running, pool).await;
}
#[tokio::test]
#[ignore = "requires isolated PostgreSQL; python3 -B scripts/postgres_test.py"]
async fn successful_operation_survives_recycle_timeout_and_pool_replaces_connection() {
let (_proxy, config, stall) = loopback_proxy(|kind| kind == b'S', None).await;
let config = config
.with_limits(PgLimits {
max_connections: 1,
min_connections: 1,
acquire_timeout: Duration::from_secs(1),
..PgLimits::default()
})
.unwrap()
.with_readiness(PgReadiness::NotRequired)
.unwrap();
let (running, database, metrics) = operations::start_with_config("lookup", config).await;
let original_pid = successful_query_with_stalled_return(&database, &stall).await;
timeout(Duration::from_secs(3), async {
while database.pool().num_idle() == 0 {
sleep(Duration::from_millis(5)).await;
}
})
.await
.expect("the pool should discard the stalled return and replenish its minimum size");
let replacement_pid: i32 = database
.get("lookup")
.unwrap()
.run(Instant::now() + Duration::from_secs(2), |connection| {
Box::pin(query_scalar("SELECT pg_backend_pid()").fetch_one(connection))
})
.await
.unwrap();
assert_ne!(replacement_pid, original_pid);
assert_eq!(stall.accepted.load(Ordering::Relaxed), 2);
operations::outcome(&metrics, "lookup", "ok", 2);
operations::stop(running, database).await;
}
#[tokio::test]
#[ignore = "requires isolated PostgreSQL; python3 -B scripts/postgres_test.py"]
async fn timed_out_replacement_replenishes_minimum_without_replaying_the_operation() {
let (_proxy, config, stall) = loopback_proxy(|kind| kind == b'S', Some(2)).await;
let config = config
.with_limits(PgLimits {
max_connections: 1,
min_connections: 1,
acquire_timeout: Duration::from_millis(500),
..PgLimits::default()
})
.unwrap()
.with_readiness(PgReadiness::NotRequired)
.unwrap();
let (running, database, metrics) = operations::start_with_config("lookup", config).await;
let original_pid = successful_query_with_stalled_return(&database, &stall).await;
timeout(Duration::from_secs(2), stall.replacement_started.notified())
.await
.expect("replenishment should open a replacement without demand from a query");
timeout(
Duration::from_millis(900),
stall.replacement_closed.notified(),
)
.await
.expect("the first stalled replacement should close at the acquisition deadline");
timeout(Duration::from_secs(2), async {
while database.pool().num_idle() == 0 {
sleep(Duration::from_millis(5)).await;
}
})
.await
.expect("the minimum should recover after the replacement times out");
let replacement_pid: i32 = query_scalar("SELECT pg_backend_pid()")
.fetch_one(database.pool())
.await
.unwrap();
assert_ne!(replacement_pid, original_pid);
assert_eq!(stall.accepted.load(Ordering::Relaxed), 3);
operations::outcome(&metrics, "lookup", "ok", 1);
operations::stop(running, database).await;
}
#[tokio::test]
#[ignore = "requires isolated PostgreSQL; python3 -B scripts/postgres_test.py"]
async fn pool_shutdown_interrupts_a_stalled_replacement_handshake() {
let (_proxy, config, stall) = loopback_proxy(|kind| kind == b'S', Some(2)).await;
let config = config
.with_limits(PgLimits {
max_connections: 1,
min_connections: 1,
acquire_timeout: Duration::from_secs(2),
..PgLimits::default()
})
.unwrap()
.with_readiness(PgReadiness::NotRequired)
.unwrap();
let (running, database, metrics) = operations::start_with_config("lookup", config).await;
successful_query_with_stalled_return(&database, &stall).await;
timeout(Duration::from_secs(4), stall.replacement_started.notified())
.await
.expect("replenishment should be inside the stalled handshake");
operations::outcome(&metrics, "lookup", "ok", 1);
operations::stop(running, database).await;
timeout(Duration::from_secs(1), stall.replacement_closed.notified())
.await
.expect("pool cleanup should have released the replacement socket");
assert_eq!(stall.accepted.load(Ordering::Relaxed), 2);
}
#[tokio::test]
#[ignore = "requires isolated PostgreSQL; python3 -B scripts/postgres_test.py"]
async fn a_healthy_idle_connection_remains_usable_during_replenishment() {
let (_proxy, config, stall) = loopback_proxy(|_| false, Some(3)).await;
let config = config
.with_limits(PgLimits {
max_connections: 2,
min_connections: 2,
acquire_timeout: Duration::from_secs(2),
..PgLimits::default()
})
.unwrap()
.with_readiness(PgReadiness::NotRequired)
.unwrap();
let (running, pool) = start(config).await;
timeout(Duration::from_secs(1), async {
while pool.num_idle() != 2 {
sleep(Duration::from_millis(5)).await;
}
})
.await
.unwrap();
drop(pool.try_acquire().unwrap().detach());
timeout(Duration::from_secs(2), stall.replacement_started.notified())
.await
.expect("retiring a connection should trigger replenishment");
let value: i32 = timeout(
Duration::from_millis(500),
query_scalar("SELECT 42").fetch_one(&pool),
)
.await
.expect("a stalled replacement should not hold the remaining connection")
.unwrap();
assert_eq!(value, 42);
stop(running, pool).await;
timeout(Duration::from_secs(1), stall.replacement_closed.notified())
.await
.expect("pool cleanup should have released the replacement socket");
}
#[tokio::test]
#[ignore = "requires isolated PostgreSQL; python3 -B scripts/postgres_test.py"]
async fn pool_shutdown_interrupts_stalled_return_before_recycle_timeout() {
let (_proxy, config, stall) = loopback_proxy(|kind| kind == b'S', None).await;
let config = config
.with_limits(PgLimits {
max_connections: 1,
min_connections: 0,
acquire_timeout: Duration::from_secs(10),
..PgLimits::default()
})
.unwrap()
.with_readiness(PgReadiness::NotRequired)
.unwrap();
let (running, database, metrics) = operations::start_with_config("lookup", config).await;
successful_query_with_stalled_return(&database, &stall).await;
operations::outcome(&metrics, "lookup", "ok", 1);
operations::stop(running, database).await;
}
async fn successful_query_with_stalled_return(
database: &PgOperations,
stall: &Arc<ReplyStall>,
) -> i32 {
let callback_stall = stall.clone();
let pid = database
.get("lookup")
.unwrap()
.run(Instant::now() + Duration::from_secs(2), move |connection| {
Box::pin(async move {
let pid: i32 = query_scalar("SELECT pg_backend_pid()")
.fetch_one(connection)
.await?;
assert_eq!(callback_stall.accepted.load(Ordering::Relaxed), 1);
callback_stall.armed.store(true, Ordering::Relaxed);
Ok(pid)
})
})
.await
.unwrap();
timeout(Duration::from_secs(2), stall.withheld.notified())
.await
.expect("the return ping should reach the local relay after the query succeeds");
assert!(pid > 0);
pid
}
#[derive(Default)]
struct ReplyStall {
armed: AtomicBool,
accepted: AtomicUsize,
withheld: Notify,
replacement_started: Notify,
replacement_closed: Notify,
}
async fn loopback_proxy(
stall_on: fn(u8) -> bool,
stall_handshake: Option<usize>,
) -> (JoinSet<()>, PgConfig, Arc<ReplyStall>) {
let mut url = url::Url::parse(&std::env::var("SERVLET_TEST_PG_URL").unwrap()).unwrap();
let upstream = SocketAddr::new(
url.host_str().unwrap().parse().unwrap(),
url.port().unwrap(),
);
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
url.set_port(Some(listener.local_addr().unwrap().port()))
.unwrap();
let config = PgConfig::new(url.as_str(), "postgres-stall")
.unwrap()
.with_tls(PgTls::PlaintextLoopback)
.unwrap();
let stall = Arc::new(ReplyStall::default());
let mut proxy = JoinSet::new();
proxy.spawn(serve(
listener,
upstream,
stall_on,
stall_handshake,
stall.clone(),
));
(proxy, config, stall)
}
async fn serve(
listener: TcpListener,
upstream: SocketAddr,
stall_on: fn(u8) -> bool,
stall_handshake: Option<usize>,
stall: Arc<ReplyStall>,
) {
let mut tunnels = JoinSet::new();
loop {
tokio::select! {
result = listener.accept() => {
let (mut client, _) = result.unwrap();
let index = stall.accepted.fetch_add(1, Ordering::Relaxed) + 1;
let stall = stall.clone();
tunnels.spawn(async move {
if stall_handshake == Some(index) {
return stall_replacement_handshake(client, stall).await;
}
let mut server = TcpStream::connect(upstream).await?;
client.set_nodelay(true)?;
server.set_nodelay(true)?;
if index == 1 {
stall_first_connection(client, server, stall_on, stall).await
} else {
io::copy_bidirectional(&mut client, &mut server).await?;
Ok(())
}
});
}
_ = tunnels.join_next(), if !tunnels.is_empty() => {}
}
}
}
async fn stall_replacement_handshake(
mut client: TcpStream,
stall: Arc<ReplyStall>,
) -> io::Result<()> {
forward_packet(&mut client, &mut io::sink()).await?;
stall.replacement_started.notify_one();
io::copy(&mut client, &mut io::sink()).await?;
stall.replacement_closed.notify_one();
Ok(())
}
async fn stall_first_connection(
mut client: TcpStream,
mut server: TcpStream,
stall_on: fn(u8) -> bool,
stall: Arc<ReplyStall>,
) -> io::Result<()> {
let (mut client_read, mut client_write) = client.split();
let (mut server_read, mut server_write) = server.split();
let stalled = AtomicBool::new(false);
let requests = async {
forward_packet(&mut client_read, &mut server_write).await?;
loop {
let kind = client_read.read_u8().await?;
if stall_on(kind)
&& stall.armed.load(Ordering::Relaxed)
&& !stalled.swap(true, Ordering::Relaxed)
{
stall.withheld.notify_one();
}
server_write.write_u8(kind).await?;
forward_packet(&mut client_read, &mut server_write).await?;
}
};
let replies = async {
let mut bytes = [0; 8192];
loop {
let count = server_read.read(&mut bytes).await?;
if count == 0 {
return Ok(());
}
if !stalled.load(Ordering::Relaxed) {
client_write.write_all(&bytes[..count]).await?;
}
}
};
tokio::select! {
result = requests => result,
result = replies => result,
}
}
async fn forward_packet(
read: &mut (impl AsyncRead + Unpin),
write: &mut (impl AsyncWrite + Unpin),
) -> io::Result<()> {
let length = read.read_u32().await?;
write.write_u32(length).await?;
io::copy(&mut read.take(u64::from(length) - 4), write).await?;
Ok(())
}