use crate::schedules::SchedulesModule;
use crate::tasks::TaskHost;
use serde_json::Value;
use std::sync::atomic::{AtomicI64, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::thread::JoinHandle;
use std::time::Duration;
pub const RETRY_MS: i64 = 1000;
pub trait TickClock: Send + Sync {
fn now(&self) -> i64;
fn wait_limit(&self, deadline: i64) -> Option<Duration>;
}
pub struct SystemTickClock;
impl TickClock for SystemTickClock {
fn now(&self) -> i64 {
(crate::util::system_clock())()
}
fn wait_limit(&self, deadline: i64) -> Option<Duration> {
Some(Duration::from_millis(deadline.saturating_sub(self.now()).max(0) as u64))
}
}
pub struct ManualTickClock {
now: AtomicI64,
}
impl ManualTickClock {
pub fn new(now: i64) -> Arc<ManualTickClock> {
Arc::new(ManualTickClock {
now: AtomicI64::new(now),
})
}
pub fn set(&self, now: i64) {
self.now.store(now, Ordering::SeqCst);
}
pub fn advance(&self, ms: i64) -> i64 {
self.now.fetch_add(ms, Ordering::SeqCst) + ms
}
pub fn as_clock(self: &Arc<Self>) -> crate::util::Clock {
let clock = self.clone();
Arc::new(move || clock.now())
}
}
impl TickClock for ManualTickClock {
fn now(&self) -> i64 {
self.now.load(Ordering::SeqCst)
}
fn wait_limit(&self, _deadline: i64) -> Option<Duration> {
None
}
}
pub type TickObserver = Arc<dyn Fn(&Result<Value, String>) + Send + Sync>;
#[derive(Default)]
struct Flags {
woken: bool,
closed: bool,
}
struct Shared {
flags: Mutex<Flags>,
bell: Condvar,
}
impl Shared {
fn wake(&self) {
jsrt::sync::lock(&self.flags).woken = true;
self.bell.notify_all();
}
}
pub struct ScheduleTicker {
shared: Arc<Shared>,
module: Arc<SchedulesModule>,
thread: Mutex<Option<JoinHandle<()>>>,
}
impl ScheduleTicker {
pub fn start(
module: Arc<SchedulesModule>,
host: Arc<dyn TaskHost>,
clock: Arc<dyn TickClock>,
observer: Option<TickObserver>,
) -> ScheduleTicker {
let shared = Arc::new(Shared {
flags: Mutex::default(),
bell: Condvar::new(),
});
let waker = shared.clone();
module.on_change(Some(Arc::new(move || waker.wake())));
let (thread_shared, thread_module) = (shared.clone(), module.clone());
let thread = std::thread::Builder::new()
.name("ultron-schedule-tick".into())
.spawn(move || run(&thread_shared, &thread_module, host.as_ref(), clock.as_ref(), observer))
.ok();
ScheduleTicker {
shared,
module,
thread: Mutex::new(thread),
}
}
pub fn wake(&self) {
self.shared.wake();
}
pub fn close(&self) {
jsrt::sync::lock(&self.shared.flags).closed = true;
self.shared.bell.notify_all();
self.module.on_change(None);
let thread = jsrt::sync::lock(&self.thread).take();
if let Some(thread) = thread {
let _ = thread.join();
}
}
}
impl Drop for ScheduleTicker {
fn drop(&mut self) {
self.close();
}
}
fn run(
shared: &Shared,
module: &SchedulesModule,
host: &dyn TaskHost,
clock: &dyn TickClock,
observer: Option<TickObserver>,
) {
loop {
if jsrt::sync::lock(&shared.flags).closed {
return;
}
let deadline = match module.next_fire() {
Ok(Some(next)) if next <= clock.now() => {
let report = module.tick(host);
let settled = report.as_ref().is_ok_and(|report| {
["fired", "failed"]
.iter()
.any(|key| report[*key].as_array().is_some_and(|items| !items.is_empty()))
});
if let Some(observer) = &observer {
observer(&report);
}
if settled {
continue;
}
Some(clock.now().saturating_add(RETRY_MS))
}
Ok(next) => next,
Err(_) => Some(clock.now().saturating_add(RETRY_MS)),
};
let mut flags = jsrt::sync::lock(&shared.flags);
while !flags.woken && !flags.closed {
let limit = deadline.map(|deadline| clock.wait_limit(deadline));
match limit {
None | Some(None) => {
flags = shared
.bell
.wait(flags)
.unwrap_or_else(std::sync::PoisonError::into_inner);
}
Some(Some(limit)) if limit.is_zero() => break,
Some(Some(limit)) => {
flags = shared
.bell
.wait_timeout(flags, limit)
.unwrap_or_else(std::sync::PoisonError::into_inner)
.0;
}
}
}
flags.woken = false;
}
}