171 lines
6.6 KiB
Rust
171 lines
6.6 KiB
Rust
use super::{tests::limits, *};
|
|
use crate::{task, tls};
|
|
use http_body_util::Full;
|
|
use hyper::service::service_fn;
|
|
use std::{convert::Infallible, time::Duration};
|
|
use tokio::{
|
|
io::{AsyncReadExt, AsyncWriteExt},
|
|
net::TcpListener,
|
|
};
|
|
|
|
fn request() -> Request {
|
|
Request {
|
|
method: "GET".into(),
|
|
target: "/stream".into(),
|
|
headers: vec![],
|
|
body: Bytes::new(),
|
|
}
|
|
}
|
|
fn pool() -> PoolLimits {
|
|
PoolLimits {
|
|
idle_ms: 1000,
|
|
chunk_bytes: 3,
|
|
read_ms: 200,
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn stream_bounds_chunks_and_eof_returns_capacity_for_connection_reuse() {
|
|
task::run(true, 16, async |scope| {
|
|
for http2 in [false, true] {
|
|
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
|
|
let origin = format!("http://{}", listener.local_addr().unwrap());
|
|
let peer = tokio::spawn(async move {
|
|
// 只接收一个连接;后续请求成功说明 EOF 后真实归还了容量和连接。
|
|
let (stream, _) = listener.accept().await.unwrap();
|
|
let service = service_fn(|_| async {
|
|
Ok::<_, Infallible>(hyper::Response::new(Full::new(Bytes::from_static(
|
|
b"abcdefghij",
|
|
))))
|
|
});
|
|
let stream = TokioIo::new(stream);
|
|
if http2 {
|
|
hyper::server::conn::http2::Builder::new(TokioExecutor::new())
|
|
.serve_connection(stream, service)
|
|
.await
|
|
.unwrap();
|
|
} else {
|
|
hyper::server::conn::http1::Builder::new()
|
|
.serve_connection(stream, service)
|
|
.await
|
|
.unwrap();
|
|
}
|
|
});
|
|
let mut limits = limits(http2);
|
|
limits.connections = 1;
|
|
limits.body_bytes = 2; // 流式下载不收集整个正文,允许超过完整响应的收集限额。
|
|
let client = client(&origin, &tls::system(), &limits, &pool(), scope)
|
|
.await
|
|
.unwrap();
|
|
for _ in 0..2 {
|
|
let response = client.open(request(), |item| item).await.unwrap();
|
|
assert_eq!(response.status, 200);
|
|
let mut bytes = Vec::new();
|
|
let mut chunks = 0;
|
|
while let Some(chunk) = response.body.next().await.unwrap() {
|
|
let chunk = chunk.unwrap();
|
|
assert!(!chunk.is_empty() && chunk.len() <= 3);
|
|
bytes.extend_from_slice(&chunk);
|
|
chunks += 1;
|
|
}
|
|
assert_eq!(bytes, b"abcdefghij");
|
|
assert!(chunks >= 4);
|
|
assert!(response.body.next().await.unwrap().is_none());
|
|
}
|
|
client.close().await.unwrap();
|
|
tokio::time::timeout(Duration::from_secs(2), peer)
|
|
.await
|
|
.unwrap()
|
|
.unwrap();
|
|
}
|
|
Ok::<_, ()>(())
|
|
})
|
|
.unwrap()
|
|
.unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn stream_delivers_headers_and_partial_data_before_one_terminal_error() {
|
|
task::run(true, 16, async |scope| {
|
|
for mode in ["truncated", "timeout", "client_close", "stream_close"] {
|
|
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
|
|
let origin = format!("http://{}", listener.local_addr().unwrap());
|
|
let (continue_body, continuation) = tokio::sync::oneshot::channel();
|
|
let peer = tokio::spawn(async move {
|
|
let (mut stream, _) = listener.accept().await.unwrap();
|
|
let mut buffer = [0; 8192];
|
|
assert!(stream.read(&mut buffer).await.unwrap() > 0);
|
|
stream
|
|
.write_all(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n")
|
|
.await
|
|
.unwrap();
|
|
// 客户端必须先取得响应头,服务端才开始发送正文。
|
|
continuation.await.unwrap();
|
|
stream.write_all(b"3\r\nabc\r\n").await.unwrap();
|
|
if mode == "truncated" {
|
|
stream.write_all(b"5\r\nx").await.unwrap();
|
|
} else {
|
|
stream.read_to_end(&mut Vec::new()).await.unwrap();
|
|
}
|
|
});
|
|
let client = client(&origin, &tls::system(), &limits(false), &pool(), scope)
|
|
.await
|
|
.unwrap();
|
|
let response = client.open(request(), |item| item).await.unwrap();
|
|
assert_eq!(response.status, 200);
|
|
continue_body.send(()).unwrap();
|
|
assert_eq!(
|
|
response.body.next().await.unwrap().unwrap().unwrap(),
|
|
b"abc"[..]
|
|
);
|
|
if mode == "stream_close" {
|
|
let mut pending = Box::pin(response.body.next());
|
|
tokio::select! {
|
|
result = &mut pending => panic!("body must wait: {result:?}"),
|
|
() = tokio::time::sleep(Duration::from_millis(10)) => {},
|
|
}
|
|
response.body.close();
|
|
assert!(pending.await.unwrap().is_none());
|
|
} else if mode == "client_close" {
|
|
let mut pending = Box::pin(response.body.next());
|
|
tokio::select! {
|
|
result = &mut pending => panic!("body must wait: {result:?}"),
|
|
() = tokio::time::sleep(Duration::from_millis(10)) => {},
|
|
}
|
|
client.close().await.unwrap();
|
|
assert_eq!(
|
|
pending.await.unwrap().unwrap().unwrap_err().kind(),
|
|
io::ErrorKind::NotConnected
|
|
);
|
|
} else {
|
|
let error = loop {
|
|
match response
|
|
.body
|
|
.next()
|
|
.await
|
|
.unwrap()
|
|
.expect("terminal failure must be delivered")
|
|
{
|
|
Ok(bytes) => assert_eq!(bytes, b"x"[..]),
|
|
Err(error) => break error,
|
|
}
|
|
};
|
|
if mode == "timeout" {
|
|
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
|
|
}
|
|
}
|
|
assert!(response.body.next().await.unwrap().is_none());
|
|
if mode != "client_close" {
|
|
client.close().await.unwrap();
|
|
}
|
|
tokio::time::timeout(Duration::from_secs(2), peer)
|
|
.await
|
|
.unwrap()
|
|
.unwrap();
|
|
}
|
|
Ok::<_, ()>(())
|
|
})
|
|
.unwrap()
|
|
.unwrap();
|
|
}
|