rustress 0.1.1

High-performance load testing engine with an interactive terminal dashboard. Open-loop (RPS) and closed-loop (virtual users) load models with live p50/p90/p95/p99 latency telemetry.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
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,
};

/// Load generation mode.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Mode {
    /// Open loop — target RPS with time-based scheduling.
    #[default]
    Rps,
    /// Closed loop — fixed number of virtual users looping.
    Users,
}

/// Load test configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    /// Target URL.
    pub url: String,

    /// HTTP method (GET, POST, etc.).
    #[serde(default = "default_method")]
    pub method: String,

    /// Request body (plain text or @file.json to read from file).
    pub body: Option<String>,

    /// HTTP headers.
    #[serde(default)]
    pub headers: IndexMap<String, String>,

    /// Target requests per second (open loop mode).
    #[serde(default = "default_target_rps")]
    pub target_rps: u32,

    /// Steady state duration in seconds.
    #[serde(default = "default_duration")]
    pub steady_dur_secs: u64,

    /// Ramp-up duration in seconds.
    #[serde(default)]
    pub ramp_up_secs: u64,

    /// Ramp-down duration in seconds.
    #[serde(default)]
    pub ramp_down_secs: u64,

    /// Request timeout in seconds.
    #[serde(default = "default_timeout")]
    pub timeout_secs: u64,

    /// Load generation mode.
    #[serde(default)]
    pub mode: Mode,

    /// Number of virtual users (closed loop mode).
    #[serde(default = "default_num_users")]
    pub num_users: u32,

    /// Think time between requests in milliseconds (closed loop mode).
    #[serde(default)]
    pub think_time_ms: u64,

    /// Shell command to execute (script mode).
    pub command: Option<String>,

    /// Output file prefix for reports.
    pub out_prefix: Option<String>,

    /// Max concurrent **in-flight** requests. Bounds work, not memory: it is
    /// the number of requests executing at once. **Open-loop (RPS) mode only.**
    ///
    /// Closed-loop (Users) mode is bounded by `num_users` alone, by design --
    /// a virtual user is the unit of concurrency there, and adding a second
    /// independent control would make the mode's throughput unexplainable.
    #[serde(default = "default_max_concurrency")]
    pub max_concurrency: u32,

    /// Max **idle** connections retained per host after a request finishes.
    ///
    /// A *different* bound from `max_concurrency`: that one limits requests
    /// executing, this one limits sockets retained afterwards. Retained sockets
    /// are not free -- each keeps a hyper read buffer sized for the largest
    /// body it has carried -- but measurement shows this is a secondary term.
    /// The dominant one is `max_concurrency`; see its docs for the numbers.
    ///
    /// Raising this reduces handshakes and measures connection reuse more
    /// faithfully; lowering it caps memory. It is a measurement trade-off, not
    /// a free win.
    #[serde(default = "default_pool_max_idle_per_host")]
    pub pool_max_idle_per_host: u32,

    /// How long an unused connection is kept warm, in seconds.
    #[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 {
    /// Total test duration.
    pub fn total_duration(&self) -> Duration {
        Duration::from_secs(self.ramp_up_secs + self.steady_dur_secs + self.ramp_down_secs)
    }

    /// Validate configuration, rejecting values that would deadlock the engine
    /// or exhaust host resources.
    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());
        }

        // A zero-permit semaphore deadlocks the engine: every request blocks
        // forever and the run never terminates.
        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)
        }
    }
}

/// Whether a URL carries an absolute HTTP scheme.
///
/// Kept dependency-free so `core` stays a leaf module; full parsing is left to
/// the HTTP client at request time.
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());
    }
}