Dever v0.0.2

This commit is contained in:
Codex committed 2026-11-27 06:03:56 +00:00
commit e6e175ebcf
816 files changed
+120349

No files matched your search

+366
View File
@@ -0,0 +1,366 @@
use super::*;
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::TcpListener,
};
#[tokio::test]
async fn single_call_rejects_invalid_send_before_connect() {
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let address = listener.local_addr().unwrap();
for request in [
Request::builder()
.uri("http://other.test/")
.header("host", "localhost")
.body(Full::new(Bytes::new()))
.unwrap(),
Request::builder()
.uri("/")
.body(Full::new(Bytes::new()))
.unwrap(),
Request::builder()
.uri("/")
.header("host", "localhost")
.header("host", "other")
.body(Full::new(Bytes::new()))
.unwrap(),
Request::builder()
.uri("/")
.header("host", "localhost")
.header("content-length", "0")
.body(Full::new(Bytes::new()))
.unwrap(),
Request::builder()
.uri("/")
.header("host", "localhost")
.header("x-large", "a".repeat(8192))
.body(Full::new(Bytes::new()))
.unwrap(),
Request::builder()
.uri("/")
.header("host", "localhost")
.body(Full::new(Bytes::from(vec![0; 1048577])))
.unwrap(),
] {
assert!(single::send(address, request).await.is_err());
}
assert!(
tokio::time::timeout(Duration::from_millis(10), listener.accept())
.await
.is_err()
);
}
#[tokio::test]
async fn cancelling_single_call_releases_socket_without_detached_driver() {
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let address = listener.local_addr().unwrap();
let (sent, received) = tokio::sync::oneshot::channel();
let server = tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.unwrap();
let mut head = Vec::new();
while !head.ends_with(b"\r\n\r\n") {
head.push(socket.read_u8().await.unwrap());
}
socket
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 1\r\n\r\n")
.await
.unwrap();
sent.send(()).unwrap();
assert_eq!(
tokio::time::timeout(Duration::from_secs(1), socket.read(&mut [0]))
.await
.unwrap()
.unwrap(),
0
);
});
{
let request = Request::builder()
.uri("/")
.header("host", "localhost")
.body(Full::new(Bytes::new()))
.unwrap();
let work = single::send(address, request);
tokio::pin!(work);
tokio::select! {
result = received => result.unwrap(),
result = &mut work => panic!("body should remain pending: {result:?}"),
}
}
server.await.unwrap();
}
#[tokio::test]
async fn sending_rejects_foreign_origin_headers_and_oversized_body_before_connect() {
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let port = listener.local_addr().unwrap().port();
let pool = Pool::new("127.0.0.1".into(), port, 1).await.unwrap();
let uri = format!("http://127.0.0.1:{port}/echo");
for request in [
Request::builder()
.uri("http://other.test/echo")
.body(Full::new(Bytes::new()))
.unwrap(),
Request::builder()
.uri(&uri)
.header("Host", "other.test")
.body(Full::new(Bytes::new()))
.unwrap(),
Request::builder()
.uri(&uri)
.header("Transfer-Encoding", "chunked")
.body(Full::new(Bytes::new()))
.unwrap(),
Request::builder()
.uri(&uri)
.header("x-large", "a".repeat(8192))
.body(Full::new(Bytes::new()))
.unwrap(),
Request::builder()
.uri(&uri)
.body(Full::new(Bytes::from(vec![0; 1048577])))
.unwrap(),
] {
assert!(pool.request(request).await.is_err());
}
assert!(
tokio::time::timeout(Duration::from_millis(10), listener.accept())
.await
.is_err()
);
assert_eq!(pool.requests.available_permits(), 1);
assert_eq!(pool.physical.available_permits(), 1);
pool.close().await;
}
#[tokio::test]
async fn server_listener_stop_drains_but_owner_cancel_releases_pending_requests() {
for graceful in [true, false] {
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let address = listener.local_addr().unwrap();
let owner = Owner::default();
let stop = CancellationToken::new();
let serving = tokio::spawn(server::serve(listener, stop.clone(), owner.clone()));
let mut socket = TcpStream::connect(address).await.unwrap();
socket.write_all(b"POST /echo HTTP/1.1\r\nHost: localhost\r\nContent-Length: 3\r\nExpect: 100-continue\r\n\r\n").await.unwrap();
let mut interim = [0; 25];
tokio::time::timeout(Duration::from_secs(1), socket.read_exact(&mut interim))
.await
.unwrap()
.unwrap();
assert_eq!(&interim, b"HTTP/1.1 100 Continue\r\n\r\n");
if graceful {
stop.cancel();
socket.write_all(b"abc").await.unwrap();
} else {
owner.cancel.cancel();
}
let mut response = Vec::new();
tokio::time::timeout(Duration::from_secs(1), socket.read_to_end(&mut response))
.await
.unwrap()
.unwrap();
if graceful {
assert!(response.starts_with(b"HTTP/1.1 200 OK\r\n"));
assert!(response.ends_with(b"abc"));
} else {
assert!(response.is_empty());
}
tokio::time::timeout(Duration::from_secs(1), serving)
.await
.unwrap()
.unwrap()
.unwrap();
assert!(owner.tasks.is_empty());
assert!(owner.take_faults().is_empty());
}
}
#[tokio::test]
async fn close_cancels_pending_body_and_drains_real_socket() {
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let port = listener.local_addr().unwrap().port();
let peer = tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.unwrap();
let mut bytes = [0; 2048];
assert!(socket.read(&mut bytes).await.unwrap() > 0);
socket
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabc")
.await
.unwrap();
assert_eq!(socket.read(&mut bytes).await.unwrap(), 0);
});
let pool = Pool::new("127.0.0.1".into(), port, 1).await.unwrap();
let request = Request::builder()
.uri(format!("http://127.0.0.1:{port}/"))
.body(Full::new(Bytes::new()))
.unwrap();
let (_, download) = pool.open(request).await.unwrap();
assert_eq!(download.next().await.unwrap().unwrap(), "abc");
assert_eq!(pool.requests.available_permits(), 0);
let pending = download.next();
tokio::pin!(pending);
assert!(
tokio::time::timeout(Duration::from_millis(10), &mut pending)
.await
.is_err()
);
pool.close().await;
assert_eq!(
pending.await.unwrap_err().kind(),
io::ErrorKind::NotConnected
);
assert!(download.next().await.unwrap().is_none());
assert_eq!(pool.requests.available_permits(), 1);
assert_eq!(pool.physical.available_permits(), 1);
assert!(pool.owner.tasks.is_empty());
tokio::time::timeout(Duration::from_secs(1), peer)
.await
.unwrap()
.unwrap();
}
#[tokio::test]
async fn tracker_preserves_panics_and_waits_for_destruction() {
use hyper::rt::Executor;
use std::sync::atomic::{AtomicBool, Ordering};
struct Guard(Arc<AtomicBool>);
impl Drop for Guard {
fn drop(&mut self) {
self.0.store(true, Ordering::SeqCst);
}
}
let owner = Owner::default();
let destroyed = Arc::new(AtomicBool::new(false));
let guard = Guard(destroyed.clone());
let (started, ready) = tokio::sync::oneshot::channel();
owner.execute(async move {
let _guard = guard;
started.send(()).unwrap();
std::future::pending::<()>().await;
});
ready.await.unwrap();
owner.execute(async {
panic!("original protocol failure");
});
tokio::task::yield_now().await;
owner.close().await;
assert!(destroyed.load(Ordering::SeqCst));
assert!(owner.tasks.is_empty());
let faults = owner.take_faults();
assert_eq!(faults.len(), 1);
assert_eq!(
faults[0].downcast_ref::<&str>(),
Some(&"original protocol failure")
);
}
#[tokio::test]
async fn physical_permit_lives_until_transport_drop() {
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let address = listener.local_addr().unwrap();
let slots = Arc::new(Semaphore::new(1));
let mut connector = Connector {
tcp: HttpConnector::new_with_resolver(FixedDns(Arc::new(vec![address]))),
slots: slots.clone(),
};
let uri: Uri = format!("http://{address}/").parse().unwrap();
let first = connector.call(uri.clone()).await.unwrap();
let (first_peer, _) = listener.accept().await.unwrap();
let second = connector.call(uri);
tokio::pin!(second);
assert!(
tokio::time::timeout(Duration::from_millis(10), &mut second)
.await
.is_err()
);
assert_eq!(slots.available_permits(), 0);
drop(first);
let second = tokio::time::timeout(Duration::from_secs(1), second)
.await
.unwrap()
.unwrap();
let (second_peer, _) = listener.accept().await.unwrap();
drop(second);
assert_eq!(slots.available_permits(), 1);
drop((first_peer, second_peer));
}
#[tokio::test]
async fn body_aliases_share_cursor_and_close_releases_an_unpolled_pending_read() {
for early in [true, false] {
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let port = listener.local_addr().unwrap().port();
let peer = tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.unwrap();
let mut request = [0; 2048];
assert!(socket.read(&mut request).await.unwrap() > 0);
let length = if early { 10 } else { 70000 };
socket
.write_all(
format!("HTTP/1.1 200 OK\r\nContent-Length: {length}\r\n\r\n").as_bytes(),
)
.await
.unwrap();
socket
.write_all(&vec![b'x'; if early { 3 } else { length }])
.await
.unwrap();
assert_eq!(socket.read(&mut request).await.unwrap(), 0);
});
let pool = Pool::new("127.0.0.1".into(), port, 1).await.unwrap();
let request = Request::builder()
.uri(format!("http://127.0.0.1:{port}/"))
.body(Full::new(Bytes::new()))
.unwrap();
let (_, body) = pool.open(request).await.unwrap();
let alias = body.clone();
let first = body.next().await.unwrap().unwrap();
assert!(first.len() <= 65536 && first.iter().all(|byte| *byte == b'x'));
if early {
assert_eq!(first, "xxx");
let pending = body.next();
tokio::pin!(pending);
assert!(
tokio::time::timeout(Duration::from_millis(10), &mut pending)
.await
.is_err()
);
alias.close();
// 不先 poll pending:同步 close 返回时必须已经归还正文许可。
assert_eq!(pool.requests.available_permits(), 1);
assert!(pending.await.unwrap().is_none());
} else {
let mut size = first.len();
while let Some(chunk) = alias.next().await.unwrap() {
assert!(chunk.len() <= 65536 && chunk.iter().all(|byte| *byte == b'x'));
size += chunk.len();
}
assert_eq!(size, 70000);
assert_eq!(pool.requests.available_permits(), 1);
}
assert!(body.next().await.unwrap().is_none());
pool.close().await;
assert_eq!(pool.physical.available_permits(), 1);
tokio::time::timeout(Duration::from_secs(1), peer)
.await
.unwrap()
.unwrap();
}
}
#[tokio::test]
async fn closing_a_panicked_shared_source_preserves_fault_and_releases_it() {
async fn broken() -> io::Result<Bytes> {
panic!("original body fault");
}
let body = streaming::SharedDownload::new(futures_util::stream::once(broken()));
let fault = AssertUnwindSafe(body.next())
.catch_unwind()
.await
.unwrap_err();
assert_eq!(fault.downcast_ref::<&str>(), Some(&"original body fault"));
body.close();
assert!(body.next().await.unwrap().is_none());
}