iskra 0.6.1

A safe, modern, Rust-native data transfer tool.
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
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
592
593
594
use std::collections::HashMap;
use std::sync::Arc;
use crate::client::util::{color_green, color_red, color_yellow};
use std::time::Duration;
use std::io::BufRead;
use crate::cli::cli_parser::{validate_url, validate_method, parse_header, parse_query};
use reqwest::Client;
use futures::future::join_all;
use tokio::sync::Semaphore;
use std::sync::Arc as StdArcSync;

/// Main burst engine
use crate::client::cache::Cache;
use std::sync::Arc as StdArc;
pub struct BurstEngine {
    pub requests: Vec<Arc<BurstRequest>>,
    pub options: BurstOptions,
    pub cache: Option<StdArc<Cache>>,
    // Cache stats for reporting
    pub cache_hits: StdArcSync<std::sync::atomic::AtomicUsize>,
    pub cache_misses: StdArcSync<std::sync::atomic::AtomicUsize>,
}
/// Represents a single burst request template.
#[derive(Debug, Clone)]
pub struct BurstRequest {
    pub url: String,
    pub method: String,
    pub headers: HashMap<String, String>,
    pub query: HashMap<String, String>,
    pub body: Option<Vec<u8>>,
    pub output: Option<String>,
}

impl BurstRequest {
    /// Parse a BurstRequest from a line of text (CSV/TSV/space-delimited or JSON in future)
    pub fn parse_from_line(line: &str) -> Result<Self, String> {
        // Format: METHOD URL [header:key:value ...] [query:key=value ...] [body:...] [output:filename]
        let mut method = None;
        let mut url = None;
        let mut headers = HashMap::new();
        let mut query = HashMap::new();
        let mut body = None;
        let mut output = None;
        let tokens: Vec<&str> = line.split_whitespace().collect();
        for token in tokens {
            if method.is_none() {
                validate_method(token).map_err(|e| format!("Invalid method: {e}"))?;
                method = Some(token.to_string());
                continue;
            }
            if url.is_none() {
                validate_url(token).map_err(|e| format!("Invalid URL: {e}"))?;
                url = Some(token.to_string());
                continue;
            }
            if let Some(h) = token.strip_prefix("header:") {
                let (k, v) = parse_header(h).map_err(|e| format!("Invalid header: {e}"))?;
                headers.insert(k, v);
            } else if let Some(q) = token.strip_prefix("query:") {
                let (k, v) = parse_query(q).map_err(|e| format!("Invalid query: {e}"))?;
                query.insert(k, v);
            } else if let Some(b) = token.strip_prefix("body:") {
                body = Some(b.as_bytes().to_vec());
            } else if let Some(o) = token.strip_prefix("output:") {
                output = Some(o.to_string());
            }
        }
        let method = method.ok_or("Missing HTTP method")?;
        let url = url.ok_or("Missing URL")?;
        Ok(BurstRequest { url, method, headers, query, body, output })
    }
    /// Parse a batch of BurstRequests from a file or stdin
    pub fn parse_batch<R: BufRead>(reader: R) -> Result<Vec<BurstRequest>, String> {
        let mut requests = Vec::new();
        for (i, line) in reader.lines().enumerate() {
            let line = line.map_err(|e| format!("IO error on line {i}: {e}"))?;
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') { continue; }
            let req = BurstRequest::parse_from_line(line)
                .map_err(|e| format!("Parse error on line {}: {}", i + 1, e))?;
            requests.push(req);
        }
        Ok(requests)
    }
}
/// Options for a burst operation.
pub struct BurstOptions {
    pub concurrency: usize, // Number of parallel requests
    pub throttle_per_sec: Option<usize>, // Optional rate limit
    pub retries: usize, // Number of retries per request
    pub backoff: Option<Duration>, // Optional backoff between retries
    pub summary: bool, // Show summary at end
    pub output_dir: Option<String>, // Output directory for responses
    pub timeout: Option<Duration>, // Per-request timeout (optional for backward compatibility)
}
/// Result of a single burst request.
pub struct BurstResult {
    pub request: Arc<BurstRequest>,
    pub status: Option<u16>,
    pub success: bool,
    pub duration: Duration,
    pub error: Option<String>,
    pub output_path: Option<String>,
}

