mockforge_bench/
parallel_executor.rs

1//! Parallel execution engine for multi-target bench testing
2//!
3//! Executes load tests against multiple targets in parallel with configurable
4//! concurrency limits. Uses tokio for async execution and semaphores for
5//! backpressure control.
6
7use crate::command::BenchCommand;
8use crate::error::{BenchError, Result};
9use crate::executor::{K6Executor, K6Results};
10use crate::k6_gen::{K6Config, K6ScriptGenerator};
11use crate::reporter::TerminalReporter;
12use crate::request_gen::RequestGenerator;
13use crate::scenarios::LoadScenario;
14use crate::spec_parser::SpecParser;
15use crate::target_parser::TargetConfig;
16use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
17use std::collections::HashMap;
18use std::path::{Path, PathBuf};
19use std::str::FromStr;
20use std::sync::Arc;
21use tokio::sync::Semaphore;
22use tokio::task::JoinHandle;
23
24/// Result for a single target execution
25#[derive(Debug, Clone)]
26pub struct TargetResult {
27    /// Target URL that was tested
28    pub target_url: String,
29    /// Index of the target (for ordering)
30    pub target_index: usize,
31    /// k6 test results
32    pub results: K6Results,
33    /// Output directory for this target
34    pub output_dir: PathBuf,
35    /// Whether the test succeeded
36    pub success: bool,
37    /// Error message if test failed
38    pub error: Option<String>,
39}
40
41/// Aggregated results from all target executions
42#[derive(Debug, Clone)]
43pub struct AggregatedResults {
44    /// Results for each target
45    pub target_results: Vec<TargetResult>,
46    /// Overall statistics
47    pub total_targets: usize,
48    pub successful_targets: usize,
49    pub failed_targets: usize,
50    /// Aggregated metrics across all targets
51    pub aggregated_metrics: AggregatedMetrics,
52}
53
54/// Aggregated metrics across all targets
55#[derive(Debug, Clone)]
56pub struct AggregatedMetrics {
57    /// Total requests across all targets
58    pub total_requests: u64,
59    /// Total failed requests across all targets
60    pub total_failed_requests: u64,
61    /// Average response time across all targets (ms)
62    pub avg_duration_ms: f64,
63    /// p95 response time across all targets (ms)
64    pub p95_duration_ms: f64,
65    /// p99 response time across all targets (ms)
66    pub p99_duration_ms: f64,
67    /// Overall error rate percentage
68    pub error_rate: f64,
69}
70
71impl AggregatedMetrics {
72    /// Calculate aggregated metrics from target results
73    fn from_results(results: &[TargetResult]) -> Self {
74        let mut total_requests = 0u64;
75        let mut total_failed_requests = 0u64;
76        let mut durations = Vec::new();
77        let mut p95_values = Vec::new();
78        let mut p99_values = Vec::new();
79
80        for result in results {
81            if result.success {
82                total_requests += result.results.total_requests;
83                total_failed_requests += result.results.failed_requests;
84                durations.push(result.results.avg_duration_ms);
85                p95_values.push(result.results.p95_duration_ms);
86                p99_values.push(result.results.p99_duration_ms);
87            }
88        }
89
90        let avg_duration_ms = if !durations.is_empty() {
91            durations.iter().sum::<f64>() / durations.len() as f64
92        } else {
93            0.0
94        };
95
96        let p95_duration_ms = if !p95_values.is_empty() {
97            p95_values.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
98            let index = (p95_values.len() as f64 * 0.95).ceil() as usize - 1;
99            p95_values[index.min(p95_values.len() - 1)]
100        } else {
101            0.0
102        };
103
104        let p99_duration_ms = if !p99_values.is_empty() {
105            p99_values.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
106            let index = (p99_values.len() as f64 * 0.99).ceil() as usize - 1;
107            p99_values[index.min(p99_values.len() - 1)]
108        } else {
109            0.0
110        };
111
112        let error_rate = if total_requests > 0 {
113            (total_failed_requests as f64 / total_requests as f64) * 100.0
114        } else {
115            0.0
116        };
117
118        Self {
119            total_requests,
120            total_failed_requests,
121            avg_duration_ms,
122            p95_duration_ms,
123            p99_duration_ms,
124            error_rate,
125        }
126    }
127}
128
129/// Parallel executor for multi-target bench testing
130pub struct ParallelExecutor {
131    /// Base command configuration (shared across all targets)
132    base_command: BenchCommand,
133    /// List of targets to test
134    targets: Vec<TargetConfig>,
135    /// Maximum number of concurrent executions
136    max_concurrency: usize,
137    /// Base output directory
138    base_output: PathBuf,
139}
140
141impl ParallelExecutor {
142    /// Create a new parallel executor
143    pub fn new(
144        base_command: BenchCommand,
145        targets: Vec<TargetConfig>,
146        max_concurrency: usize,
147    ) -> Self {
148        let base_output = base_command.output.clone();
149        Self {
150            base_command,
151            targets,
152            max_concurrency,
153            base_output,
154        }
155    }
156
157    /// Execute tests against all targets in parallel
158    pub async fn execute_all(&self) -> Result<AggregatedResults> {
159        let total_targets = self.targets.len();
160        TerminalReporter::print_progress(&format!(
161            "Starting parallel execution for {} targets (max concurrency: {})",
162            total_targets, self.max_concurrency
163        ));
164
165        // Validate k6 installation
166        if !K6Executor::is_k6_installed() {
167            TerminalReporter::print_error("k6 is not installed");
168            TerminalReporter::print_warning(
169                "Install k6 from: https://k6.io/docs/get-started/installation/",
170            );
171            return Err(BenchError::K6NotFound);
172        }
173
174        // Load and parse spec(s) (shared across all targets)
175        TerminalReporter::print_progress("Loading OpenAPI specification(s)...");
176        let merged_spec = self.base_command.load_and_merge_specs().await?;
177        let parser = SpecParser::from_spec(merged_spec);
178        TerminalReporter::print_success("Specification(s) loaded");
179
180        // Get operations
181        let operations = if let Some(filter) = &self.base_command.operations {
182            parser.filter_operations(filter)?
183        } else {
184            parser.get_operations()
185        };
186
187        if operations.is_empty() {
188            return Err(BenchError::Other("No operations found in spec".to_string()));
189        }
190
191        TerminalReporter::print_success(&format!("Found {} operations", operations.len()));
192
193        // Generate request templates (shared across all targets)
194        TerminalReporter::print_progress("Generating request templates...");
195        let templates: Vec<_> = operations
196            .iter()
197            .map(RequestGenerator::generate_template)
198            .collect::<Result<Vec<_>>>()?;
199        TerminalReporter::print_success("Request templates generated");
200
201        // Parse base headers
202        let base_headers = self.base_command.parse_headers()?;
203
204        // Resolve base path (CLI option takes priority over spec's servers URL)
205        let base_path = self.resolve_base_path(&parser);
206        if let Some(ref bp) = base_path {
207            TerminalReporter::print_progress(&format!("Using base path: {}", bp));
208        }
209
210        // Parse scenario
211        let scenario = LoadScenario::from_str(&self.base_command.scenario)
212            .map_err(BenchError::InvalidScenario)?;
213
214        let duration_secs = BenchCommand::parse_duration(&self.base_command.duration)?;
215
216        // Create semaphore for concurrency control
217        let semaphore = Arc::new(Semaphore::new(self.max_concurrency));
218        let multi_progress = MultiProgress::new();
219
220        // Create progress bars for each target
221        let progress_bars: Vec<ProgressBar> = (0..total_targets)
222            .map(|i| {
223                let pb = multi_progress.add(ProgressBar::new(1));
224                pb.set_style(
225                    ProgressStyle::default_bar()
226                        .template("{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {pos}/{len} {msg}")
227                        .unwrap(),
228                );
229                pb.set_message(format!("Target {}", i + 1));
230                pb
231            })
232            .collect();
233
234        // Spawn tasks for each target
235        let mut handles: Vec<JoinHandle<Result<TargetResult>>> = Vec::new();
236
237        for (index, target) in self.targets.iter().enumerate() {
238            let target = target.clone();
239            // Clone necessary fields from base_command instead of passing reference
240            let duration = self.base_command.duration.clone();
241            let vus = self.base_command.vus;
242            let scenario_str = self.base_command.scenario.clone();
243            let operations = self.base_command.operations.clone();
244            let auth = self.base_command.auth.clone();
245            let headers = self.base_command.headers.clone();
246            let threshold_percentile = self.base_command.threshold_percentile.clone();
247            let threshold_ms = self.base_command.threshold_ms;
248            let max_error_rate = self.base_command.max_error_rate;
249            let verbose = self.base_command.verbose;
250            let skip_tls_verify = self.base_command.skip_tls_verify;
251            let security_testing_enabled =
252                self.base_command.security_test || self.base_command.wafbench_dir.is_some();
253
254            let templates = templates.clone();
255            let base_headers = base_headers.clone();
256            let scenario = scenario.clone();
257            let duration_secs = duration_secs;
258            let base_output = self.base_output.clone();
259            let semaphore = semaphore.clone();
260            let progress_bar = progress_bars[index].clone();
261            let target_index = index;
262            let base_path = base_path.clone();
263
264            let handle = tokio::spawn(async move {
265                // Acquire semaphore permit
266                let _permit = semaphore.acquire().await.map_err(|e| {
267                    BenchError::Other(format!("Failed to acquire semaphore: {}", e))
268                })?;
269
270                progress_bar.set_message(format!("Testing {}", target.url));
271
272                // Create a temporary BenchCommand for this target execution
273                // We only need it to call execute_single_target, so we'll pass individual fields
274                // Execute test for this target
275                let result = Self::execute_single_target_internal(
276                    &duration,
277                    vus,
278                    &scenario_str,
279                    &operations,
280                    &auth,
281                    &headers,
282                    &threshold_percentile,
283                    threshold_ms,
284                    max_error_rate,
285                    verbose,
286                    skip_tls_verify,
287                    security_testing_enabled,
288                    base_path.as_ref(),
289                    &target,
290                    target_index,
291                    &templates,
292                    &base_headers,
293                    &scenario,
294                    duration_secs,
295                    &base_output,
296                )
297                .await;
298
299                progress_bar.inc(1);
300                progress_bar.finish_with_message(format!("Completed {}", target.url));
301
302                result
303            });
304
305            handles.push(handle);
306        }
307
308        // Wait for all tasks to complete and collect results
309        let mut target_results = Vec::new();
310        for (index, handle) in handles.into_iter().enumerate() {
311            match handle.await {
312                Ok(Ok(result)) => {
313                    target_results.push(result);
314                }
315                Ok(Err(e)) => {
316                    // Create error result
317                    let target_url = self.targets[index].url.clone();
318                    target_results.push(TargetResult {
319                        target_url: target_url.clone(),
320                        target_index: index,
321                        results: K6Results::default(),
322                        output_dir: self.base_output.join(format!("target_{}", index + 1)),
323                        success: false,
324                        error: Some(e.to_string()),
325                    });
326                }
327                Err(e) => {
328                    // Join error
329                    let target_url = self.targets[index].url.clone();
330                    target_results.push(TargetResult {
331                        target_url: target_url.clone(),
332                        target_index: index,
333                        results: K6Results::default(),
334                        output_dir: self.base_output.join(format!("target_{}", index + 1)),
335                        success: false,
336                        error: Some(format!("Task join error: {}", e)),
337                    });
338                }
339            }
340        }
341
342        // Sort results by target index
343        target_results.sort_by_key(|r| r.target_index);
344
345        // Calculate aggregated metrics
346        let aggregated_metrics = AggregatedMetrics::from_results(&target_results);
347
348        let successful_targets = target_results.iter().filter(|r| r.success).count();
349        let failed_targets = total_targets - successful_targets;
350
351        Ok(AggregatedResults {
352            target_results,
353            total_targets,
354            successful_targets,
355            failed_targets,
356            aggregated_metrics,
357        })
358    }
359
360    /// Resolve the effective base path for API endpoints
361    fn resolve_base_path(&self, parser: &SpecParser) -> Option<String> {
362        // CLI option takes priority (including empty string to disable)
363        if let Some(cli_base_path) = &self.base_command.base_path {
364            if cli_base_path.is_empty() {
365                return None;
366            }
367            return Some(cli_base_path.clone());
368        }
369        // Fall back to spec's base path
370        parser.get_base_path()
371    }
372
373    /// Execute a single target test (internal method that doesn't require BenchCommand)
374    #[allow(clippy::too_many_arguments)]
375    async fn execute_single_target_internal(
376        duration: &str,
377        vus: u32,
378        scenario_str: &str,
379        operations: &Option<String>,
380        auth: &Option<String>,
381        headers: &Option<String>,
382        threshold_percentile: &str,
383        threshold_ms: u64,
384        max_error_rate: f64,
385        verbose: bool,
386        skip_tls_verify: bool,
387        security_testing_enabled: bool,
388        base_path: Option<&String>,
389        target: &TargetConfig,
390        target_index: usize,
391        templates: &[crate::request_gen::RequestTemplate],
392        base_headers: &HashMap<String, String>,
393        scenario: &LoadScenario,
394        duration_secs: u64,
395        base_output: &Path,
396    ) -> Result<TargetResult> {
397        // Merge target-specific headers with base headers
398        let mut custom_headers = base_headers.clone();
399        if let Some(target_headers) = &target.headers {
400            custom_headers.extend(target_headers.clone());
401        }
402
403        // Use target-specific auth if provided, otherwise use base auth
404        let auth_header = target.auth.as_ref().or(auth.as_ref()).cloned();
405
406        // Create k6 config for this target
407        let k6_config = K6Config {
408            target_url: target.url.clone(),
409            base_path: base_path.cloned(),
410            scenario: scenario.clone(),
411            duration_secs,
412            max_vus: vus,
413            threshold_percentile: threshold_percentile.to_string(),
414            threshold_ms,
415            max_error_rate,
416            auth_header,
417            custom_headers,
418            skip_tls_verify,
419            security_testing_enabled,
420        };
421
422        // Generate k6 script
423        let generator = K6ScriptGenerator::new(k6_config, templates.to_vec());
424        let script = generator.generate()?;
425
426        // Validate script
427        let validation_errors = K6ScriptGenerator::validate_script(&script);
428        if !validation_errors.is_empty() {
429            return Err(BenchError::Other(format!(
430                "Script validation failed for target {}: {}",
431                target.url,
432                validation_errors.join(", ")
433            )));
434        }
435
436        // Create output directory for this target
437        let output_dir = base_output.join(format!("target_{}", target_index + 1));
438        std::fs::create_dir_all(&output_dir)?;
439
440        // Write script to file
441        let script_path = output_dir.join("k6-script.js");
442        std::fs::write(&script_path, script)?;
443
444        // Execute k6
445        let executor = K6Executor::new()?;
446        let results = executor.execute(&script_path, Some(&output_dir), verbose).await;
447
448        match results {
449            Ok(k6_results) => Ok(TargetResult {
450                target_url: target.url.clone(),
451                target_index,
452                results: k6_results,
453                output_dir,
454                success: true,
455                error: None,
456            }),
457            Err(e) => Ok(TargetResult {
458                target_url: target.url.clone(),
459                target_index,
460                results: K6Results::default(),
461                output_dir,
462                success: false,
463                error: Some(e.to_string()),
464            }),
465        }
466    }
467}
468
469#[cfg(test)]
470mod tests {
471    use super::*;
472
473    #[test]
474    fn test_aggregated_metrics_from_results() {
475        let results = vec![
476            TargetResult {
477                target_url: "http://api1.com".to_string(),
478                target_index: 0,
479                results: K6Results {
480                    total_requests: 100,
481                    failed_requests: 5,
482                    avg_duration_ms: 100.0,
483                    p95_duration_ms: 200.0,
484                    p99_duration_ms: 300.0,
485                },
486                output_dir: PathBuf::from("output1"),
487                success: true,
488                error: None,
489            },
490            TargetResult {
491                target_url: "http://api2.com".to_string(),
492                target_index: 1,
493                results: K6Results {
494                    total_requests: 200,
495                    failed_requests: 10,
496                    avg_duration_ms: 150.0,
497                    p95_duration_ms: 250.0,
498                    p99_duration_ms: 350.0,
499                },
500                output_dir: PathBuf::from("output2"),
501                success: true,
502                error: None,
503            },
504        ];
505
506        let metrics = AggregatedMetrics::from_results(&results);
507        assert_eq!(metrics.total_requests, 300);
508        assert_eq!(metrics.total_failed_requests, 15);
509        assert_eq!(metrics.avg_duration_ms, 125.0); // (100 + 150) / 2
510    }
511
512    #[test]
513    fn test_aggregated_metrics_with_failed_targets() {
514        let results = vec![
515            TargetResult {
516                target_url: "http://api1.com".to_string(),
517                target_index: 0,
518                results: K6Results {
519                    total_requests: 100,
520                    failed_requests: 5,
521                    avg_duration_ms: 100.0,
522                    p95_duration_ms: 200.0,
523                    p99_duration_ms: 300.0,
524                },
525                output_dir: PathBuf::from("output1"),
526                success: true,
527                error: None,
528            },
529            TargetResult {
530                target_url: "http://api2.com".to_string(),
531                target_index: 1,
532                results: K6Results::default(),
533                output_dir: PathBuf::from("output2"),
534                success: false,
535                error: Some("Network error".to_string()),
536            },
537        ];
538
539        let metrics = AggregatedMetrics::from_results(&results);
540        // Only successful target should be counted
541        assert_eq!(metrics.total_requests, 100);
542        assert_eq!(metrics.total_failed_requests, 5);
543        assert_eq!(metrics.avg_duration_ms, 100.0);
544    }
545
546    #[test]
547    fn test_aggregated_metrics_empty_results() {
548        let results = vec![];
549        let metrics = AggregatedMetrics::from_results(&results);
550        assert_eq!(metrics.total_requests, 0);
551        assert_eq!(metrics.total_failed_requests, 0);
552        assert_eq!(metrics.avg_duration_ms, 0.0);
553        assert_eq!(metrics.error_rate, 0.0);
554    }
555
556    #[test]
557    fn test_aggregated_metrics_error_rate_calculation() {
558        let results = vec![TargetResult {
559            target_url: "http://api1.com".to_string(),
560            target_index: 0,
561            results: K6Results {
562                total_requests: 1000,
563                failed_requests: 50,
564                avg_duration_ms: 100.0,
565                p95_duration_ms: 200.0,
566                p99_duration_ms: 300.0,
567            },
568            output_dir: PathBuf::from("output1"),
569            success: true,
570            error: None,
571        }];
572
573        let metrics = AggregatedMetrics::from_results(&results);
574        assert_eq!(metrics.error_rate, 5.0); // 50/1000 * 100
575    }
576
577    #[test]
578    fn test_aggregated_metrics_p95_p99_calculation() {
579        let results = vec![
580            TargetResult {
581                target_url: "http://api1.com".to_string(),
582                target_index: 0,
583                results: K6Results {
584                    total_requests: 100,
585                    failed_requests: 0,
586                    avg_duration_ms: 100.0,
587                    p95_duration_ms: 150.0,
588                    p99_duration_ms: 200.0,
589                },
590                output_dir: PathBuf::from("output1"),
591                success: true,
592                error: None,
593            },
594            TargetResult {
595                target_url: "http://api2.com".to_string(),
596                target_index: 1,
597                results: K6Results {
598                    total_requests: 100,
599                    failed_requests: 0,
600                    avg_duration_ms: 200.0,
601                    p95_duration_ms: 250.0,
602                    p99_duration_ms: 300.0,
603                },
604                output_dir: PathBuf::from("output2"),
605                success: true,
606                error: None,
607            },
608            TargetResult {
609                target_url: "http://api3.com".to_string(),
610                target_index: 2,
611                results: K6Results {
612                    total_requests: 100,
613                    failed_requests: 0,
614                    avg_duration_ms: 300.0,
615                    p95_duration_ms: 350.0,
616                    p99_duration_ms: 400.0,
617                },
618                output_dir: PathBuf::from("output3"),
619                success: true,
620                error: None,
621            },
622        ];
623
624        let metrics = AggregatedMetrics::from_results(&results);
625        // p95 should be the 95th percentile of [150, 250, 350] = index 2 = 350
626        // p99 should be the 99th percentile of [200, 300, 400] = index 2 = 400
627        assert_eq!(metrics.p95_duration_ms, 350.0);
628        assert_eq!(metrics.p99_duration_ms, 400.0);
629    }
630}