use std::sync::Arc;
use bytes::Bytes;
use futures::{SinkExt, StreamExt, stream};
use tokio::{sync::Notify, time::Instant};
use wireframe_testing::{TestError, TestResult};
use super::watch_support::{
App,
GRACE_SLACK,
Scenario,
bounded_for,
ensure,
open_body,
read_reply,
send_complete,
send_request,
spawn_connection,
};
use crate::{
app::{Envelope, ResponseHandler, StreamingHandler, WireframeApp},
connection::PEER_CLOSED_RESPONSE_GRACE,
request::{RequestBodyStream, RequestParts},
response::{FrameStream, Response, WireframeError},
test_helpers::{TestAssembler, continuation_frame_payload},
};
const LIVE_ROUTE: u32 = 70;
const PARKED_ROUTE: u32 = 71;
const LIVE_KEY: u64 = 41;
const PARKED_KEY: u64 = 42;
fn holding_handler(started: Arc<Notify>, release: Arc<Notify>) -> StreamingHandler {
Arc::new(move |_parts: RequestParts, mut body: RequestBodyStream| {
let start_signal = Arc::clone(&started);
let release_signal = Arc::clone(&release);
Box::pin(async move {
start_signal.notify_one();
release_signal.notified().await;
while let Some(item) = body.next().await {
item.ok()?;
}
Some(Bytes::from_static(b"live"))
})
})
}
fn stalled_reply() -> ResponseHandler<Envelope> {
Arc::new(|_request: &Envelope| {
Box::pin(async {
let first = Envelope::new(PARKED_ROUTE, None, vec![1]);
let frames: FrameStream<Envelope, ()> = Box::pin(
stream::once(async move { Ok::<_, WireframeError<()>>(first) })
.chain(stream::pending()),
);
Response::Stream(frames)
})
})
}
fn scenario_app(started: Arc<Notify>, release: Arc<Notify>) -> TestResult<App> {
WireframeApp::new()
.map(|app| app.with_message_assembler(TestAssembler))
.and_then(|app| app.streaming_route(LIVE_ROUTE, holding_handler(started, release)))
.and_then(|app| app.route_response(PARKED_ROUTE, stalled_reply()))
.map_err(|error| TestError::Msg(format!("build the application: {error}")))
}
#[tokio::test(start_paused = true)]
async fn a_parked_reply_observes_a_peer_that_half_closes_while_it_streams() -> TestResult {
let started = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let Scenario {
mut client,
connection,
} = spawn_connection(scenario_app(Arc::clone(&started), Arc::clone(&release))?).await?;
open_body(&mut client, LIVE_ROUTE, LIVE_KEY, &started).await?;
send_complete(&mut client, PARKED_ROUTE, PARKED_KEY, b"parked").await?;
release.notify_one();
send_request(
&mut client,
LIVE_ROUTE,
&continuation_frame_payload(LIVE_KEY.into(), 1.into(), b"end", true)?,
)
.await?;
ensure(
read_reply(&mut client, "the live reply").await? == b"live".to_vec(),
"the live body must be answered before the parked one",
)?;
ensure(
read_reply(&mut client, "the parked reply's first frame").await? == vec![1],
"the parked reply must start streaming once the slot frees",
)?;
SinkExt::<Bytes>::close(&mut client).await?;
let window = Instant::now();
let joined = bounded_for(
PEER_CLOSED_RESPONSE_GRACE + GRACE_SLACK,
"the connection ending after the peer half-closed",
connection,
)
.await?;
joined??;
let elapsed = window.elapsed();
ensure(
elapsed >= PEER_CLOSED_RESPONSE_GRACE,
format!(
"a stalled parked reply must survive the idle grace, not be cut short: ended after \
{elapsed:?}"
),
)?;
ensure(
elapsed <= PEER_CLOSED_RESPONSE_GRACE + GRACE_SLACK,
format!("the reply must be cancelled at the grace, not later: ended after {elapsed:?}"),
)?;
ensure(
client.next().await.is_none(),
"the connection must close rather than serve a frame after the grace",
)
}
#[tokio::test(start_paused = true)]
async fn a_parked_reply_is_bounded_when_the_peer_closes_before_it_drains() -> TestResult {
let started = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let Scenario {
mut client,
connection,
} = spawn_connection(scenario_app(Arc::clone(&started), Arc::clone(&release))?).await?;
open_body(&mut client, LIVE_ROUTE, LIVE_KEY, &started).await?;
release.notify_one();
send_complete(&mut client, PARKED_ROUTE, PARKED_KEY, b"parked").await?;
SinkExt::<Bytes>::close(&mut client).await?;
ensure(
read_reply(&mut client, "the parked reply's first frame").await? == vec![1],
"the parked reply must start streaming after the truncated body fails",
)?;
let joined = bounded_for(
PEER_CLOSED_RESPONSE_GRACE + GRACE_SLACK,
"the connection ending after the peer closed",
connection,
)
.await?;
joined??;
ensure(
client.next().await.is_none(),
"the connection must close rather than serve a frame after the grace",
)
}