impl BurstEngine {
    /// Create a new burst engine
    /// Backward compatible: if options.timeout is None, use 30s default.
    /// Use this for most cases.
    pub fn new(requests: Vec<BurstRequest>, mut options: BurstOptions) -> Self {
        if options.timeout.is_none() {
            options.timeout = Some(Duration::from_secs(30));
        }
        let requests = requests.into_iter().map(Arc::new).collect();
        BurstEngine {
            requests,
            options,
            cache: None,
            cache_hits: StdArcSync::new(std::sync::atomic::AtomicUsize::new(0)),
            cache_misses: StdArcSync::new(std::sync::atomic::AtomicUsize::new(0)),
        }
    }

    pub fn new_with_cache(requests: Vec<BurstRequest>, mut options: BurstOptions, cache: Option<StdArc<Cache>>) -> Self {
        if options.timeout.is_none() {
            options.timeout = Some(Duration::from_secs(30));
        }
        let requests = requests.into_iter().map(Arc::new).collect();
        BurstEngine {
            requests,
            options,
            cache,
            cache_hits: StdArcSync::new(std::sync::atomic::AtomicUsize::new(0)),
            cache_misses: StdArcSync::new(std::sync::atomic::AtomicUsize::new(0)),
        }
    }
    /// Convenience constructor for custom timeout (used by CLI)
    pub fn new_with_timeout(requests: Vec<BurstRequest>, mut options: BurstOptions, timeout: Duration) -> Self {
        options.timeout = Some(timeout);
        let requests = requests.into_iter().map(Arc::new).collect();
        BurstEngine {
            requests,
            options,
            cache: None,
            cache_hits: StdArcSync::new(std::sync::atomic::AtomicUsize::new(0)),
            cache_misses: StdArcSync::new(std::sync::atomic::AtomicUsize::new(0)),
        }
    }
    /// Run all burst requests (parallel, batched, or templated)
    pub async fn run(&self) -> Vec<BurstResult> {
        use tokio::fs;
        let client = Client::builder()
            .timeout(self.options.timeout.unwrap_or(Duration::from_secs(30)))
            .build()
            .expect("Failed to build reqwest client with timeout");
        let output_dir = self.options.output_dir.clone();
        let concurrency = self.options.concurrency;
        let throttle = self.options.throttle_per_sec.unwrap_or(0);
        let retries = self.options.retries;
        let backoff = self.options.backoff.unwrap_or(Duration::from_millis(0));
        let verbose = true;
        let quiet = false;
        let requests = self.requests.clone();
        let cache = self.cache.clone();
        let semaphore = StdArcSync::new(Semaphore::new(concurrency.max(1)));
        // For cache stats
        let cache_hits = self.cache_hits.clone();
        let cache_misses = self.cache_misses.clone();
        let mut handles = Vec::new();
        for (i, req) in requests.iter().enumerate() {
            let req = Arc::clone(req);
            let client = client.clone();
            let output_dir = output_dir.clone();
            let cache = cache.clone();
            let semaphore = semaphore.clone();
            let cache_hits = cache_hits.clone();
            let cache_misses = cache_misses.clone();
            let handle = tokio::spawn(async move {
                let _permit = semaphore.acquire().await.unwrap();
                if throttle > 0 && i > 0 {
                    let delay = Duration::from_millis(1000 / throttle as u64);
                    tokio::time::sleep(delay).await;
                }
                let mut attempt = 0;
                let start = std::time::Instant::now();
                loop {
                    // Only cache GET requests
                    let use_cache = cache.is_some() && req.method.to_uppercase() == "GET";
                    let cache_key = format!("{}:{}::", req.method, req.url);
                    if use_cache {
                        if let Some(ref cache) = cache {
                            if let Some((_data, _meta)) = cache.get(&cache_key, None) {
                                cache_hits.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                                let duration = start.elapsed();
                                if verbose && !quiet {
                                    println!("[Burst][{}][cache HIT] {} {} time: {:.2?}", i, req.method, req.url, duration);
                                }
                                return BurstResult {
                                    request: req,
                                    status: Some(200),
                                    success: true,
                                    duration,
                                    error: None,
                                    output_path: None,
                                };
                            } else {
                                cache_misses.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                            }
                        }
                    }
                    let mut builder = client.request(
                        reqwest::Method::from_bytes(req.method.as_bytes()).unwrap_or(reqwest::Method::GET),
                        &req.url,
                    );
                    for (k, v) in &req.headers {
                        builder = builder.header(k, v);
                    }
                    if !req.query.is_empty() {
                        builder = builder.query(&req.query);
                    }
                    if let Some(body) = &req.body {
                        builder = builder.body(body.clone());
                    }
                    match builder.send().await {
                        Ok(resp) => {
                            let status = resp.status().as_u16();
                            let success = resp.status().is_success();
                            let duration = start.elapsed();
                            let body = resp.bytes().await.ok();
                            // Store in cache if GET and success
                            if use_cache && success {
                                if let (Some(ref cache), Some(ref b)) = (cache.as_ref(), body.as_ref()) {
                                    cache.set(&cache_key, None, b, &Default::default());
                                }
                            }
                            let (output_path, error) = if success {
                                if let Some(ref out) = req.output {
                                    // Sanitize output file name
                                    let sanitized = out.replace("..", "_").replace('/', "_").replace('\\', "_");
                                    let sanitized = if sanitized.len() > 128 { sanitized[..128].to_string() } else { sanitized };
                                    let path = if let Some(ref dir) = output_dir {
                                        format!("{}/{}", dir, sanitized)
                                    } else {
                                        sanitized
                                    };
                                    if path == "/" || path == "C:/" || path == "C:\\" || path == "\\" {
                                        return BurstResult {
                                            request: req,
                                            status: None,
                                            success: false,
                                            duration,
                                            error: Some("Refusing to overwrite system file!".to_string()),
                                            output_path: None,
                                        };
                                    }
                                    if let Some(ref b) = body {
                                        if fs::metadata(&path).await.is_ok() {
                                            eprintln!("[Burst][WARN] Output file '{}' already exists, will overwrite.", path);
                                        }
                                        match fs::write(&path, b).await {
                                            Ok(_) => (Some(path), None),
                                            Err(e) => (None, Some(format!("Failed to write output: {}", e))),
                                        }
                                    } else {
                                        (None, None)
                                    }
                                } else if let Some(ref dir) = output_dir {
                                    let path = format!("{}/response_{}.bin", dir, i);
                                    if let Some(ref b) = body {
                                        if fs::metadata(&path).await.is_ok() {
                                            eprintln!("[Burst][WARN] Output file '{}' already exists, will overwrite.", path);
                                        }
                                        match fs::write(&path, b).await {
                                            Ok(_) => (Some(path), None),
                                            Err(e) => (None, Some(format!("Failed to write output: {}", e))),
                                        }
                                    } else {
                                        (None, None)
                                    }
                                } else if let Some(ref b) = body {
                                    if verbose && !quiet {
                                        if let Ok(s) = std::str::from_utf8(b) {
                                            println!("[Burst][{}] {} {}\n{}", i, req.method, req.url, s);
                                        } else {
                                            println!("[Burst][{}] {} {} (binary {} bytes)", i, req.method, req.url, b.len());
                                        }
                                    }
                                    (None, None)
                                } else {
                                    (None, None)
                                }
                            } else {
                                (None, Some(format!("HTTP error: status {}", status)))
                            };
                            return BurstResult {
                                request: req,
                                status: Some(status),
                                success,
                                duration,
                                error,
                                output_path,
                            };
                        }
                        Err(e) => {
                            attempt += 1;
                            if attempt > retries {
                                if verbose && !quiet {
                                    println!("[Burst][{}] {} {} -> ERROR: {}", i, req.method, req.url, e);
                                }
                                return BurstResult {
                                    request: req,
                                    status: None,
                                    success: false,
                                    duration: start.elapsed(),
                                    error: Some(e.to_string()),
                                    output_path: None,
                                };
                            }
                            let jitter = rand::random::<u64>() % 100;
                            let sleep = backoff * attempt as u32 + Duration::from_millis(jitter);
                            tokio::time::sleep(sleep).await;
                        }
                    }
                }
            });
            handles.push(handle);
        }
        let results = join_all(handles).await;
        let results: Vec<BurstResult> = results.into_iter().filter_map(|r| r.ok()).collect();
        if self.options.summary {
            let total = results.len();
            let successes = results.iter().filter(|r| r.success).count();
            let failures = total - successes;
            let total_time: Duration = results.iter().map(|r| r.duration).sum();
            let avg_time = if total > 0 { total_time / (total as u32) } else { Duration::from_secs(0) };
            let hits = self.cache_hits.load(std::sync::atomic::Ordering::Relaxed);
            let misses = self.cache_misses.load(std::sync::atomic::Ordering::Relaxed);
            println!("\n--- Burst Summary ---");
            println!("Total: {} | Success: {} | Fail: {}", total, color_green(&successes.to_string()), color_red(&failures.to_string()));
            println!("Avg Time: {:.2?} | Total Time: {:.2?}", avg_time, total_time);
            if self.cache.is_some() {
                println!("Cache: {} hits, {} misses", color_green(&hits.to_string()), color_red(&misses.to_string()));
            }
            for (i, r) in results.iter().enumerate() {
                let is_timeout = r.error.as_ref().map_or(false, |e| {
                    let e = e.to_lowercase();
                    e.contains("timeout") || e.contains("timed out")
                });
                let (status_str, color_fn): (&str, Box<dyn Fn(&str) -> String>) = if r.success {
                    ("OK", Box::new(color_green))
                } else if is_timeout {
                    ("TIMEOUT", Box::new(color_yellow))
                } else {
                    ("FAIL", Box::new(color_red))
                };
                let status_colored = color_fn(status_str);
                println!("[{}] {} {} -> {}{}{}", i, r.request.method, r.request.url, status_colored, r.status.map(|s| format!(" [{}]", s)).unwrap_or_default(), r.output_path.as_ref().map(|p| format!(" -> {}", p)).unwrap_or_default());
                if let Some(ref e) = r.error {
                    let err_colored = if is_timeout {
                        color_yellow(&format!("TIMEOUT: {}", e))
                    } else {
                        color_red(e)
                    };
                    println!("    Error: {}", err_colored);
                }
            }
            println!("---------------------\n");
        }
        results
    }
}

