Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 45 additions & 28 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -738,39 +738,56 @@ async fn run(mut opts: Opts) -> anyhow::Result<()> {
mode => {
let (result_tx, result_rx) = kanal::unbounded();
let data_collector = if no_tui {
// When `--no-tui` is enabled, just collect all data.

let token = tokio_util::sync::CancellationToken::new();
let result_rx_ctrl_c = result_rx.clone();
let token_ctrl_c = token.clone();
let ctrl_c = tokio::spawn(async move {
tokio::select! {
_ = tokio::signal::ctrl_c() => {
let mut all: ResultData = Default::default();
let mut buf = Vec::new();
let _ = result_rx_ctrl_c.drain_into(&mut buf);
for res in buf {
all.push(res);
// Keep receiving results during the run, even without a TUI (#910).
// Previously, collection started only after the workers finished,
// so every result accumulated in kanal's unbounded queue. Its
// VecDeque grows while holding the channel lock, blocking result
// senders and stalling request processing as the queue gets larger.
// Concurrent collection keeps the queue short and moves ResultData
// growth outside that lock. Async recv also leaves runtime workers
// free while waiting, and this task owns the results for Ctrl+C.
let collector = tokio::spawn(async move {
let result_rx = result_rx.to_async();
let mut all = ResultData::default();
let ctrl_c = tokio::signal::ctrl_c();
tokio::pin!(ctrl_c);

loop {
let receive = result_rx.recv();
tokio::pin!(receive);
tokio::select! {
result = &mut receive => {
match result {
Ok(res) => all.push(res),
Err(_) => return (all, print_config),
}
}
_ = &mut ctrl_c => {
// Kanal can deliver directly to a pending receive.
// Poll it once before draining the queue so that an
// already-delivered result is included in the report.
if let std::task::Poll::Ready(Ok(res)) =
std::future::poll_fn(|cx| {
std::task::Poll::Ready(std::future::Future::poll(
receive.as_mut(), cx,
))
}).await
{
all.push(res);
}
let mut buf = Vec::new();
let _ = result_rx.drain_into(&mut buf);
for res in buf {
all.push(res);
}
let _ = printer::print_result(print_config, start, &all, start.elapsed());
std::process::exit(libc::EXIT_SUCCESS);
}
let _ = printer::print_result(print_config, start, &all, start.elapsed());
std::process::exit(libc::EXIT_SUCCESS);
}
_ = token_ctrl_c.cancelled() => {
print_config
}

}
});

Box::pin(async move {
token.cancel();
let config = ctrl_c.await.unwrap();
let mut all = ResultData::default();
while let Ok(res) = result_rx.recv() {
all.push(res);
}
(all, config)
})
Box::pin(async move { collector.await.unwrap() })
as Pin<Box<dyn std::future::Future<Output = (ResultData, PrintConfig)>>>
} else {
// Spawn monitor future which draws realtime tui
Expand Down
105 changes: 105 additions & 0 deletions tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -930,6 +930,111 @@ async fn test_worker_threads_fast_mode() {
);
}

#[rstest]
#[case(false)]
#[case(true)]
#[tokio::test]
async fn test_result_collection_single_worker(#[case] latency_correction: bool) {
let (listener, port) = bind_port().await;
let app = Router::new().route("/", get(|| async { "ok" }));
let server = tokio::spawn(async move { axum::serve(listener, app).await });
let mut command = tokio::process::Command::new(env!("CARGO_BIN_EXE_oha"));
command.args([
"--no-tui",
"--output-format",
"json",
"--worker-threads",
"1",
"-n",
"20",
"-q",
"100",
"-c",
"1",
]);
if latency_correction {
command.arg("--latency-correction");
}
let output = tokio::time::timeout(
std::time::Duration::from_secs(10),
command
.arg(format!("http://127.0.0.1:{port}/"))
.kill_on_drop(true)
.output(),
)
.await
.expect("result collection blocked the runtime")
.unwrap();
server.abort();
assert!(output.status.success(), "{:?}", output);
let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(report["statusCodeDistribution"]["200"], 20);
}

#[cfg(unix)]
#[tokio::test]
async fn test_result_collection_ctrl_c() {
use std::sync::atomic::{AtomicUsize, Ordering};

let count = Arc::new(AtomicUsize::new(0));
let stalled = Arc::new(tokio::sync::Notify::new());
let stalled_server = stalled.clone();
let app = Router::new().route(
"/",
get(move || {
let count = count.clone();
let stalled = stalled_server.clone();
async move {
if count.fetch_add(1, Ordering::SeqCst) == 10 {
// With one connection, the previous ten responses have completed.
// Leave this request pending to check that Ctrl+C does not wait for it.
stalled.notify_one();
std::future::pending::<()>().await;
}
"ok"
}
}),
);
let (listener, port) = bind_port().await;
let server = tokio::spawn(async move { axum::serve(listener, app).await });
let child = tokio::process::Command::new(env!("CARGO_BIN_EXE_oha"))
.args([
"--no-tui",
"--output-format",
"json",
"--worker-threads",
"1",
"-n",
"1000",
"-q",
"100",
"-c",
"1",
])
.arg(format!("http://127.0.0.1:{port}/"))
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.kill_on_drop(true)
.spawn()
.unwrap();
tokio::time::timeout(std::time::Duration::from_secs(10), stalled.notified())
.await
.expect("requests did not complete");
// SAFETY: the child is still owned and has not been reaped.
assert_eq!(
unsafe { libc::kill(child.id().unwrap() as libc::pid_t, libc::SIGINT) },
0
);
let output = tokio::time::timeout(std::time::Duration::from_secs(10), child.wait_with_output())
.await
.expect("Ctrl+C did not stop oha")
.unwrap();
server.abort();
assert!(output.status.success(), "{:?}", output);
let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(report["statusCodeDistribution"]["200"], 10);
}

#[tokio::test]
async fn test_http_versions() {
assert_eq!(get_req("/", &[]).await.version(), http::Version::HTTP_11);
Expand Down
Loading