use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use axum::Json;
use axum::Router;
use axum::body::Bytes;
use axum::extract::{Extension, Query};
use axum::http::header::{
CACHE_CONTROL, CONTENT_TYPE, HeaderName, HeaderValue,
};
use axum::response::IntoResponse;
use axum::routing::{MethodRouter, get, post};
use claviron_runtime::AppState;
use claviron_runtime::activity::ACTIVITY;
#[derive(serde::Deserialize, Default)]
pub struct Ask {
min: Option<u64>,
max: Option<u64>,
payload: Option<usize>,
}
impl Ask {
fn duration(&self) -> Option<Duration> {
let (low, high) = match (self.min, self.max) {
(None, None) => return None,
(Some(only), None) => (only, only),
(None, Some(high)) => (0, high),
(Some(low), Some(high)) if low > high => (high, low),
(Some(low), Some(high)) => (low, high),
};
Some(Duration::from_millis(if low == high {
low
} else {
low + spread(high - low + 1)
}))
}
}
const PAYLOAD_MAX: usize = 1024 * 1024;
fn body(bytes: usize) -> &'static str {
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
static ALPHABET: &[u8] =
b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
static SOURCE: OnceLock<Vec<u8>> = OnceLock::new();
static BODIES: OnceLock<Mutex<HashMap<usize, &'static str>>> =
OnceLock::new();
let bytes = bytes.min(PAYLOAD_MAX);
let mut bodies = BODIES
.get_or_init(Default::default)
.lock()
.expect("the body cache is never poisoned");
bodies.entry(bytes).or_insert_with(|| {
let source = SOURCE.get_or_init(|| {
(0..PAYLOAD_MAX)
.map(|_| ALPHABET[spread(ALPHABET.len() as u64) as usize])
.collect()
});
let message = std::str::from_utf8(&source[..bytes])
.expect("the alphabet is ASCII");
Box::leak(
format!(r#"{{"from":"rust","message":"{message}"}}"#)
.into_boxed_str(),
)
})
}
fn spread(bound: u64) -> u64 {
static STATE: AtomicU64 = AtomicU64::new(0x2545_f491_4f6c_dd1d);
let mut x = STATE.fetch_add(0x9e37_79b9_7f4a_7c15, Ordering::Relaxed);
x ^= x >> 30;
x = x.wrapping_mul(0xbf58_476d_1ce4_e5b9);
x ^= x >> 27;
x % bound
}
fn baseline_routes(stats: MethodRouter) -> Router {
Router::new().route("/rust", get(rust).post(rust)).route("/stats", stats)
}
pub fn routes() -> Router {
workload_routes(get(stats))
}
pub fn routes_with_state(state: &AppState) -> Router {
workload_routes(get(stats).layer(Extension(state.clone())))
}
fn workload_routes(stats: MethodRouter) -> Router {
Router::new()
.route("/bench/plain", get(plain))
.route("/bench/json", get(json))
.route("/bench/echo", post(echo))
.nest("/_bench", baseline_routes(stats))
}
async fn plain() -> &'static str {
"ok\n"
}
#[derive(serde::Serialize)]
struct JsonReply {
message: &'static str,
}
async fn json() -> Json<JsonReply> {
Json(JsonReply { message: "ok" })
}
async fn echo(request: axum::extract::Request) -> axum::response::Response {
let mut response = axum::response::Response::new(request.into_body());
response.headers_mut().insert(
CONTENT_TYPE,
HeaderValue::from_static("application/octet-stream"),
);
response
}
async fn rust(
Query(ask): Query<Ask>,
received: Bytes,
) -> axum::response::Response {
let received = received.len();
if let Some(waited) = ask.duration() {
tokio::time::sleep(waited).await;
}
let json = match ask.payload {
Some(bytes) => body(bytes),
None => r#"{"from":"rust"}"#,
};
(
[
(CONTENT_TYPE, HeaderValue::from_static("application/json")),
(CACHE_CONTROL, HeaderValue::from_static("no-store")),
(
HeaderName::from_static("x-received"),
HeaderValue::from(received as u64),
),
],
json,
)
.into_response()
}
#[derive(serde::Serialize)]
struct Stats<'a> {
in_flight: u64,
total: u64,
sessions: u64,
#[serde(flatten)]
identity: Option<StatsIdentity<'a>>,
}
#[derive(serde::Serialize)]
struct StatsIdentity<'a> {
application: &'a str,
runtime: &'static str,
fleet: &'a str,
pid: u32,
worker: Option<u8>,
}
async fn stats(state: Option<Extension<AppState>>) -> axum::response::Response {
let identity = state.as_ref().map(|Extension(state)| StatsIdentity {
application: state.name(),
runtime: "rust",
fleet: state.fleet_name(),
pid: state.pid(),
worker: state.worker_id(),
});
(
[(CACHE_CONTROL, "no-store")],
Json(Stats {
in_flight: ACTIVITY.in_flight(),
total: ACTIVITY.total(),
sessions: ACTIVITY.sessions(),
identity,
}),
)
.into_response()
}