use std::{any::Any, time::Instant};
use futures::future::join_all;
#[cfg(feature = "tui")]
use crate::progress::{Progress, ProgressGuard, ProgressPlan};
#[cfg(feature = "tui")]
use crate::tui::TuiOptions;
use crate::{
registry::{ScenarioRegistration, ScenarioRegistry},
report::ScenarioReport,
runner::{RunMode, RunnerConfig},
shutdown::Shutdown,
};
#[derive(Debug)]
pub struct ManagerConfig {
concurrency: u64,
run_mode: Option<RunMode>,
shutdown: Option<Shutdown>,
#[cfg(feature = "tui")]
tui: Option<TuiOptions>,
}
impl ManagerConfig {
pub fn new(concurrency: u64) -> Self {
if concurrency == 0 {
panic!("Manager Config concurrency cannot be zero");
}
Self {
concurrency,
run_mode: None,
shutdown: None,
#[cfg(feature = "tui")]
tui: None,
}
}
pub fn with_run_mode(mut self, run_mode: RunMode) -> Self {
self.run_mode = Some(run_mode);
self
}
pub fn with_shutdown(mut self, shutdown: Shutdown) -> Self {
self.shutdown = Some(shutdown);
self
}
pub fn install_ctrl_c(mut self) -> Self {
self.shutdown = Some(Shutdown::install_ctrl_c());
self
}
#[cfg(feature = "tui")]
pub fn with_tui(mut self) -> Self {
self.tui = Some(TuiOptions::default());
self
}
#[cfg(feature = "tui")]
pub fn with_tui_options(mut self, options: TuiOptions) -> Self {
self.tui = Some(options);
self
}
}
pub struct ScenarioManager {
config: ManagerConfig,
}
impl ScenarioManager {
pub fn new(config: ManagerConfig) -> Self {
Self { config }
}
pub async fn run_all<Ctx: Any + Sync>(&self, ctx: &Ctx) -> Vec<ScenarioReport> {
let scenarios = ScenarioRegistry::scenarios::<Ctx>();
self.run(ctx, &scenarios).await
}
pub async fn run_all_with_shutdown<Ctx: Any + Sync>(
&self,
ctx: &Ctx,
shutdown: Shutdown,
) -> Vec<ScenarioReport> {
let scenarios = ScenarioRegistry::scenarios::<Ctx>();
self.run_with_shutdown(ctx, &scenarios, shutdown).await
}
pub async fn run<Ctx: Any + Sync>(
&self,
ctx: &Ctx,
scenarios: &[&'static ScenarioRegistration],
) -> Vec<ScenarioReport> {
self.run_inner(ctx, scenarios, self.config.shutdown.as_ref())
.await
}
pub async fn run_with_shutdown<Ctx: Any + Sync>(
&self,
ctx: &Ctx,
scenarios: &[&'static ScenarioRegistration],
shutdown: Shutdown,
) -> Vec<ScenarioReport> {
self.run_inner(ctx, scenarios, Some(&shutdown)).await
}
async fn run_inner<Ctx: Any + Sync>(
&self,
ctx: &Ctx,
scenarios: &[&'static ScenarioRegistration],
shutdown: Option<&Shutdown>,
) -> Vec<ScenarioReport> {
let mut reports = Vec::with_capacity(scenarios.len());
for (i, s) in scenarios.iter().enumerate() {
if shutdown.is_some_and(|s| s.is_cancelled()) {
break;
}
reports.push(self.run_entry(s, ctx, shutdown, i, scenarios.len()).await);
}
reports
}
pub async fn run_one<Ctx: Any + Sync>(&self, name: &str, ctx: &Ctx) -> Option<ScenarioReport> {
let s = ScenarioRegistry::find::<Ctx>(name)?;
Some(
self.run_entry(s, ctx, self.config.shutdown.as_ref(), 0, 1)
.await,
)
}
pub async fn run_one_with_shutdown<Ctx: Any + Sync>(
&self,
name: &str,
ctx: &Ctx,
shutdown: Shutdown,
) -> Option<ScenarioReport> {
let s = ScenarioRegistry::find::<Ctx>(name)?;
Some(self.run_entry(s, ctx, Some(&shutdown), 0, 1).await)
}
async fn run_entry(
&self,
entry: &ScenarioRegistration,
ctx: &dyn Any,
shutdown: Option<&Shutdown>,
scenario_index: usize,
scenario_total: usize,
) -> ScenarioReport {
#[cfg(not(feature = "tui"))]
let _ = (scenario_index, scenario_total);
let mode = self
.config
.run_mode
.or(entry.config.run_mode)
.unwrap_or_else(|| panic!("{} 未配置执行模式(times/duration)", entry.name));
let concurrency = self.config.concurrency;
#[cfg(feature = "tui")]
let tui = self
.config
.tui
.clone()
.map(|mut options| (options.clone(), options.take_channel()));
#[cfg(feature = "tui")]
let progress: Option<Progress> = tui.as_ref().map(|(_options, channel)| {
let plan = match mode {
RunMode::Times(total) => ProgressPlan::Rounds(total),
RunMode::Duration(d) => ProgressPlan::Time(d),
};
Progress::new(
entry.name,
plan,
Some(channel.clone()),
scenario_index,
scenario_total,
)
});
#[cfg(feature = "tui")]
let progress_guard: Option<ProgressGuard> = match tui.as_ref() {
Some((options, channel)) => progress
.as_ref()
.map(|p| p.start_tui(channel.clone(), options.clone(), shutdown.cloned())),
None => None,
};
let mk_config = |i: u64, mode: RunMode| RunnerConfig {
mode,
task_index: i as usize,
task_total: concurrency as usize,
shutdown: shutdown.cloned(),
#[cfg(feature = "tui")]
progress: progress.clone(),
};
let cfgs: Vec<RunnerConfig> = match mode {
RunMode::Times(total) => {
let base = total / concurrency;
let rem = total % concurrency;
(0..concurrency)
.map(|i| mk_config(i, RunMode::Times(base + u64::from(i < rem))))
.collect()
}
RunMode::Duration(d) => (0..concurrency)
.map(|i| mk_config(i, RunMode::Duration(d)))
.collect(),
};
let start = Instant::now();
let futures: Vec<_> = cfgs.iter().map(|c| (entry.invoke)(ctx, c)).collect();
let results = join_all(futures).await;
let elapsed = start.elapsed();
#[cfg(feature = "tui")]
if let Some(guard) = progress_guard {
guard.stop().await;
}
#[cfg(feature = "tui")]
if let Some((_, channel)) = tui.as_ref() {
if shutdown.is_some_and(|s| s.is_cancelled()) {
eprintln!(
"{}",
crate::report::paint(
"^C received, graceful shutdown: finishing current rounds, report below",
"1;33",
true,
)
);
}
for line in channel.drain() {
eprintln!("{line}");
}
}
let mut it = results.into_iter();
let mut merged = it.next().expect("concurrency must be > 0");
for other in it {
merged.merge(other);
}
ScenarioReport::from_recorder(entry.name, merged, self.config.concurrency, elapsed)
}
}