use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use std::time::Duration;
use crate::core::constants::{
DEFAULT_DURATION_SECS, DEFAULT_MAX_CONCURRENCY, DEFAULT_METHOD, DEFAULT_NUM_USERS,
DEFAULT_POOL_IDLE_TIMEOUT_SECS, DEFAULT_POOL_MAX_IDLE_PER_HOST, DEFAULT_TARGET_RPS,
DEFAULT_TIMEOUT_SECS, MAX_ALLOWED_CONCURRENCY, MAX_ALLOWED_RPS, MAX_ALLOWED_USERS,
MAX_IDLE_CONNS_PER_HOST, MAX_POOL_IDLE_TIMEOUT_SECS, MIN_ALLOWED_CONCURRENCY,
};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Mode {
#[default]
Rps,
Users,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
pub url: String,
#[serde(default = "default_method")]
pub method: String,
pub body: Option<String>,
#[serde(default)]
pub headers: IndexMap<String, String>,
#[serde(default = "default_target_rps")]
pub target_rps: u32,
#[serde(default = "default_duration")]
pub steady_dur_secs: u64,
#[serde(default)]
pub ramp_up_secs: u64,
#[serde(default)]
pub ramp_down_secs: u64,
#[serde(default = "default_timeout")]
pub timeout_secs: u64,
#[serde(default)]
pub mode: Mode,
#[serde(default = "default_num_users")]
pub num_users: u32,
#[serde(default)]
pub think_time_ms: u64,
pub command: Option<String>,
pub out_prefix: Option<String>,
#[serde(default = "default_max_concurrency")]
pub max_concurrency: u32,
#[serde(default = "default_pool_max_idle_per_host")]
pub pool_max_idle_per_host: u32,
#[serde(default = "default_pool_idle_timeout")]
pub pool_idle_timeout_secs: u64,
}
impl Default for Config {
fn default() -> Self {
Self {
url: String::new(),
method: default_method(),
body: None,
headers: IndexMap::new(),
target_rps: default_target_rps(),
steady_dur_secs: default_duration(),
ramp_up_secs: 0,
ramp_down_secs: 0,
timeout_secs: default_timeout(),
mode: Mode::default(),
num_users: default_num_users(),
think_time_ms: 0,
command: None,
out_prefix: None,
max_concurrency: default_max_concurrency(),
pool_max_idle_per_host: default_pool_max_idle_per_host(),
pool_idle_timeout_secs: default_pool_idle_timeout(),
}
}
}
impl Config {
pub fn total_duration(&self) -> Duration {
Duration::from_secs(self.ramp_up_secs + self.steady_dur_secs + self.ramp_down_secs)
}
pub fn validate(&self) -> Result<(), Vec<String>> {
let mut errors = Vec::new();
if self.mode == Mode::Rps && self.target_rps == 0 {
errors.push("target_rps must be greater than 0 in RPS mode".into());
}
if self.target_rps > MAX_ALLOWED_RPS {
errors.push(format!(
"target_rps must be at most {MAX_ALLOWED_RPS} (got {})",
self.target_rps
));
}
if self.mode == Mode::Users && self.num_users == 0 {
errors.push("num_users must be greater than 0 in Users mode".into());
}
if self.num_users > MAX_ALLOWED_USERS {
errors.push(format!(
"num_users must be at most {MAX_ALLOWED_USERS} (got {})",
self.num_users
));
}
if self.steady_dur_secs == 0 {
errors.push("steady_dur_secs must be greater than 0".into());
}
if self.max_concurrency < MIN_ALLOWED_CONCURRENCY {
errors.push(format!(
"max_concurrency must be at least {MIN_ALLOWED_CONCURRENCY} (got {})",
self.max_concurrency
));
}
if self.max_concurrency > MAX_ALLOWED_CONCURRENCY {
errors.push(format!(
"max_concurrency must be at most {MAX_ALLOWED_CONCURRENCY} (got {})",
self.max_concurrency
));
}
if self.pool_max_idle_per_host == 0 {
errors.push("pool_max_idle_per_host must be greater than 0".into());
}
if self.pool_max_idle_per_host > MAX_IDLE_CONNS_PER_HOST as u32 {
errors.push(format!(
"pool_max_idle_per_host must be at most {MAX_IDLE_CONNS_PER_HOST} (got {})",
self.pool_max_idle_per_host
));
}
if self.pool_idle_timeout_secs > MAX_POOL_IDLE_TIMEOUT_SECS {
errors.push(format!(
"pool_idle_timeout_secs must be at most {MAX_POOL_IDLE_TIMEOUT_SECS} (got {})",
self.pool_idle_timeout_secs
));
}
if self.timeout_secs == 0 {
errors.push("timeout_secs must be greater than 0".into());
}
if self.url.is_empty() && self.command.is_none() {
errors.push("either url or command must be specified".into());
} else if !self.url.is_empty() && !has_http_scheme(&self.url) {
errors.push(format!(
"url must be absolute and start with http:// or https:// (got {})",
self.url
));
}
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
}
fn has_http_scheme(url: &str) -> bool {
let lowered = url.to_ascii_lowercase();
lowered.starts_with("http://") || lowered.starts_with("https://")
}
fn default_method() -> String {
DEFAULT_METHOD.to_string()
}
fn default_target_rps() -> u32 {
DEFAULT_TARGET_RPS
}
fn default_duration() -> u64 {
DEFAULT_DURATION_SECS
}
fn default_timeout() -> u64 {
DEFAULT_TIMEOUT_SECS
}
fn default_num_users() -> u32 {
DEFAULT_NUM_USERS
}
fn default_max_concurrency() -> u32 {
DEFAULT_MAX_CONCURRENCY
}
fn default_pool_max_idle_per_host() -> u32 {
DEFAULT_POOL_MAX_IDLE_PER_HOST as u32
}
fn default_pool_idle_timeout() -> u64 {
DEFAULT_POOL_IDLE_TIMEOUT_SECS
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default_config() {
let cfg = Config::default();
assert_eq!(cfg.method, "GET");
assert_eq!(cfg.target_rps, 100);
assert_eq!(cfg.steady_dur_secs, 30);
assert_eq!(cfg.mode, Mode::Rps);
}
#[test]
fn test_total_duration() {
let cfg = Config {
ramp_up_secs: 5,
steady_dur_secs: 30,
ramp_down_secs: 5,
..Default::default()
};
assert_eq!(cfg.total_duration(), Duration::from_secs(40));
}
#[test]
fn test_validate_empty_url_and_command() {
let cfg = Config::default();
assert!(cfg.validate().is_err());
}
#[test]
fn test_validate_rps_zero() {
let cfg = Config {
url: "http://localhost".into(),
target_rps: 0,
mode: Mode::Rps,
..Default::default()
};
assert!(cfg.validate().is_err());
}
#[test]
fn test_validate_users_zero() {
let cfg = Config {
command: Some("echo test".into()),
num_users: 0,
mode: Mode::Users,
..Default::default()
};
assert!(cfg.validate().is_err());
}
#[test]
fn test_validate_ok() {
let cfg = Config {
url: "http://localhost:8080".into(),
target_rps: 50,
steady_dur_secs: 10,
mode: Mode::Rps,
..Default::default()
};
assert!(cfg.validate().is_ok());
}
#[test]
fn a_script_run_needs_no_url() {
let cfg = Config {
url: String::new(),
command: Some("echo hello".into()),
steady_dur_secs: 1,
..Default::default()
};
assert!(
cfg.validate().is_ok(),
"script mode has no target url to validate: {:?}",
cfg.validate()
);
}
#[test]
fn a_script_run_still_validates_every_other_bound() {
let cfg = Config {
url: String::new(),
command: Some("echo hello".into()),
steady_dur_secs: 1,
max_concurrency: 0,
..Default::default()
};
let errors = cfg
.validate()
.expect_err("a zero-permit semaphore must be rejected");
assert_eq!(
errors.len(),
1,
"expected exactly one violation: {errors:?}"
);
assert!(errors[0].contains("max_concurrency"), "{errors:?}");
}
#[test]
fn the_scheme_check_is_case_insensitive() {
let cfg = Config {
url: "HTTP://localhost:8080/x".into(),
steady_dur_secs: 1,
..Default::default()
};
assert!(
cfg.validate().is_ok(),
"a scheme is case-insensitive per RFC 3986: {:?}",
cfg.validate()
);
}
#[test]
fn a_non_http_scheme_is_rejected() {
for url in ["ftp://host/x", "file:///etc/passwd", "//host/x"] {
let cfg = Config {
url: url.into(),
steady_dur_secs: 1,
..Default::default()
};
assert!(
cfg.validate().is_err(),
"{url} is not an absolute HTTP url and must be rejected at construction"
);
}
}
#[test]
fn every_documented_maximum_is_itself_accepted() {
let cfg = Config {
url: "http://localhost:8080".into(),
target_rps: MAX_ALLOWED_RPS,
num_users: MAX_ALLOWED_USERS,
max_concurrency: MAX_ALLOWED_CONCURRENCY,
steady_dur_secs: 1,
timeout_secs: 1,
..Default::default()
};
assert!(
cfg.validate().is_ok(),
"a bound that rejects its own maximum is off by one: {:?}",
cfg.validate()
);
}
#[test]
fn one_past_each_documented_maximum_is_rejected() {
let cases: [(&str, Config); 3] = [
(
"target_rps",
Config {
url: "http://localhost:8080".into(),
target_rps: MAX_ALLOWED_RPS + 1,
steady_dur_secs: 1,
..Default::default()
},
),
(
"num_users",
Config {
url: "http://localhost:8080".into(),
num_users: MAX_ALLOWED_USERS + 1,
steady_dur_secs: 1,
..Default::default()
},
),
(
"max_concurrency",
Config {
url: "http://localhost:8080".into(),
max_concurrency: MAX_ALLOWED_CONCURRENCY + 1,
steady_dur_secs: 1,
..Default::default()
},
),
];
for (field, cfg) in cases {
let errors = cfg
.validate()
.err()
.unwrap_or_else(|| panic!("{field} one past its maximum must be rejected"));
assert!(
errors.iter().any(|e| e.contains(field)),
"the rejection must name {field}: {errors:?}"
);
}
}
#[test]
fn the_minimum_concurrency_is_accepted_and_one_below_it_is_not() {
let at_min = Config {
url: "http://localhost:8080".into(),
max_concurrency: MIN_ALLOWED_CONCURRENCY,
steady_dur_secs: 1,
..Default::default()
};
assert!(at_min.validate().is_ok());
let below = Config {
max_concurrency: MIN_ALLOWED_CONCURRENCY - 1,
..at_min
};
assert!(below.validate().is_err());
}
}