use std::{io, process::Command, sync::Arc};
use bytes::Bytes;
use futures::{SinkExt, StreamExt};
use metrics_util::debugging::{DebugValue, DebuggingRecorder, Snapshotter};
use tokio::{sync::Notify, task::JoinHandle};
use wireframe_testing::{TestError, TestResult};
use super::watch_support::{
App,
Client,
STEP_WAIT,
Scenario,
bounded_for,
ensure,
open_body,
read_reply,
send_complete,
send_request,
spawn_connection,
};
use crate::{
app::{Envelope, ResponseHandler, StreamingHandler, WireframeApp},
metrics::STREAMING_BODIES_PARKED,
request::{RequestBodyStream, RequestParts},
response::Response,
test_helpers::{TestAssembler, continuation_frame_payload},
};
const LIVE_ROUTE: u32 = 80;
const PARKED_ROUTE: u32 = 81;
const LIVE_KEY: u64 = 61;
const FIRST_KEY: u64 = 62;
const SECOND_KEY: u64 = 63;
const GATED_PAYLOAD: &[u8] = b"first";
const SECOND_PAYLOAD: &[u8] = b"second";
const SENTINEL_LIVE_KEY: u64 = 64;
const SENTINEL_PARKED_KEY: u64 = 65;
#[derive(Clone, Copy, Debug)]
enum Ending {
NormalExit,
TaskAbort,
HandlerPanic,
}
impl Ending {
const ALL: [Self; 3] = [Self::NormalExit, Self::TaskAbort, Self::HandlerPanic];
const fn child(self) -> &'static str {
match self {
Self::NormalExit => "child_normal_exit",
Self::TaskAbort => "child_task_abort",
Self::HandlerPanic => "child_handler_panic",
}
}
const fn label(self) -> &'static str {
match self {
Self::NormalExit => "normal_exit",
Self::TaskAbort => "task_abort",
Self::HandlerPanic => "handler_panic",
}
}
}
#[test]
fn the_parked_gauge_returns_to_baseline_for_every_ending() {
for ending in Ending::ALL {
let name = child_test_name(ending.child());
let output = Command::new(std::env::current_exe().expect("the test binary path is known"))
.args([
"--ignored",
"--exact",
&name,
"--test-threads=1",
"--nocapture",
])
.output()
.expect("the child test process starts");
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
output.status.success(),
"the {} ending failed in its child process:\n{stdout}\n{stderr}",
ending.label()
);
assert!(
stdout.contains(&format!("scenario={}", ending.label())),
"the {} ending did not run: the child reported no scenario marker\n{stdout}\n{stderr}",
ending.label()
);
}
}
fn child_test_name(child: &str) -> String {
let module = scenarios::MODULE;
let relative = module.split_once("::").map_or(module, |(_, rest)| rest);
format!("{relative}::{child}")
}
fn install_recorder() -> TestResult<Snapshotter> {
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
recorder
.install()
.map_err(|_| TestError::Msg("the metrics recorder is installed once per process".into()))?;
Ok(snapshotter)
}
fn parked_gauge(snapshotter: &Snapshotter) -> f64 {
snapshotter
.snapshot()
.into_vec()
.into_iter()
.filter(|(key, ..)| key.key().name() == STREAMING_BODIES_PARKED)
.filter_map(|(_, _, _, value)| match value {
DebugValue::Gauge(total) => Some(total.into_inner()),
_ => None,
})
.next_back()
.unwrap_or(0.0)
}
#[expect(
clippy::float_cmp,
reason = "the gauge carries whole message counts, which f64 represents exactly"
)]
fn gauge_reads(snapshotter: &Snapshotter, expected: f64) -> bool {
parked_gauge(snapshotter) == expected
}
async fn await_gauge(snapshotter: &Snapshotter, expected: f64) -> TestResult<()> {
let observe = async {
loop {
if gauge_reads(snapshotter, expected) {
return;
}
tokio::task::yield_now().await;
}
};
tokio::time::timeout(STEP_WAIT, observe).await.map_err(|_| {
TestError::Msg(format!(
"the parked gauge never read {expected} within {STEP_WAIT:?}; it reads {}",
parked_gauge(snapshotter)
))
})
}
#[cfg(test)]
#[path = "stream_parked_gauge_support.rs"]
mod support;
#[cfg(test)]
#[path = "stream_parked_gauge_scenarios.rs"]
mod scenarios;