use std::thread;
use log::info;
use crate::core::job::now_time;
use crate::core::step::{mount_step_status, StepStatus, throw_tolerant_exception};
pub mod complex_step;
pub mod simple_step;
pub mod step_builder;
pub trait Runner
where
Self: Sized,
{
type Output;
fn run(self) -> Self::Output;
}
pub trait Decider {
fn is_run(&self) -> bool;
}
pub type StepCallback = Box<dyn FnOnce() + Send>;
pub type DeciderCallback = Box<dyn Fn() -> bool>;
pub struct SyncStep {
#[allow(dead_code)]
pub(crate) start_time: Option<u64>,
#[allow(dead_code)]
pub(crate) end_time: Option<u64>,
pub name: String,
pub throw_tolerant: Option<bool>,
pub(crate) decider: Option<DeciderCallback>,
pub(crate) callback: Option<Box<dyn FnOnce() -> () + Send>>,
}
impl Runner for SyncStep {
type Output = StepStatus;
fn run(self) -> Self::Output {
return match self.callback {
None => {
throw_tolerant_exception(self.throw_tolerant.unwrap_or(false), self.name)
}
Some(callback) => {
info!("Step {} is running", self.name);
let task = thread::spawn(move || {
callback();
});
let task_result = task.join();
let start_time = now_time();
return match task_result {
Ok(_) => {
let message = format!("Step {} executed successfully", self.name);
info!("{}", message);
mount_step_status(self.name, Ok(message), start_time)
}
Err(_) => {
let message = format!("Step {} failed to execute", self.name);
info!("{}", message);
mount_step_status(self.name, Err(message), start_time)
}
};
}
};
}
}
impl Decider for SyncStep {
fn is_run(&self) -> bool {
return match &self.decider {
None => true,
Some(decider) => decider(),
};
}
}
unsafe impl Send for SyncStep {}