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
252            let templates = templates.clone();
253            let base_headers = base_headers.clone();
254            let scenario = scenario.clone();
255            let duration_secs = duration_secs;
256            let base_output = self.base_output.clone();
257            let semaphore = semaphore.clone();
258            let progress_bar = progress_bars[index].clone();
259            let target_index = index;
260            let base_path = base_path.clone();
261
262            let handle = tokio::spawn(async move {
263                // Acquire semaphore permit
264                let _permit = semaphore.acquire().await.map_err(|e| {
265                    BenchError::Other(format!("Failed to acquire semaphore: {}", e))
266                })?;
267
268                progress_bar.set_message(format!("Testing {}", target.url));
269
270                // Create a temporary BenchCommand for this target execution
271                // We only need it to call execute_single_target, so we'll pass individual fields
272                // Execute test for this target
273                let result = Self::execute_single_target_internal(
274                    &duration,
275                    vus,
276                    &scenario_str,
277                    &operations,
278                    &auth,
279                    &headers,
280                    &threshold_percentile,
281                    threshold_ms,
282                    max_error_rate,
283                    verbose,
284                    skip_tls_verify,
285                    base_path.as_ref(),
286                    &target,
287                    target_index,
288                    &templates,
289                    &base_headers,
290                    &scenario,
291                    duration_secs,
292                    &base_output,
293                )
294                .await;
295
296                progress_bar.inc(1);
297                progress_bar.finish_with_message(format!("Completed {}", target.url));
298
299                result
300            });
301
302            handles.push(handle);
303        }
304
305        // Wait for all tasks to complete and collect results
306        let mut target_results = Vec::new();
307        for (index, handle) in handles.into_iter().enumerate() {
308            match handle.await {
309                Ok(Ok(result)) => {
310                    target_results.push(result);
311                }
312                Ok(Err(e)) => {
313                    // Create error result
314                    let target_url = self.targets[index].url.clone();
315                    target_results.push(TargetResult {
316                        target_url: target_url.clone(),
317                        target_index: index,
318                        results: K6Results::default(),
319                        output_dir: self.base_output.join(format!("target_{}", index + 1)),
320                        success: false,
321                        error: Some(e.to_string()),
322                    });
323                }
324                Err(e) => {
325                    // Join error
326                    let target_url = self.targets[index].url.clone();
327                    target_results.push(TargetResult {
328                        target_url: target_url.clone(),
329                        target_index: index,
330                        results: K6Results::default(),
331                        output_dir: self.base_output.join(format!("target_{}", index + 1)),
332                        success: false,
333                        error: Some(format!("Task join error: {}", e)),
334                    });
335                }
336            }
337        }
338
339        // Sort results by target index
340        target_results.sort_by_key(|r| r.target_index);
341
342        // Calculate aggregated metrics
343        let aggregated_metrics = AggregatedMetrics::from_results(&target_results);
344
345        let successful_targets = target_results.iter().filter(|r| r.success).count();
346        let failed_targets = total_targets - successful_targets;
347
348        Ok(AggregatedResults {
349            target_results,
350            total_targets,
351            successful_targets,
352            failed_targets,
353            aggregated_metrics,
354        })
355    }
356
357    /// Resolve the effective base path for API endpoints
358    fn resolve_base_path(&self, parser: &SpecParser) -> Option<String> {
359        // CLI option takes priority (including empty string to disable)
360        if let Some(cli_base_path) = &self.base_command.base_path {
361            if cli_base_path.is_empty() {
362                return None;
363            }
364            return Some(cli_base_path.clone());
365        }
366        // Fall back to spec's base path
367        parser.get_base_path()
368    }
369
370    /// Execute a single target test (internal method that doesn't require BenchCommand)
371    #[allow(clippy::too_many_arguments)]
372    async fn execute_single_target_internal(
373        duration: &str,
374        vus: u32,
375        scenario_str: &str,
376        operations: &Option<String>,
377        auth: &Option<String>,
378        headers: &Option<String>,
379        threshold_percentile: &str,
380        threshold_ms: u64,
381        max_error_rate: f64,
382        verbose: bool,
383        skip_tls_verify: bool,
384        base_path: Option<&String>,
385        target: &TargetConfig,
386        target_index: usize,
387        templates: &[crate::request_gen::RequestTemplate],
388        base_headers: &HashMap<String, String>,
389        scenario: &LoadScenario,
390        duration_secs: u64,
391        base_output: &Path,
392    ) -> Result<TargetResult> {
393        // Merge target-specific headers with base headers
394        let mut custom_headers = base_headers.clone();
395        if let Some(target_headers) = &target.headers {
396            custom_headers.extend(target_headers.clone());
397        }
398
399        // Use target-specific auth if provided, otherwise use base auth
400        let auth_header = target.auth.as_ref().or(auth.as_ref()).cloned();
401
402        // Create k6 config for this target
403        let k6_config = K6Config {
404            target_url: target.url.clone(),
405            base_path: base_path.cloned(),
406            scenario: scenario.clone(),
407            duration_secs,
408            max_vus: vus,
409            threshold_percentile: threshold_percentile.to_string(),
410            threshold_ms,
411            max_error_rate,
412            auth_header,
413            custom_headers,
414            skip_tls_verify,
415        };
416
417        // Generate k6 script
418        let generator = K6ScriptGenerator::new(k6_config, templates.to_vec());
419        let script = generator.generate()?;
420
421        // Validate script
422        let validation_errors = K6ScriptGenerator::validate_script(&script);
423        if !validation_errors.is_empty() {
424            return Err(BenchError::Other(format!(
425                "Script validation failed for target {}: {}",
426                target.url,
427                validation_errors.join(", ")
428            )));
429        }
430
431        // Create output directory for this target
432        let output_dir = base_output.join(format!("target_{}", target_index + 1));
433        std::fs::create_dir_all(&output_dir)?;
434
435        // Write script to file
436        let script_path = output_dir.join("k6-script.js");
437        std::fs::write(&script_path, script)?;
438
439        // Execute k6
440        let executor = K6Executor::new()?;
441        let results = executor.execute(&script_path, Some(&output_dir), verbose).await;
442
443        match results {
444            Ok(k6_results) => Ok(TargetResult {
445                target_url: target.url.clone(),
446                target_index,
447                results: k6_results,
448                output_dir,
449                success: true,
450                error: None,
451            }),
452            Err(e) => Ok(TargetResult {
453                target_url: target.url.clone(),
454                target_index,
455                results: K6Results::default(),
456                output_dir,
457                success: false,
458                error: Some(e.to_string()),
459            }),
460        }
461    }
462}
463
464#[cfg(test)]
465mod tests {
466    use super::*;
467
468    #[test]
469    fn test_aggregated_metrics_from_results() {
470        let results = vec![
471            TargetResult {
472                target_url: "http://api1.com".to_string(),
473                target_index: 0,
474                results: K6Results {
475                    total_requests: 100,
476                    failed_requests: 5,
477                    avg_duration_ms: 100.0,
478                    p95_duration_ms: 200.0,
479                    p99_duration_ms: 300.0,
480                },
481                output_dir: PathBuf::from("output1"),
482                success: true,
483                error: None,
484            },
485            TargetResult {
486                target_url: "http://api2.com".to_string(),
487                target_index: 1,
488                results: K6Results {
489                    total_requests: 200,
490                    failed_requests: 10,
491                    avg_duration_ms: 150.0,
492                    p95_duration_ms: 250.0,
493                    p99_duration_ms: 350.0,
494                },
495                output_dir: PathBuf::from("output2"),
496                success: true,
497                error: None,
498            },
499        ];
500
501        let metrics = AggregatedMetrics::from_results(&results);
502        assert_eq!(metrics.total_requests, 300);
503        assert_eq!(metrics.total_failed_requests, 15);
504        assert_eq!(metrics.avg_duration_ms, 125.0); // (100 + 150) / 2
505    }
506
507    #[test]
508    fn test_aggregated_metrics_with_failed_targets() {
509        let results = vec![
510            TargetResult {
511                target_url: "http://api1.com".to_string(),
512                target_index: 0,
513                results: K6Results {
514                    total_requests: 100,
515                    failed_requests: 5,
516                    avg_duration_ms: 100.0,
517                    p95_duration_ms: 200.0,
518                    p99_duration_ms: 300.0,
519                },
520                output_dir: PathBuf::from("output1"),
521                success: true,
522                error: None,
523            },
524            TargetResult {
525                target_url: "http://api2.com".to_string(),
526                target_index: 1,
527                results: K6Results::default(),
528                output_dir: PathBuf::from("output2"),
529                success: false,
530                error: Some("Network error".to_string()),
531            },
532        ];
533
534        let metrics = AggregatedMetrics::from_results(&results);
535        // Only successful target should be counted
536        assert_eq!(metrics.total_requests, 100);
537        assert_eq!(metrics.total_failed_requests, 5);
538        assert_eq!(metrics.avg_duration_ms, 100.0);
539    }
540
541    #[test]
542    fn test_aggregated_metrics_empty_results() {
543        let results = vec![];
544        let metrics = AggregatedMetrics::from_results(&results);
545        assert_eq!(metrics.total_requests, 0);
546        assert_eq!(metrics.total_failed_requests, 0);
547        assert_eq!(metrics.avg_duration_ms, 0.0);
548        assert_eq!(metrics.error_rate, 0.0);
549    }
550
551    #[test]
552    fn test_aggregated_metrics_error_rate_calculation() {
553        let results = vec![TargetResult {
554            target_url: "http://api1.com".to_string(),
555            target_index: 0,
556            results: K6Results {
557                total_requests: 1000,
558                failed_requests: 50,
559                avg_duration_ms: 100.0,
560                p95_duration_ms: 200.0,
561                p99_duration_ms: 300.0,
562            },
563            output_dir: PathBuf::from("output1"),
564            success: true,
565            error: None,
566        }];
567
568        let metrics = AggregatedMetrics::from_results(&results);
569        assert_eq!(metrics.error_rate, 5.0); // 50/1000 * 100
570    }
571
572    #[test]
573    fn test_aggregated_metrics_p95_p99_calculation() {
574        let results = vec![
575            TargetResult {
576                target_url: "http://api1.com".to_string(),
577                target_index: 0,
578                results: K6Results {
579                    total_requests: 100,
580                    failed_requests: 0,
581                    avg_duration_ms: 100.0,
582                    p95_duration_ms: 150.0,
583                    p99_duration_ms: 200.0,
584                },
585                output_dir: PathBuf::from("output1"),
586                success: true,
587                error: None,
588            },
589            TargetResult {
590                target_url: "http://api2.com".to_string(),
591                target_index: 1,
592                results: K6Results {
593                    total_requests: 100,
594                    failed_requests: 0,
595                    avg_duration_ms: 200.0,
596                    p95_duration_ms: 250.0,
597                    p99_duration_ms: 300.0,
598                },
599                output_dir: PathBuf::from("output2"),
600                success: true,
601                error: None,
602            },
603            TargetResult {
604                target_url: "http://api3.com".to_string(),
605                target_index: 2,
606                results: K6Results {
607                    total_requests: 100,
608                    failed_requests: 0,
609                    avg_duration_ms: 300.0,
610                    p95_duration_ms: 350.0,
611                    p99_duration_ms: 400.0,
612                },
613                output_dir: PathBuf::from("output3"),
614                success: true,
615                error: None,
616            },
617        ];
618
619        let metrics = AggregatedMetrics::from_results(&results);
620        // p95 should be the 95th percentile of [150, 250, 350] = index 2 = 350
621        // p99 should be the 99th percentile of [200, 300, 400] = index 2 = 400
622        assert_eq!(metrics.p95_duration_ms, 350.0);
623        assert_eq!(metrics.p99_duration_ms, 400.0);
624    }
625}