use std::{
borrow::Cow,
marker::PhantomData,
time::{Duration, Instant},
};
#[cfg(feature = "tui")]
use crate::progress::Progress;
use crate::{
error::ScenarioError,
recorder::Recorder,
scenario::{Scenario, SetupMode, TeardownMode},
shutdown::Shutdown,
};
#[derive(Clone, Copy, Debug)]
pub enum RunMode {
Times(u64),
Duration(Duration),
}
#[derive(Clone, Copy, Debug)]
pub struct BackoffConfig {
pub initial: Duration,
pub max: Duration,
pub factor: f64,
}
impl Default for BackoffConfig {
fn default() -> Self {
Self {
initial: Duration::from_millis(100),
max: Duration::from_secs(3),
factor: 2.0,
}
}
}
impl BackoffConfig {
pub const fn new(initial: Duration, max: Duration, factor: f64) -> Self {
Self {
initial,
max,
factor,
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct TaskIndex {
pub index: usize,
pub total: usize,
pub round: usize,
}
impl TaskIndex {
pub const fn new(index: usize, total: usize, round: usize) -> Self {
Self {
index,
total,
round,
}
}
}
pub struct RunnerConfig {
pub mode: RunMode,
pub task_index: usize,
pub task_total: usize,
pub shutdown: Option<Shutdown>,
pub backoff: Option<BackoffConfig>,
#[cfg(feature = "tui")]
pub progress: Option<Progress>,
}
pub struct ScenarioRunner<S> {
config: RunnerConfig,
_marker: PhantomData<S>,
}
enum SetupDone<S> {
Ready(S),
Failed,
Cancelled,
}
#[derive(Clone, Copy, Debug)]
enum RoundBudget {
Times {
left: u64,
},
Duration {
remaining: Duration,
},
}
impl RoundBudget {
const fn new(mode: RunMode) -> Self {
match mode {
RunMode::Times(times) => Self::Times { left: times },
RunMode::Duration(duration) => Self::Duration {
remaining: duration,
},
}
}
fn has_next(&self) -> bool {
match self {
Self::Times { left } => *left > 0,
Self::Duration { remaining } => !remaining.is_zero(),
}
}
fn spend(&mut self, elapsed: Duration) {
match self {
Self::Times { left } => *left = left.saturating_sub(1),
Self::Duration { remaining } => *remaining = remaining.saturating_sub(elapsed),
}
}
}
impl<S> ScenarioRunner<S>
where
S: Scenario,
S::Error: ScenarioError,
{
pub fn new(config: RunnerConfig) -> Self {
Self {
config,
_marker: PhantomData,
}
}
pub async fn run(&self, ctx: &S::Ctx) -> Recorder {
let mut recorder = Recorder::from_config(&self.config);
let mut backoff_wait = Self::backoff_initial(self.config.backoff);
match S::SETUP_MODE {
SetupMode::Task => {
if self.is_cancelled() {
recorder.record_interrupted();
return recorder;
}
let task = TaskIndex::new(self.config.task_index, self.config.task_total, 0);
#[cfg(feature = "tui")]
recorder.begin_setup();
let setup = match self
.setup_retrying(ctx, &task, &mut recorder, &mut backoff_wait)
.await
{
SetupDone::Ready(setup) => setup,
SetupDone::Failed => return recorder,
SetupDone::Cancelled => {
recorder.record_interrupted();
return recorder;
}
};
#[cfg(feature = "tui")]
recorder.end_setup();
if self.is_cancelled() {
recorder.record_interrupted();
} else {
self.drive_rounds(ctx, &setup, &mut recorder, &mut backoff_wait)
.await;
}
if S::TEARDOWN_MODE == TeardownMode::Task {
Self::teardown(ctx, &task, &setup, None, &mut recorder).await;
}
}
SetupMode::Round => {
let mut budget = RoundBudget::new(self.config.mode);
let mut round = 0usize;
let mut last: Option<(TaskIndex, S::Setup)> = None;
while budget.has_next() {
if self.is_cancelled() {
recorder.record_interrupted();
break;
}
let start = Instant::now();
let task =
TaskIndex::new(self.config.task_index, self.config.task_total, round);
round += 1;
let setup = match self
.setup_retrying(ctx, &task, &mut recorder, &mut backoff_wait)
.await
{
SetupDone::Ready(setup) => setup,
SetupDone::Failed => break,
SetupDone::Cancelled => {
recorder.record_interrupted();
break;
}
};
let entry = (task, setup);
let stopped = self
.round(ctx, &entry.0, &entry.1, &mut recorder, &mut backoff_wait)
.await;
budget.spend(start.elapsed());
last = Some(entry);
if stopped {
recorder.record_interrupted();
break;
}
}
if S::TEARDOWN_MODE == TeardownMode::Task
&& let Some((task, setup)) = last.as_ref()
{
Self::teardown(ctx, task, setup, None, &mut recorder).await;
}
}
}
recorder
}
async fn drive_rounds(
&self,
ctx: &S::Ctx,
setup: &S::Setup,
recorder: &mut Recorder,
wait: &mut Duration,
) {
let mut budget = RoundBudget::new(self.config.mode);
let mut round = 0usize;
while budget.has_next() {
if self.is_cancelled() {
recorder.record_interrupted();
return;
}
let task = TaskIndex::new(self.config.task_index, self.config.task_total, round);
round += 1;
let start = Instant::now();
if self.round(ctx, &task, setup, recorder, wait).await {
recorder.record_interrupted();
return;
}
budget.spend(start.elapsed());
}
}
fn backoff_initial(backoff: Option<BackoffConfig>) -> Duration {
backoff.map(|b| b.initial).unwrap_or(Duration::ZERO)
}
async fn setup_retrying(
&self,
ctx: &S::Ctx,
task: &TaskIndex,
recorder: &mut Recorder,
wait: &mut Duration,
) -> SetupDone<S::Setup> {
let Some(cfg) = self.config.backoff else {
let start = Instant::now();
let ret = S::setup(ctx, task).await;
recorder.record_setup_duration(start.elapsed());
return match ret {
Ok(setup) => SetupDone::Ready(setup),
Err(err) => {
recorder.record_result(&Err::<(), S::Error>(err));
SetupDone::Failed
}
};
};
loop {
let start = Instant::now();
let ret = S::setup(ctx, task).await;
recorder.record_setup_duration(start.elapsed());
match ret {
Ok(setup) => {
if *wait != cfg.initial {
*wait = cfg.initial;
}
return SetupDone::Ready(setup);
}
Err(err) => {
let timed_out = err.is_timeout();
recorder.record_result(&Err::<(), S::Error>(err));
if !timed_out {
return SetupDone::Failed;
}
if self.wait_or_cancel(*wait).await {
return SetupDone::Cancelled;
}
let next = wait.as_secs_f64() * cfg.factor;
*wait = Duration::from_secs_f64(next.min(cfg.max.as_secs_f64()));
*wait = (*wait).max(cfg.initial);
}
}
}
}
async fn round(
&self,
ctx: &S::Ctx,
task: &TaskIndex,
setup: &S::Setup,
recorder: &mut Recorder,
wait: &mut Duration,
) -> bool {
let result = Self::once(ctx, task, setup, recorder).await;
let timed_out = result.as_ref().is_err_and(|e| e.is_timeout());
if let Ok(output) = &result {
Self::validate(ctx, task, setup, output, recorder).await;
}
if S::TEARDOWN_MODE == TeardownMode::Round {
Self::teardown(ctx, task, setup, Some(result.as_ref()), recorder).await;
}
let Some(cfg) = self.config.backoff else {
return false;
};
if timed_out {
if self.wait_or_cancel(*wait).await {
return true;
}
let next = wait.as_secs_f64() * cfg.factor;
*wait = Duration::from_secs_f64(next.min(cfg.max.as_secs_f64()));
*wait = (*wait).max(cfg.initial);
} else if *wait != cfg.initial {
*wait = cfg.initial;
}
false
}
async fn wait_or_cancel(&self, duration: Duration) -> bool {
match self.config.shutdown.as_ref() {
Some(s) => tokio::select! {
_ = tokio::time::sleep(duration) => false,
_ = s.wait_cancelled() => true,
},
None => {
tokio::time::sleep(duration).await;
false
}
}
}
fn is_cancelled(&self) -> bool {
self.config
.shutdown
.as_ref()
.is_some_and(|s| s.is_cancelled())
}
async fn once(
ctx: &S::Ctx,
task: &TaskIndex,
setup: &S::Setup,
recorder: &mut Recorder,
) -> Result<S::Output, S::Error> {
let start = Instant::now();
#[cfg(feature = "tui")]
recorder.begin_round();
let result = S::run(ctx, task, setup).await;
#[cfg(feature = "tui")]
recorder.end_round();
recorder.record_duration(start.elapsed());
recorder.record_result(&result);
result
}
async fn validate(
ctx: &S::Ctx,
task: &TaskIndex,
setup: &S::Setup,
output: &S::Output,
recorder: &mut Recorder,
) {
let start = Instant::now();
let ret = S::validate(ctx, task, setup, output).await;
recorder.record_validate_duration(start.elapsed());
match ret {
Ok(true) => {
recorder.record_validate(true);
}
Ok(false) => {
recorder.record_validate_failure(Cow::Borrowed("validate"));
}
Err(err) => {
recorder.log_internal(format!("{err:?}"));
recorder.record_validate_failure_with_status(err.kind(), err.status_code());
}
}
}
async fn teardown(
ctx: &S::Ctx,
task: &TaskIndex,
setup: &S::Setup,
result: Option<Result<&S::Output, &S::Error>>,
recorder: &mut Recorder,
) {
let start = Instant::now();
let ret = S::teardown(ctx, task, setup, result).await;
recorder.record_teardown_duration(start.elapsed());
match ret {
Ok(()) => recorder.record_teardown(true),
Err(err) => {
recorder.log_internal(format!("{err:?}"));
recorder.record_teardown(false);
recorder.record_teardown_error_with_status(err.kind(), err.status_code());
}
}
}
}