#![allow(dead_code)]
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use axum::Router;
use tokio::net::TcpListener;
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use rustress::core::config::Config;
use rustress::core::constants::STATS_CHANNEL_CAPACITY;
use rustress::core::result::ExperimentResult;
use rustress::core::snapshot::StatsSnapshot;
use rustress::runner::LoadEngine;
use rustress::runner::stats::RunStats;
pub struct TestServer {
addr: SocketAddr,
handle: JoinHandle<()>,
}
impl TestServer {
pub fn addr(&self) -> SocketAddr {
self.addr
}
pub fn url(&self, path: &str) -> String {
format!("http://{}{}", self.addr, path)
}
}
impl Drop for TestServer {
fn drop(&mut self) {
self.handle.abort();
}
}
pub async fn serve(router: Router) -> TestServer {
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("bind ephemeral port");
let addr = listener.local_addr().expect("read bound address");
let handle = tokio::spawn(async move {
let _ = axum::serve(listener, router).await;
});
TestServer { addr, handle }
}
pub async fn dummy_server() -> TestServer {
serve(rustress::dummy::server::DummyServer::router()).await
}
pub struct Harness {
engine: LoadEngine,
pub updates: mpsc::Receiver<StatsSnapshot>,
cancel: CancellationToken,
}
impl Harness {
pub fn new(cfg: Config) -> anyhow::Result<Self> {
let (tx, updates) = mpsc::channel(STATS_CHANNEL_CAPACITY);
let engine = LoadEngine::new(cfg, tx)?;
Ok(Self {
engine,
updates,
cancel: CancellationToken::new(),
})
}
pub fn cancel_token(&self) -> CancellationToken {
self.cancel.clone()
}
pub async fn run(&self) {
self.engine.run(self.cancel.clone()).await;
}
pub async fn run_cancelling_after(&self, after: Duration) {
let cancel = self.cancel.clone();
tokio::spawn(async move {
tokio::time::sleep(after).await;
cancel.cancel();
});
self.engine.run(self.cancel.clone()).await;
}
pub fn stats(&self) -> &Arc<RunStats> {
self.engine.stats()
}
pub fn snapshot(&self) -> StatsSnapshot {
self.engine.stats().snapshot()
}
pub fn results(&self) -> Vec<ExperimentResult> {
self.engine.stats().get_results()
}
}
pub fn cfg_for(url: &str) -> Config {
Config {
url: url.to_string(),
target_rps: 20,
steady_dur_secs: 1,
timeout_secs: 5,
max_concurrency: 32,
..Default::default()
}
}
pub fn rss_bytes() -> Option<u64> {
let status = std::fs::read_to_string("/proc/self/status").ok()?;
for line in status.lines() {
if let Some(rest) = line.strip_prefix("VmRSS:") {
let kb: u64 = rest.split_whitespace().next()?.parse().ok()?;
return Some(kb * 1024);
}
}
None
}
pub fn assert_grew_by_at_least(label: &str, before: u64, after: u64, floor: u64) {
assert!(
after.saturating_sub(before) >= floor,
"{label}: resident memory grew by only {} bytes, but this probe must be \
able to observe at least {floor} bytes of real growth. A probe that \
cannot see a known allocation cannot certify an allocation bound.",
after.saturating_sub(before)
);
}