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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
//! Configuration types and contexts for benchmarks.
//!
//! This module contains types used to configure benchmarks and pass context
//! to hooks and generator functions:
//!
//! - **Configuration**: [`HttpMethod`], [`RequestConfig`], [`RequestSource`]
//! - **Generator Contexts**: [`RequestContext`], [`RateContext`]
//! - **Hook Contexts**: [`BeforeRequestContext`], [`AfterRequestContext`]
//! - **Hook Control**: [`HookAction`]
//! - **Function Types**: [`RequestGenerator`], [`RateFunction`], [`BeforeRequestHook`], [`AfterRequestHook`]
//!
//! # Examples
//!
//! Using request context for dynamic URLs:
//! ```no_run
//! use httpress::{Benchmark, RequestContext, RequestConfig, HttpMethod};
//! use std::collections::HashMap;
//!
//! # #[tokio::main]
//! # async fn main() -> httpress::Result<()> {
//! Benchmark::builder()
//! .request_fn(|ctx: RequestContext| {
//! RequestConfig {
//! url: format!("http://localhost:3000/user/{}", ctx.request_number),
//! method: HttpMethod::Get,
//! headers: HashMap::new(),
//! body: None,
//! }
//! })
//! .requests(100)
//! .build()?;
//! # Ok(())
//! # }
//! ```
use HashMap;
use Arc;
use Duration;
use Bytes;
use ProgressBar;
use crateArgs;
use crateError;
use crate;
/// Defines when the benchmark should stop
/// HTTP method for requests.
///
/// Specifies the HTTP method to use when making requests to the target server.
///
/// # Examples
///
/// ```
/// use httpress::HttpMethod;
///
/// let method = HttpMethod::Post;
/// ```
/// Configuration for a single HTTP request.
///
/// Used by custom request generator functions to specify the details of each request.
/// When using [`BenchmarkBuilder::request_fn`](crate::BenchmarkBuilder::request_fn),
/// your function returns this struct to configure each individual request.
///
/// # Examples
///
/// ```
/// use httpress::{RequestConfig, HttpMethod};
/// use std::collections::HashMap;
/// use bytes::Bytes;
///
/// let config = RequestConfig {
/// url: "http://localhost:3000/api/users".to_string(),
/// method: HttpMethod::Post,
/// headers: HashMap::from([
/// ("Content-Type".to_string(), "application/json".to_string()),
/// ("Authorization".to_string(), "Bearer token123".to_string()),
/// ]),
/// body: Some(Bytes::from(r#"{"name": "John"}"#)),
/// };
/// ```
/// Context passed to request generator functions.
///
/// Provides information about the current request context, allowing you to generate
/// different requests based on worker ID and request number.
///
/// # Examples
///
/// ```no_run
/// # use httpress::{Benchmark, RequestContext, RequestConfig, HttpMethod};
/// # use std::collections::HashMap;
/// # #[tokio::main]
/// # async fn main() -> httpress::Result<()> {
/// Benchmark::builder()
/// .request_fn(|ctx: RequestContext| {
/// // Rotate through 100 different user IDs
/// let user_id = ctx.request_number % 100;
///
/// // Add worker ID to headers for debugging
/// let mut headers = HashMap::new();
/// headers.insert("X-Worker-Id".to_string(), ctx.worker_id.to_string());
///
/// RequestConfig {
/// url: format!("http://localhost:3000/user/{}", user_id),
/// method: HttpMethod::Get,
/// headers,
/// body: None,
/// }
/// })
/// .concurrency(10)
/// .requests(1000)
/// .build()?;
/// # Ok(())
/// # }
/// ```
/// Context passed to rate generator functions.
///
/// Provides runtime information about the benchmark state, allowing you to dynamically
/// adjust the request rate based on elapsed time, request counts, or success rates.
///
/// # Examples
///
/// ```no_run
/// # use httpress::{Benchmark, RateContext};
/// # use std::time::Duration;
/// # #[tokio::main]
/// # async fn main() -> httpress::Result<()> {
/// Benchmark::builder()
/// .url("http://localhost:3000")
/// .rate_fn(|ctx: RateContext| {
/// let elapsed_secs = ctx.elapsed.as_secs_f64();
///
/// // Linear ramp from 100 to 1000 req/s over 10 seconds
/// if elapsed_secs < 10.0 {
/// let progress = elapsed_secs / 10.0;
/// 100.0 + (900.0 * progress)
/// } else {
/// 1000.0
/// }
/// })
/// .duration(Duration::from_secs(30))
/// .build()?;
/// # Ok(())
/// # }
/// ```
/// Type alias for request generator functions.
///
/// A request generator is a function that creates a [`RequestConfig`] for each request
/// based on the provided [`RequestContext`]. This allows you to dynamically generate
/// requests with different URLs, methods, headers, or bodies.
///
/// # Type Signature
///
/// ```text
/// Fn(RequestContext) -> RequestConfig + Send + Sync + 'static
/// ```
///
/// # Examples
///
/// See [`BenchmarkBuilder::request_fn`](crate::BenchmarkBuilder::request_fn) for usage examples.
pub type RequestGenerator = ;
/// Type alias for rate generator functions.
///
/// A rate function dynamically determines the request rate (requests per second) based
/// on the current benchmark state provided in [`RateContext`]. This enables advanced
/// patterns like rate ramping, adaptive rate control, or scheduled rate changes.
///
/// # Type Signature
///
/// ```text
/// Fn(RateContext) -> f64 + Send + Sync + 'static
/// ```
///
/// The returned `f64` value represents the desired requests per second.
///
/// # Examples
///
/// See [`BenchmarkBuilder::rate_fn`](crate::BenchmarkBuilder::rate_fn) for usage examples.
pub type RateFunction = ;
/// Context passed to before-request hook functions.
///
/// Provides information about the benchmark state before a request is sent.
/// Before-request hooks can use this to implement rate limiting, circuit breakers,
/// or conditional request execution.
///
/// # Examples
///
/// ```no_run
/// # use httpress::{Benchmark, BeforeRequestContext, HookAction};
/// # #[tokio::main]
/// # async fn main() -> httpress::Result<()> {
/// Benchmark::builder()
/// .url("http://localhost:3000")
/// .before_request(|ctx: BeforeRequestContext| {
/// // Circuit breaker: stop sending requests if too many failures
/// let failure_rate = ctx.failed_requests as f64 / ctx.total_requests.max(1) as f64;
/// if failure_rate > 0.5 && ctx.total_requests > 100 {
/// println!("Circuit breaker triggered at {}% failures", failure_rate * 100.0);
/// HookAction::Abort
/// } else {
/// HookAction::Continue
/// }
/// })
/// .requests(1000)
/// .build()?;
/// # Ok(())
/// # }
/// ```
/// Context passed to after-request hook functions.
///
/// Provides detailed information about a completed request, including latency and status code.
/// After-request hooks can use this for custom metrics collection, retry logic based on
/// response status, or conditional behavior based on performance.
///
/// # Examples
///
/// ```no_run
/// # use httpress::{Benchmark, AfterRequestContext, HookAction};
/// # use std::sync::{Arc, Mutex};
/// # use std::time::Duration;
/// # #[tokio::main]
/// # async fn main() -> httpress::Result<()> {
/// let slow_request_count = Arc::new(Mutex::new(0));
/// let slow_count_clone = slow_request_count.clone();
///
/// Benchmark::builder()
/// .url("http://localhost:3000")
/// .after_request(move |ctx: AfterRequestContext| {
/// // Track slow requests (> 100ms)
/// if ctx.latency > Duration::from_millis(100) {
/// let mut count = slow_count_clone.lock().unwrap();
/// *count += 1;
/// }
///
/// // Retry on 5xx errors
/// if let Some(status) = ctx.status {
/// if status >= 500 {
/// return HookAction::Retry;
/// }
/// }
///
/// HookAction::Continue
/// })
/// .max_retries(3)
/// .requests(1000)
/// .build()?;
/// # Ok(())
/// # }
/// ```
/// Action returned by hook functions to control request execution.
///
/// Hook functions (both before-request and after-request) return this enum to signal
/// what action the benchmark executor should take for the current request.
///
/// # Examples
///
/// ```no_run
/// # use httpress::{Benchmark, AfterRequestContext, HookAction};
/// # #[tokio::main]
/// # async fn main() -> httpress::Result<()> {
/// Benchmark::builder()
/// .url("http://localhost:3000")
/// .after_request(|ctx: AfterRequestContext| {
/// match ctx.status {
/// Some(status) if status >= 500 => {
/// // Retry server errors
/// HookAction::Retry
/// }
/// Some(status) if status == 429 => {
/// // Abort on rate limiting
/// HookAction::Abort
/// }
/// _ => {
/// // Continue normally
/// HookAction::Continue
/// }
/// }
/// })
/// .max_retries(3)
/// .requests(1000)
/// .build()?;
/// # Ok(())
/// # }
/// ```
/// Type alias for before-request hook functions.
///
/// Before-request hooks are called before sending each HTTP request. They receive
/// [`BeforeRequestContext`] and return [`HookAction`] to control execution flow.
///
/// # Type Signature
///
/// ```text
/// Fn(BeforeRequestContext) -> HookAction + Send + Sync + 'static
/// ```
///
/// # Examples
///
/// See [`BenchmarkBuilder::before_request`](crate::BenchmarkBuilder::before_request) for usage examples.
pub type BeforeRequestHook = ;
/// Type alias for after-request hook functions.
///
/// After-request hooks are called after each HTTP request completes (or fails).
/// They receive [`AfterRequestContext`] with request latency and status code,
/// and return [`HookAction`] to control execution flow.
///
/// # Type Signature
///
/// ```text
/// Fn(AfterRequestContext) -> HookAction + Send + Sync + 'static
/// ```
///
/// # Examples
///
/// See [`BenchmarkBuilder::after_request`](crate::BenchmarkBuilder::after_request) for usage examples.
pub type AfterRequestHook = ;
/// Source of request configuration - either static or dynamically generated.
///
/// This enum represents how requests are configured in a benchmark. It is used
/// internally by the builder and executor, but is exposed publicly as part of
/// the configuration API.
///
/// You typically don't construct this directly; instead use
/// [`BenchmarkBuilder::url`](crate::BenchmarkBuilder::url) for static configuration or
/// [`BenchmarkBuilder::request_fn`](crate::BenchmarkBuilder::request_fn) for dynamic generation.
/// Benchmark configuration
/// Parse duration string like "10s", "1m", "500ms"
/// Parse header strings like "Content-Type: application/json"