use std::cmp::Reverse;
use std::collections::BinaryHeap;
use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant};
use super::error::report_fault;
use super::mailbox::{Mailbox, WaitEpoch};
use super::process::{Flow, FlowId};
use super::sync_lock;
enum TimerPayload {
WakeSleeper(Box<Flow>),
WakeReceiver {
pid: FlowId,
mailbox: Arc<Mailbox>,
dest_reg: u8,
epoch: WaitEpoch,
},
}
struct TimerEntry {
deadline: Instant,
payload: TimerPayload,
}
impl PartialEq for TimerEntry {
fn eq(&self, other: &Self) -> bool {
self.deadline == other.deadline
}
}
impl Eq for TimerEntry {}
impl PartialOrd for TimerEntry {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for TimerEntry {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.deadline.cmp(&other.deadline)
}
}
pub struct TimerWheel {
heap: Mutex<BinaryHeap<Reverse<TimerEntry>>>,
cvar: Condvar,
shutdown: Mutex<bool>,
}
fn deadline_from_now(delay: Duration) -> Instant {
Instant::now()
.checked_add(delay)
.or_else(|| Instant::now().checked_add(Duration::from_secs(60 * 60 * 24 * 365 * 30)))
.unwrap_or_else(Instant::now)
}
impl TimerWheel {
pub fn new() -> Arc<Self> {
Arc::new(TimerWheel {
heap: Mutex::new(BinaryHeap::new()),
cvar: Condvar::new(),
shutdown: Mutex::new(false),
})
}
pub fn schedule_sleep(&self, delay: Duration, flow: Box<Flow>) {
let entry = TimerEntry {
deadline: deadline_from_now(delay),
payload: TimerPayload::WakeSleeper(flow),
};
self.push(entry);
}
pub fn schedule_receive_timeout(
&self,
delay: Duration,
pid: FlowId,
mailbox: Arc<Mailbox>,
dest_reg: u8,
epoch: WaitEpoch,
) {
let entry = TimerEntry {
deadline: deadline_from_now(delay),
payload: TimerPayload::WakeReceiver {
pid,
mailbox,
dest_reg,
epoch,
},
};
self.push(entry);
}
fn push(&self, entry: TimerEntry) {
match sync_lock::lock(&self.heap, "TimerWheel::push") {
Ok(mut heap) => {
heap.push(Reverse(entry));
self.cvar.notify_one();
}
Err(e) => report_fault(e),
}
}
pub fn shutdown(&self) {
match sync_lock::lock(&self.shutdown, "TimerWheel::shutdown") {
Ok(mut flag) => *flag = true,
Err(e) => report_fault(e),
}
self.cvar.notify_all();
}
pub(crate) fn drain(&self) -> Vec<Box<Flow>> {
let mut flows = Vec::new();
match sync_lock::lock(&self.heap, "TimerWheel::drain") {
Ok(mut heap) => {
while let Some(Reverse(entry)) = heap.pop() {
if let TimerPayload::WakeSleeper(flow) = entry.payload {
flows.push(flow);
}
}
}
Err(e) => report_fault(e),
}
flows
}
pub fn drive(self: &Arc<Self>, shared: &super::runtime::Shared) {
loop {
let mut heap = match sync_lock::lock(&self.heap, "TimerWheel::drive") {
Ok(h) => h,
Err(e) => {
report_fault(e);
return;
}
};
let shutting_down = match sync_lock::lock(&self.shutdown, "TimerWheel::drive/shutdown")
{
Ok(g) => *g,
Err(e) => {
report_fault(e);
return;
}
};
if shutting_down {
return;
}
match heap.peek() {
None => {
match sync_lock::wait_timeout(
&self.cvar,
heap,
Duration::from_millis(250),
"TimerWheel::idle",
) {
Ok((guard, _)) => {
drop(guard);
}
Err(e) => {
report_fault(e);
return;
}
}
}
Some(Reverse(top)) => {
let now = Instant::now();
if top.deadline <= now {
let Reverse(entry) = match heap.pop() {
Some(e) => e,
None => continue,
};
drop(heap);
self.fire(entry, shared);
} else {
let wait_for = top.deadline - now;
match sync_lock::wait_timeout(
&self.cvar,
heap,
wait_for,
"TimerWheel::wait",
) {
Ok((guard, _)) => drop(guard),
Err(e) => {
report_fault(e);
return;
}
}
}
}
}
}
}
fn fire(&self, entry: TimerEntry, shared: &super::runtime::Shared) {
match entry.payload {
TimerPayload::WakeSleeper(flow) => {
shared.injector.push(flow);
}
TimerPayload::WakeReceiver {
pid,
mailbox,
dest_reg,
epoch,
} => {
match mailbox.take_parked_at(epoch) {
Ok(Some(flow)) => {
debug_assert_eq!(
flow.id, pid,
"timer fired for a mailbox owned by a different flow"
);
if let Err(e) = shared.ask_waits.remove_asker(flow.id) {
report_fault(e);
}
if let Some(flow) = super::finalize::resume_or_fail(
shared,
flow,
dest_reg,
crate::bytecode::Value::Unit,
) {
shared.injector.push(flow);
}
}
Ok(None) => {
}
Err(e) => report_fault(e),
}
}
}
match sync_lock::lock(&shared.notify.0, "TimerWheel::fire/notify") {
Ok(_guard) => shared.notify.1.notify_all(),
Err(e) => report_fault(e),
}
}
}