use crate::goal::GoalDriver;
use crate::schedule_tick::{ScheduleTicker, SystemTickClock, TickClock, TickObserver};
use crate::schedules::SchedulesModule;
use crate::tasks::TaskHost;
use kernel::{HostHandler, Signal};
use serde_json::{Map, Value};
use std::sync::{Arc, Mutex};
pub struct DurableWorkOptions {
pub tasks: Arc<dyn TaskHost>,
pub schedules: Option<Arc<SchedulesModule>>,
pub goal: Option<Arc<GoalDriver>>,
pub jobs: Option<Arc<host::Host>>,
pub clock: Arc<dyn TickClock>,
pub on_tick: Option<TickObserver>,
}
impl DurableWorkOptions {
pub fn new(tasks: Arc<dyn TaskHost>) -> DurableWorkOptions {
DurableWorkOptions {
tasks,
schedules: None,
goal: None,
jobs: None,
clock: Arc::new(SystemTickClock),
on_tick: None,
}
}
pub fn schedules(mut self, schedules: Arc<SchedulesModule>) -> Self {
self.schedules = Some(schedules);
self
}
pub fn goal(mut self, goal: Arc<GoalDriver>) -> Self {
self.goal = Some(goal);
self
}
pub fn jobs(mut self, jobs: Arc<host::Host>) -> Self {
self.jobs = Some(jobs);
self
}
pub fn clock(mut self, clock: Arc<dyn TickClock>) -> Self {
self.clock = clock;
self
}
pub fn on_tick(mut self, observer: TickObserver) -> Self {
self.on_tick = Some(observer);
self
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Recovered {
pub goal: Option<Value>,
pub next_fire: Option<i64>,
pub jobs: Vec<Value>,
}
pub struct DurableWork {
ticker: Mutex<Option<ScheduleTicker>>,
goal: Option<Arc<GoalDriver>>,
jobs: Option<Arc<host::Host>>,
recovered: Recovered,
}
impl DurableWork {
pub fn open(options: DurableWorkOptions) -> Result<DurableWork, String> {
let mut next_fire = None;
if let Some(schedules) = &options.schedules {
schedules.start(options.tasks.as_ref())?;
next_fire = schedules.next_fire()?;
}
let goal = match &options.goal {
Some(driver) => driver.recover()?,
None => None,
};
let jobs = match &options.jobs {
Some(host) => host
.handle("shell.list", Map::new(), &Signal::new())?
.as_array()
.cloned()
.unwrap_or_default(),
None => Vec::new(),
};
let ticker = options
.schedules
.map(|schedules| ScheduleTicker::start(schedules, options.tasks, options.clock, options.on_tick));
Ok(DurableWork {
ticker: Mutex::new(ticker),
goal: options.goal,
jobs: options.jobs,
recovered: Recovered { goal, next_fire, jobs },
})
}
pub fn recovered(&self) -> &Recovered {
&self.recovered
}
pub fn wake(&self) {
if let Some(ticker) = jsrt::sync::lock(&self.ticker).as_ref() {
ticker.wake();
}
}
fn stop(&self) {
let ticker = jsrt::sync::lock(&self.ticker).take();
if let Some(ticker) = ticker {
ticker.close();
}
if let Some(goal) = &self.goal {
goal.close();
}
}
pub fn close(&self) {
self.stop();
if let Some(jobs) = &self.jobs {
jobs.stop_jobs();
}
}
pub fn hand_over(&self) {
self.stop();
if let Some(jobs) = &self.jobs {
jobs.release_jobs();
}
}
}
impl Drop for DurableWork {
fn drop(&mut self) {
self.stop();
}
}