use std::{
num::NonZeroUsize,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
time::Duration,
};
use bytes::Bytes;
use futures::{SinkExt, StreamExt};
use tokio::{io::AsyncReadExt, sync::Notify, time::Instant};
use wireframe_testing::{TestError, TestResult};
use super::watch_support::{
App,
Client,
STEP_WAIT,
Scenario,
bounded_for,
ensure,
open_body,
send_complete,
spawn_connection_buffering,
};
use crate::{
app::{Envelope, ResponseHandler, StreamingHandler, WireframeApp},
connection::PEER_CLOSED_RESPONSE_GRACE,
fragment::FragmentationConfig,
request::{RequestBodyStream, RequestParts},
response::Response,
test_helpers::TestAssembler,
};
const LIVE_ROUTE: u32 = 72;
const PARKED_ROUTE: u32 = 73;
const LIVE_KEY: u64 = 51;
const PARKED_KEY: u64 = 52;
const EXPIRY_ROUTE: u32 = 74;
const EXPIRY_KEY: u64 = 61;
const TRANSPORT_CAPACITY: usize = 64;
const BULK_REPLY_BYTES: usize = 512;
const EXPIRY_TIMEOUT: Duration = Duration::from_millis(20);
const EXPIRY_SETTLE: Duration = Duration::from_millis(100);
fn bulk_answer() -> Bytes { Bytes::from(vec![7_u8; BULK_REPLY_BYTES]) }
async fn drain_to_end(mut body: RequestBodyStream) -> bool {
let mut truncated = false;
while let Some(item) = body.next().await {
truncated = truncated || item.is_err();
}
truncated
}
fn bulk_reply_handler(started: Arc<Notify>, waits_for_truncation: bool) -> StreamingHandler {
Arc::new(move |_parts: RequestParts, body: RequestBodyStream| {
let start_signal = Arc::clone(&started);
Box::pin(async move {
start_signal.notify_one();
if waits_for_truncation && !drain_to_end(body).await {
return None;
}
Some(bulk_answer())
})
})
}
fn bulk_reply(started: Arc<Notify>) -> StreamingHandler { bulk_reply_handler(started, false) }
fn truncated_body_reply(started: Arc<Notify>) -> StreamingHandler {
bulk_reply_handler(started, true)
}
fn recording_reply(served: Arc<AtomicBool>) -> ResponseHandler<Envelope> {
Arc::new(move |_request: &Envelope| {
served.store(true, Ordering::SeqCst);
Box::pin(async { Response::Single(Envelope::new(PARKED_ROUTE, None, vec![1])) })
})
}
fn streaming_app(route: u32, handler: StreamingHandler) -> TestResult<App> {
WireframeApp::new()
.map(|app| app.with_message_assembler(TestAssembler))
.and_then(|app| app.streaming_route(route, handler))
.map_err(|error| TestError::Msg(format!("build the application: {error}")))
}
fn bulk_app(started: Arc<Notify>) -> TestResult<App> {
streaming_app(LIVE_ROUTE, bulk_reply(started))
}
fn truncated_app(started: Arc<Notify>, served: Arc<AtomicBool>) -> TestResult<App> {
streaming_app(LIVE_ROUTE, truncated_body_reply(started))?
.route_response(PARKED_ROUTE, recording_reply(served))
.map_err(|error| TestError::Msg(format!("build the application: {error}")))
}
fn expiry_app(started: Arc<Notify>) -> TestResult<App> {
let fragmentation = FragmentationConfig::for_frame_budget(
1024,
NonZeroUsize::new(BULK_REPLY_BYTES * 8).unwrap_or(NonZeroUsize::MIN),
EXPIRY_TIMEOUT,
);
streaming_app(EXPIRY_ROUTE, truncated_body_reply(started))
.map(|app| app.fragmentation(fragmentation))
}
async fn ends_at_the_grace(
connection: tokio::task::JoinHandle<std::io::Result<()>>,
window: Instant,
) -> TestResult {
let joined = bounded_for(
PEER_CLOSED_RESPONSE_GRACE + STEP_WAIT,
"the connection ending after the peer half-closed",
connection,
)
.await?;
joined??;
let elapsed = window.elapsed();
ensure(
elapsed >= PEER_CLOSED_RESPONSE_GRACE,
format!("the reply must be given the idle grace: ended after {elapsed:?}"),
)?;
ensure(
elapsed <= PEER_CLOSED_RESPONSE_GRACE + STEP_WAIT,
format!("the reply must be cancelled at the grace, not later: ended after {elapsed:?}"),
)
}
async fn read_buffered(client: &mut Client) -> TestResult<usize> {
let mut buffer = [0_u8; TRANSPORT_CAPACITY];
let read = bounded_for(
STEP_WAIT,
"the reply write reaching the transport",
client.get_mut().read(&mut buffer),
)
.await??;
Ok(read)
}
#[tokio::test(start_paused = true)]
async fn a_live_reply_is_bounded_when_the_peer_stops_reading() -> TestResult {
let started = Arc::new(Notify::new());
let Scenario {
mut client,
connection,
} = spawn_connection_buffering(bulk_app(Arc::clone(&started))?, TRANSPORT_CAPACITY).await?;
open_body(&mut client, LIVE_ROUTE, LIVE_KEY, &started).await?;
ensure(
read_buffered(&mut client).await? > 0,
"the handler's reply must reach the transport before the peer leaves",
)?;
SinkExt::<Bytes>::close(&mut client).await?;
let window = Instant::now();
ends_at_the_grace(connection, window).await
}
#[tokio::test(start_paused = true)]
async fn a_cancelled_live_reply_does_not_drain_parked_messages() -> TestResult {
let served = Arc::new(AtomicBool::new(false));
let started = Arc::new(Notify::new());
let Scenario {
mut client,
connection,
} = spawn_connection_buffering(
truncated_app(Arc::clone(&started), Arc::clone(&served))?,
TRANSPORT_CAPACITY,
)
.await?;
open_body(&mut client, LIVE_ROUTE, LIVE_KEY, &started).await?;
send_complete(&mut client, PARKED_ROUTE, PARKED_KEY, b"parked").await?;
SinkExt::<Bytes>::close(&mut client).await?;
let window = Instant::now();
ends_at_the_grace(connection, window).await?;
ensure(
!served.load(Ordering::SeqCst),
"a cancelled reply must stop the parked drain",
)
}
#[tokio::test(start_paused = true)]
async fn an_expired_body_reply_is_bounded_when_the_peer_stops_reading() -> TestResult {
let started = Arc::new(Notify::new());
let Scenario {
mut client,
connection,
} = spawn_connection_buffering(expiry_app(Arc::clone(&started))?, TRANSPORT_CAPACITY).await?;
open_body(&mut client, EXPIRY_ROUTE, EXPIRY_KEY, &started).await?;
std::thread::sleep(EXPIRY_SETTLE);
ensure(
read_buffered(&mut client).await? > 0,
"the expired body's reply must reach the transport before the peer leaves",
)?;
SinkExt::<Bytes>::close(&mut client).await?;
let window = Instant::now();
ends_at_the_grace(connection, window).await
}