use std::{
num::NonZeroUsize,
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
time::Duration,
};
use bytes::Bytes;
use futures::SinkExt;
use tokio::sync::Notify;
use wireframe_testing::{TestError, TestResult};
#[cfg(feature = "metrics")]
use super::super::stream_outcome_support::{paused_block_on, recorded};
use super::{
STALLED_BODY_BOUND,
watch_support::{
App,
STEP_WAIT,
Scenario,
bounded,
bounded_for,
ensure,
read_reply_within,
send_complete,
send_request,
spawn_connection,
},
};
#[cfg(feature = "metrics")]
use crate::metrics::StreamingBodyOutcome;
use crate::{
app::{BudgetBytes, Envelope, MemoryBudgets, ResponseHandler, StreamingHandler, WireframeApp},
request::{RequestBodyStream, RequestParts},
response::Response,
test_helpers::{TestAssembler, continuation_frame_payload, first_frame_payload},
};
const STALLED_ROUTE: u32 = 75;
const STALLED_KEY: u64 = 62;
const PROBE_ROUTE: u32 = 76;
const PROBE_KEY: u64 = 63;
const PROBE_REPLY: &[u8] = b"served";
const CHUNK_BYTES: usize = 256;
const MESSAGE_BUDGET: usize = 64 * 1024;
const CONNECTION_BUDGET: usize = 500;
const END_WAIT: Duration = Duration::from_millis(200);
fn past_stall_bound() -> Duration { STALLED_BODY_BOUND + STEP_WAIT }
fn stalled_handler(
started: Arc<Notify>,
release: Arc<Notify>,
read: Arc<AtomicUsize>,
) -> StreamingHandler {
Arc::new(move |_parts: RequestParts, body: RequestBodyStream| {
let start_signal = Arc::clone(&started);
let release_signal = Arc::clone(&release);
let counted = Arc::clone(&read);
Box::pin(async move {
start_signal.notify_one();
release_signal.notified().await;
counted.fetch_add(1, Ordering::SeqCst);
drop(body);
None
})
})
}
fn probe_reply() -> ResponseHandler<Envelope> {
Arc::new(|_request: &Envelope| {
Box::pin(async { Response::Single(Envelope::new(PROBE_ROUTE, None, PROBE_REPLY.to_vec())) })
})
}
fn budget(bytes: usize) -> TestResult<BudgetBytes> {
NonZeroUsize::new(bytes)
.map(BudgetBytes::new)
.ok_or_else(|| format!("a budget of {bytes} bytes must be non-zero").into())
}
fn stalled_app(handler: StreamingHandler) -> TestResult<App> {
let budgets = MemoryBudgets::new(
budget(MESSAGE_BUDGET)?,
budget(CONNECTION_BUDGET)?,
budget(CONNECTION_BUDGET)?,
);
WireframeApp::new()
.map(|app| app.with_message_assembler(TestAssembler))
.and_then(|app| app.streaming_route(STALLED_ROUTE, handler))
.and_then(|app| app.route_response(PROBE_ROUTE, probe_reply()))
.map(|app| app.memory_budgets(budgets))
.map_err(|error| TestError::Msg(format!("build the application: {error}")))
}
#[tokio::test(start_paused = true)]
async fn a_peer_leaving_while_a_chunk_waits_is_observed() -> TestResult {
let started = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let read = Arc::new(AtomicUsize::new(0));
let Scenario {
mut client,
connection,
} = spawn_connection(stalled_app(stalled_handler(
Arc::clone(&started),
Arc::clone(&release),
Arc::clone(&read),
))?)
.await?;
let chunk = vec![7_u8; CHUNK_BYTES];
send_request(
&mut client,
STALLED_ROUTE,
&first_frame_payload(STALLED_KEY.into(), &chunk, false, None)?,
)
.await?;
bounded("the live handler starting", started.notified()).await?;
send_request(
&mut client,
STALLED_ROUTE,
&continuation_frame_payload(STALLED_KEY.into(), 1_u32.into(), &chunk, false)?,
)
.await?;
SinkExt::<Bytes>::close(&mut client).await?;
let joined = bounded_for(
STEP_WAIT + END_WAIT,
"the connection ending after the peer left",
connection,
)
.await?;
joined??;
ensure(
read.load(Ordering::SeqCst) == 0,
"the stalled handler must not be released",
)
}
#[cfg(feature = "metrics")]
#[test]
fn a_stalled_final_chunk_ends_its_body_within_budget() -> TestResult {
let (scenario, counts) = recorded(|| paused_block_on(stalled_final_chunk_scenario()));
scenario??;
ensure(
counts.count(StreamingBodyOutcome::Delivered) == 0,
"a final chunk the budget refuses must not be counted as delivered",
)?;
ensure(
counts.count(StreamingBodyOutcome::Abandoned) > 0,
"the body the refused final chunk ended must be counted as abandoned",
)
}
#[cfg(feature = "metrics")]
async fn stalled_final_chunk_scenario() -> TestResult {
let started = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let read = Arc::new(AtomicUsize::new(0));
let Scenario {
mut client,
connection,
} = spawn_connection(stalled_app(stalled_handler(
Arc::clone(&started),
Arc::clone(&release),
Arc::clone(&read),
))?)
.await?;
let chunk = vec![7_u8; CHUNK_BYTES];
send_request(
&mut client,
STALLED_ROUTE,
&first_frame_payload(STALLED_KEY.into(), &chunk, false, None)?,
)
.await?;
bounded("the live handler starting", started.notified()).await?;
send_request(
&mut client,
STALLED_ROUTE,
&continuation_frame_payload(STALLED_KEY.into(), 1_u32.into(), &chunk, true)?,
)
.await?;
send_request(
&mut client,
STALLED_ROUTE,
&continuation_frame_payload(STALLED_KEY.into(), 2_u32.into(), &chunk, false)?,
)
.await?;
send_complete(&mut client, PROBE_ROUTE, PROBE_KEY, b"probe").await?;
SinkExt::<Bytes>::close(&mut client).await?;
let joined = bounded_for(
past_stall_bound() + END_WAIT,
"the connection ending after the stalled final chunk",
connection,
)
.await?;
joined??;
ensure(
read.load(Ordering::SeqCst) == 0,
"the stalled handler must not be released",
)
}
#[tokio::test(start_paused = true)]
async fn a_chunk_stalled_behind_a_buffered_frame_ends_its_body() -> TestResult {
let started = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let read = Arc::new(AtomicUsize::new(0));
let Scenario {
mut client,
connection,
} = spawn_connection(stalled_app(stalled_handler(
Arc::clone(&started),
Arc::clone(&release),
Arc::clone(&read),
))?)
.await?;
let chunk = vec![7_u8; CHUNK_BYTES];
send_request(
&mut client,
STALLED_ROUTE,
&first_frame_payload(STALLED_KEY.into(), &chunk, false, None)?,
)
.await?;
bounded("the live handler starting", started.notified()).await?;
send_request(
&mut client,
STALLED_ROUTE,
&continuation_frame_payload(STALLED_KEY.into(), 1_u32.into(), &chunk, false)?,
)
.await?;
send_request(
&mut client,
STALLED_ROUTE,
&continuation_frame_payload(STALLED_KEY.into(), 2_u32.into(), &chunk, false)?,
)
.await?;
send_complete(&mut client, PROBE_ROUTE, PROBE_KEY, b"probe").await?;
let reply = read_reply_within(past_stall_bound(), &mut client, "the probe reply").await?;
ensure(
reply == PROBE_REPLY,
format!("the probe must be served once the stalled body fails, got {reply:?}"),
)?;
ensure(
read.load(Ordering::SeqCst) == 0,
"the stalled handler must not be released",
)?;
SinkExt::<Bytes>::close(&mut client).await?;
let joined = bounded_for(
STEP_WAIT + END_WAIT,
"the connection ending after the peer left",
connection,
)
.await?;
joined??;
Ok(())
}