use std::{
any::{Any, TypeId},
future::Future,
pin::Pin,
};
use crate::{
error::ScenarioError,
recorder::Recorder,
runner::{RunMode, RunnerConfig, ScenarioRunner},
scenario::Scenario,
};
#[derive(Clone, Copy, Debug)]
pub struct ScenarioConfig {
pub run_mode: Option<RunMode>,
}
impl ScenarioConfig {
pub const fn new(run_mode: Option<RunMode>) -> Self {
Self { run_mode }
}
}
pub type ScenarioInvoke =
for<'a> fn(&'a dyn Any, &'a RunnerConfig) -> Pin<Box<dyn Future<Output = Recorder> + 'a>>;
pub struct ScenarioRegistration {
pub name: &'static str,
pub ctx_type: fn() -> TypeId,
pub config: ScenarioConfig,
pub invoke: ScenarioInvoke,
}
inventory::collect!(ScenarioRegistration);
pub fn invoke<'a, S>(
ctx: &'a dyn Any,
cfg: &'a RunnerConfig,
) -> Pin<Box<dyn Future<Output = Recorder> + 'a>>
where
S: Scenario,
S::Error: ScenarioError,
{
let ctx = ctx.downcast_ref::<S::Ctx>().expect("Ctx 类型不匹配");
Box::pin(async move {
let runner = ScenarioRunner::<S>::new(RunnerConfig {
mode: cfg.mode,
task_index: cfg.task_index,
task_total: cfg.task_total,
shutdown: cfg.shutdown.clone(),
#[cfg(feature = "tui")]
progress: cfg.progress.clone(),
});
runner.run(ctx).await
})
}
pub struct ScenarioRegistry;
impl ScenarioRegistry {
pub fn scenarios<Ctx: Any + Sync>() -> Vec<&'static ScenarioRegistration> {
let id = TypeId::of::<Ctx>();
inventory::iter::<ScenarioRegistration>
.into_iter()
.filter(|e| (e.ctx_type)() == id)
.collect()
}
pub fn names<Ctx: Any + Sync>() -> Vec<&'static str> {
Self::scenarios::<Ctx>()
.into_iter()
.map(|e| e.name)
.collect()
}
pub fn find<Ctx: Any + Sync>(name: &str) -> Option<&'static ScenarioRegistration> {
Self::scenarios::<Ctx>()
.into_iter()
.find(|e| e.name == name)
}
}