Skip to content

Commit 708d9c3

Browse files
committed
[bitreq]: Test that pool hits refresh LRU position
Drives `a, b, a, c, a` through a `Client` with capacity 2, backed by three `tokio::net::TcpListener` servers so each URL resolves to a distinct `ConnectionKey`. On the fix, step 3 promotes `a` to most-recent, step 4's c-insert evicts `b`, and step 5 reuses the warm `a` entry — three TCP accepts. Pre-fix, `a` stays at the front of the LRU queue and gets evicted at step 4 instead — four accepts. Covers one regression only: the LRU refresh on hit. The other architectural improvement on this branch — explicit pool-layer eviction on failure / `Connection: close` — produces the same externally-observable behaviour as the pre-fix code because `AsyncConnection::send`'s interior `retry_new_connection!` machinery compensates by swapping poisoned inner state on the next use. That change is defended on architectural grounds (explicit pool-layer logic instead of reliance on the inner retry) rather than via a black-box regression test. Co-Authored-By: HAL 9000
1 parent 32cb7e0 commit 708d9c3

1 file changed

Lines changed: 107 additions & 0 deletions

File tree

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
//! Regression test for the async [`Client`](bitreq::Client) pool's LRU
2+
//! bookkeeping: a cache hit must move the entry to the most-recently-used
3+
//! slot, otherwise capacity-driven eviction drops still-warm keys.
4+
5+
#![cfg(feature = "async")]
6+
7+
use std::sync::atomic::{AtomicUsize, Ordering};
8+
use std::sync::Arc;
9+
10+
use tokio::io::{AsyncReadExt, AsyncWriteExt};
11+
use tokio::net::{TcpListener, TcpStream};
12+
13+
async fn bind_ephemeral() -> (TcpListener, String) {
14+
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
15+
let port = listener.local_addr().unwrap().port();
16+
let base_url = format!("http://127.0.0.1:{}", port);
17+
(listener, base_url)
18+
}
19+
20+
/// Reads bytes from `stream` until the HTTP header terminator `\r\n\r\n`
21+
/// is seen. Returns the accumulated buffer. Assumes no request body, which
22+
/// is true for the GETs issued by this test.
23+
async fn read_request_headers(stream: &mut TcpStream) -> std::io::Result<Vec<u8>> {
24+
let mut buf = Vec::with_capacity(512);
25+
let mut chunk = [0u8; 256];
26+
loop {
27+
let n = stream.read(&mut chunk).await?;
28+
if n == 0 {
29+
return Err(std::io::ErrorKind::UnexpectedEof.into());
30+
}
31+
buf.extend_from_slice(&chunk[..n]);
32+
if buf.windows(4).any(|w| w == b"\r\n\r\n") {
33+
return Ok(buf);
34+
}
35+
}
36+
}
37+
38+
const KEEP_ALIVE_RESPONSE: &[u8] =
39+
b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\nConnection: keep-alive\r\nKeep-Alive: timeout=60\r\n\r\nok\n";
40+
41+
#[tokio::test]
42+
async fn pool_hit_refreshes_lru_position() {
43+
// Capacity = 2, three distinct hosts (= three distinct `ConnectionKey`s
44+
// because the port differs). Request order: a, b, a, c, a.
45+
//
46+
// A correct LRU refresh-on-hit moves `a` to the most-recent slot at
47+
// step 3, so step 4's capacity-driven eviction drops `b`, and step 5
48+
// is a cache hit on `a` — three TCP accepts total. A pool that does
49+
// not refresh LRU on hit still has `a` as the oldest entry after
50+
// step 3, so step 4 evicts `a` instead, and step 5 is a miss —
51+
// four TCP accepts total.
52+
async fn run_server(listener: TcpListener, accepts: Arc<AtomicUsize>) {
53+
loop {
54+
let (mut stream, _) = match listener.accept().await {
55+
Ok(s) => s,
56+
Err(_) => return,
57+
};
58+
accepts.fetch_add(1, Ordering::SeqCst);
59+
tokio::spawn(async move {
60+
loop {
61+
if read_request_headers(&mut stream).await.is_err() {
62+
return;
63+
}
64+
if stream.write_all(KEEP_ALIVE_RESPONSE).await.is_err() {
65+
return;
66+
}
67+
}
68+
});
69+
}
70+
}
71+
72+
let (listener_a, url_a) = bind_ephemeral().await;
73+
let (listener_b, url_b) = bind_ephemeral().await;
74+
let (listener_c, url_c) = bind_ephemeral().await;
75+
76+
let accepts_a = Arc::new(AtomicUsize::new(0));
77+
let accepts_b = Arc::new(AtomicUsize::new(0));
78+
let accepts_c = Arc::new(AtomicUsize::new(0));
79+
80+
let srv_a = tokio::spawn(run_server(listener_a, Arc::clone(&accepts_a)));
81+
let srv_b = tokio::spawn(run_server(listener_b, Arc::clone(&accepts_b)));
82+
let srv_c = tokio::spawn(run_server(listener_c, Arc::clone(&accepts_c)));
83+
84+
let client = bitreq::Client::new(2);
85+
for url in [&url_a, &url_b, &url_a, &url_c, &url_a] {
86+
let response = client.send_async(bitreq::get(format!("{}/x", url))).await.unwrap();
87+
assert_eq!(response.status_code, 200);
88+
assert_eq!(response.as_bytes(), b"ok\n");
89+
}
90+
91+
srv_a.abort();
92+
srv_b.abort();
93+
srv_c.abort();
94+
let _ = tokio::join!(srv_a, srv_b, srv_c);
95+
96+
let total = accepts_a.load(Ordering::SeqCst)
97+
+ accepts_b.load(Ordering::SeqCst)
98+
+ accepts_c.load(Ordering::SeqCst);
99+
assert_eq!(
100+
total, 3,
101+
"request sequence a,b,a,c,a with capacity=2 must refresh a's LRU \
102+
position on the second hit, keeping it warm past the c-driven \
103+
eviction — expected 3 accepts (miss a, miss b, miss c), got {}",
104+
total,
105+
);
106+
assert_eq!(accepts_a.load(Ordering::SeqCst), 1, "a must be reused, not re-opened");
107+
}

0 commit comments

Comments
 (0)