// Burst: Launch multiple HTTP requests in parallel, batch, or templated form.
impl BurstEngine {
    /// Run all burst requests with verbosity/quiet control
    pub async fn run_with_verbosity(&self, verbose: bool, quiet: bool) -> Vec<BurstResult> {
        use tokio::fs;
        let client = reqwest::Client::builder()
            .timeout(self.options.timeout.unwrap_or(std::time::Duration::from_secs(30)))
            .build()
            .expect("Failed to build reqwest client with timeout");
        let throttle = self.options.throttle_per_sec.unwrap_or(0);
        let retries = self.options.retries;
        let backoff = self.options.backoff.unwrap_or(std::time::Duration::from_millis(0));
        let output_dir = self.options.output_dir.clone();
        // Safety: Prevent dangerous output_dir values
        if let Some(ref dir) = output_dir {
            if dir == "/" || dir == "C:/" || dir == "C:\\" || dir == "\\" {
                panic!("Refusing to use system root as output directory!");
            }
            if let Err(e) = fs::create_dir_all(dir).await {
                eprintln!("[Burst] Failed to create output directory '{}': {}", dir, e);
            }
        }
        // Bound concurrency to a safe maximum
        if self.options.concurrency > 1000 {
            panic!("Concurrency too high ({} > 1000). Refusing to run.", self.options.concurrency);
        }
        let concurrency = self.options.concurrency.max(1);
        let semaphore = StdArcSync::new(Semaphore::new(concurrency));
        let wall_start = std::time::Instant::now();
        let mut handles = Vec::new();
        for (i, req) in self.requests.iter().enumerate() {
            let req = std::sync::Arc::clone(req);
            let client = client.clone();
            let output_dir = output_dir.clone();
            let semaphore = semaphore.clone();
            let handle = tokio::spawn(async move {
                let _permit = semaphore.acquire().await.unwrap();
                if throttle > 0 && i > 0 {
                    let delay = std::time::Duration::from_millis(1000 / throttle as u64);
                    tokio::time::sleep(delay).await;
                }
                let mut attempt = 0;
                let start = std::time::Instant::now();
                loop {
                    let mut builder = client.request(
                        reqwest::Method::from_bytes(req.method.as_bytes()).unwrap_or(reqwest::Method::GET),
                        &req.url,
                    );
                    for (k, v) in &req.headers {
                        builder = builder.header(k, v);
                    }
                    if !req.query.is_empty() {
                        builder = builder.query(&req.query);
                    }
                    if let Some(body) = &req.body {
                        builder = builder.body(body.clone());
                    }
                    match builder.send().await {
                        Ok(resp) => {
                            let status = resp.status().as_u16();
                            let success = resp.status().is_success();
                            let duration = start.elapsed();
                            let body = resp.bytes().await.ok();
                            let (output_path, error) = if success {
                                // Write to file if output or output_dir is set, else stdout
                                if let Some(ref out) = req.output {
                                    // Sanitize output file name
                                    let sanitized = out.replace("..", "_").replace('/', "_").replace('\\', "_");
                                    let sanitized = if sanitized.len() > 128 { sanitized[..128].to_string() } else { sanitized };
                                    let path = if let Some(ref dir) = output_dir {
                                        format!("{}/{}", dir, sanitized)
                                    } else {
                                        sanitized
                                    };
                                    // Prevent accidental overwrite of system files
                                    if path == "/" || path == "C:/" || path == "C:\\" || path == "\\" {
                                        return BurstResult {
                                            request: req,
                                            status: None,
                                            success: false,
                                            duration,
                                            error: Some("Refusing to overwrite system file!".to_string()),
                                            output_path: None,
                                        };
                                    }
                                    if let Some(ref b) = body {
                                        // Check if file exists, warn if so
                                        if fs::metadata(&path).await.is_ok() {
                                            eprintln!("[Burst][WARN] Output file '{}' already exists, will overwrite.", path);
                                        }
                                        match fs::write(&path, b).await {
                                            Ok(_) => (Some(path), None),
                                            Err(e) => (None, Some(format!("Failed to write output: {}", e))),
                                        }
                                    } else {
                                        (None, None)
                                    }
                                } else if let Some(ref dir) = output_dir {
                                    // Use a default filename based on index
                                    let path = format!("{}/response_{}.bin", dir, i);
                                    if let Some(ref b) = body {
                                        if fs::metadata(&path).await.is_ok() {
                                            eprintln!("[Burst][WARN] Output file '{}' already exists, will overwrite.", path);
                                        }
                                        match fs::write(&path, b).await {
                                            Ok(_) => (Some(path), None),
                                            Err(e) => (None, Some(format!("Failed to write output: {}", e))),
                                        }
                                    } else {
                                        (None, None)
                                    }
                                } else if let Some(ref b) = body {
                                    // Write to stdout if verbose and not quiet
                                    if verbose && !quiet {
                                        if let Ok(s) = std::str::from_utf8(b) {
                                            println!("[Burst][{}] {} {}\n{}", i, req.method, req.url, s);
                                        } else {
                                            println!("[Burst][{}] {} {} (binary {} bytes)", i, req.method, req.url, b.len());
                                        }
                                    }
                                    (None, None)
                                } else {
                                    (None, None)
                                }
                            } else {
                                (None, Some(format!("HTTP error: status {}", status)))
                            };
                            return BurstResult {
                                request: req,
                                status: Some(status),
                                success,
                                duration,
                                error,
                                output_path,
                            };
                        }
                        Err(e) => {
                            attempt += 1;
                            if attempt > retries {
                                if verbose && !quiet {
                                    println!("[Burst][{}] {} {} -> ERROR: {}", i, req.method, req.url, e);
                                }
                                return BurstResult {
                                    request: req,
                                    status: None,
                                    success: false,
                                    duration: start.elapsed(),
                                    error: Some(e.to_string()),
                                    output_path: None,
                                };
                            }
                            // Exponential backoff with jitter
                            let jitter = rand::random::<u64>() % 100;
                            let sleep = backoff * attempt as u32 + std::time::Duration::from_millis(jitter);
                            tokio::time::sleep(sleep).await;
                        }
                    }
                }
            });
            handles.push(handle);
        }
        let results = futures::future::join_all(handles).await;
        let results: Vec<BurstResult> = results.into_iter().filter_map(|r| r.ok()).collect();
        if self.options.summary && !quiet {
            let total = results.len();
            let successes = results.iter().filter(|r| r.success).count();
            let failures = total - successes;
            let wall_elapsed = wall_start.elapsed();
            let mut times: Vec<_> = results.iter().map(|r| r.duration).collect();
            times.sort();
            let avg_time = if total > 0 { times.iter().sum::<std::time::Duration>() / (total as u32) } else { std::time::Duration::from_secs(0) };
            let min_time = times.first().cloned().unwrap_or_default();
            let max_time = times.last().cloned().unwrap_or_default();
            let median_time = if total == 0 {
                std::time::Duration::from_secs(0)
            } else if total % 2 == 1 {
                times[total / 2]
            } else {
                let t1 = times[total / 2 - 1];
                let t2 = times[total / 2];
                t1 + (t2 - t1) / 2
            };
            let throughput = if wall_elapsed.as_secs_f64() > 0.0 {
                total as f64 / wall_elapsed.as_secs_f64()
            } else {
                0.0
            };
            println!("\n--- Burst Summary ---");
            println!("Total Requests: {} | Success: {} | Fail: {}", total, color_green(&successes.to_string()), color_red(&failures.to_string()));
            println!("Elapsed (wall): {:.2?} | Throughput: {:.2} req/s", wall_elapsed, throughput);
            println!("Avg: {:.2?} | Median: {:.2?} | Min: {:.2?} | Max: {:.2?}", avg_time, median_time, min_time, max_time);
            println!("  (All times are per-request duration)");
            println!("  Elapsed = total wall-clock time for all requests");
            println!("  Throughput = requests per second");
            for (i, r) in results.iter().enumerate() {
                let is_timeout = r.error.as_ref().map_or(false, |e| {
                    let e = e.to_lowercase();
                    e.contains("timeout") || e.contains("timed out")
                });
                let (status_str, color_fn): (&str, Box<dyn Fn(&str) -> String>) = if r.success {
                    ("OK", Box::new(color_green))
                } else if is_timeout {
                    ("TIMEOUT", Box::new(color_yellow))
                } else {
                    ("FAIL", Box::new(color_red))
                };
                let status_colored = color_fn(status_str);
                println!("[{}] {} {} -> {}{}{}", i, r.request.method, r.request.url, status_colored, r.status.map(|s| format!(" [{}]", s)).unwrap_or_default(), r.output_path.as_ref().map(|p| format!(" -> {}", p)).unwrap_or_default());
                if let Some(ref e) = r.error {
                    let err_colored = if is_timeout {
                        color_yellow(&format!("TIMEOUT: {}", e))
                    } else {
                        color_red(e)
                    };
                    println!("    Error: {}", err_colored);
                }
            }
            println!("---------------------\n");
        }
        results
    }
}