use std::fmt;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::watch;
use tokio_util::sync::CancellationToken;
use tracing::trace;
use crate::common::clock::{Clock, Timer};
use crate::common::types::ActorSender;
use crate::message::OutboundEnvelope;
use crate::traits::ActonMessage;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FireAt(Instant);
impl FireAt {
#[must_use]
pub fn after(now: Instant, delay: Duration) -> Self {
if let Some(deadline) = now.checked_add(delay) {
return Self(deadline);
}
let mut delay = delay;
loop {
delay /= 2;
if delay.is_zero() {
return Self(now);
}
if let Some(deadline) = now.checked_add(delay) {
return Self(deadline);
}
}
}
#[must_use]
pub const fn at(deadline: Instant) -> Self {
Self(deadline)
}
#[must_use]
pub const fn instant(self) -> Instant {
self.0
}
#[must_use]
pub fn remaining_from(self, now: Instant) -> Duration {
self.0.saturating_duration_since(now)
}
#[must_use]
pub fn is_due_at(self, now: Instant) -> bool {
now >= self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Interval(Duration);
impl Interval {
#[must_use]
pub const fn new(period: Duration) -> Option<Self> {
if period.is_zero() {
None
} else {
Some(Self(period))
}
}
#[must_use]
pub const fn from_secs(secs: u64) -> Option<Self> {
Self::new(Duration::from_secs(secs))
}
#[must_use]
pub const fn from_millis(millis: u64) -> Option<Self> {
Self::new(Duration::from_millis(millis))
}
#[must_use]
pub const fn get(self) -> Duration {
self.0
}
}
impl TryFrom<Duration> for Interval {
type Error = ZeroInterval;
fn try_from(period: Duration) -> Result<Self, Self::Error> {
Self::new(period).ok_or(ZeroInterval)
}
}
impl From<Interval> for Duration {
fn from(interval: Interval) -> Self {
interval.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ZeroInterval;
impl fmt::Display for ZeroInterval {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"a repeating interval must be greater than zero; a zero interval is a spin loop, \
not a schedule"
)
}
}
impl std::error::Error for ZeroInterval {}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Cadence {
FixedRate,
FixedDelay,
}
#[must_use]
pub fn next_fixed_rate(armed_at: Instant, interval: Interval, now: Instant) -> FireAt {
let elapsed = now.saturating_duration_since(armed_at).as_nanos();
let step = interval.get().as_nanos();
let ticks = elapsed / step + 1;
let offset_nanos = ticks.saturating_mul(step);
let seconds = offset_nanos / 1_000_000_000;
let remainder = offset_nanos % 1_000_000_000;
let offset = u64::try_from(seconds).map_or(Duration::MAX, |seconds| {
Duration::new(seconds, u32::try_from(remainder).unwrap_or(0))
});
FireAt::after(armed_at, offset)
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ScheduledSendOutcome {
Delivered,
Cancelled,
Abandoned,
Undeliverable {
detail: String,
},
}
#[derive(Debug, Clone)]
struct Progress {
deliveries: u64,
due: Option<FireAt>,
settled: Option<ScheduledSendOutcome>,
}
#[derive(Debug, Clone)]
pub struct ScheduledSend {
cancel: CancellationToken,
progress: watch::Receiver<Progress>,
}
impl ScheduledSend {
#[must_use]
pub fn due_at(&self) -> Option<FireAt> {
self.progress.borrow().due
}
#[must_use]
pub fn deliveries(&self) -> u64 {
self.progress.borrow().deliveries
}
#[must_use]
pub fn settled(&self) -> Option<ScheduledSendOutcome> {
self.progress.borrow().settled.clone()
}
#[must_use]
pub fn is_settled(&self) -> bool {
self.progress.borrow().settled.is_some()
}
pub fn cancel(&self) {
self.cancel.cancel();
}
pub async fn outcome(&self) -> ScheduledSendOutcome {
let mut observer = self.progress.clone();
loop {
{
let progress = observer.borrow_and_update();
if let Some(outcome) = progress.settled.clone() {
return outcome;
}
}
if observer.changed().await.is_err() {
return ScheduledSendOutcome::Abandoned;
}
}
}
pub async fn wait_for_deliveries(&self, at_least: u64) -> u64 {
let mut observer = self.progress.clone();
loop {
{
let progress = observer.borrow_and_update();
if progress.deliveries >= at_least || progress.settled.is_some() {
return progress.deliveries;
}
}
if observer.changed().await.is_err() {
return observer.borrow().deliveries;
}
}
}
}
#[derive(Debug, Clone, Copy)]
pub enum Plan {
Once(FireAt),
Repeat {
armed_at: Instant,
interval: Interval,
cadence: Cadence,
},
}
impl Plan {
fn first_deadline(self) -> FireAt {
match self {
Self::Once(due) => due,
Self::Repeat {
armed_at, interval, ..
} => next_fixed_rate(armed_at, interval, armed_at),
}
}
fn deadline_after_tick(self, now: Instant) -> Option<FireAt> {
match self {
Self::Once(_) => None,
Self::Repeat {
armed_at,
interval,
cadence,
} => Some(match cadence {
Cadence::FixedRate => next_fixed_rate(armed_at, interval, now),
Cadence::FixedDelay => FireAt::after(now, interval.get()),
}),
}
}
}
pub struct Schedule {
pub clock: Arc<dyn Clock>,
pub envelope: OutboundEnvelope,
pub outbox: ActorSender,
pub message: Box<dyn ActonMessage + Send + Sync>,
pub plan: Plan,
}
pub fn arm(schedule: Schedule) -> ScheduledSend {
let cancel = CancellationToken::new();
let first = schedule.plan.first_deadline();
let armed = schedule.clock.timer(first.instant());
let (progress, observer) = watch::channel(Progress {
deliveries: 0,
due: Some(first),
settled: None,
});
let handle = ScheduledSend {
cancel: cancel.clone(),
progress: observer,
};
tokio::spawn(run(schedule, armed, cancel, progress));
handle
}
async fn run(
schedule: Schedule,
armed: Timer,
cancel: CancellationToken,
progress: watch::Sender<Progress>,
) {
let Schedule {
clock,
envelope,
outbox,
message,
plan,
} = schedule;
let mut timer = armed;
loop {
let outcome = tokio::select! {
() = cancel.cancelled() => Some(ScheduledSendOutcome::Cancelled),
() = outbox.closed() => Some(ScheduledSendOutcome::Abandoned),
() = &mut timer => {
match deliver(&envelope, message.as_ref()).await {
Ok(()) => None,
Err(detail) => Some(ScheduledSendOutcome::Undeliverable { detail }),
}
}
};
if let Some(outcome) = outcome {
trace!(?outcome, "scheduled send settled");
progress.send_modify(|state| {
state.due = None;
state.settled = Some(outcome);
});
return;
}
let next = plan.deadline_after_tick(clock.now());
progress.send_modify(|state| {
state.deliveries += 1;
state.due = next;
if next.is_none() {
state.settled = Some(ScheduledSendOutcome::Delivered);
}
});
let Some(next) = next else {
return;
};
timer = clock.timer(next.instant());
}
}
async fn deliver(
envelope: &OutboundEnvelope,
message: &(dyn ActonMessage + Send + Sync),
) -> Result<(), String> {
let copy: Box<dyn ActonMessage + Send + Sync> = dyn_clone::clone_box(message);
envelope
.try_send_dyn(Arc::from(copy))
.await
.map_err(|error| error.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
const SECOND: Duration = Duration::from_secs(1);
fn interval(secs: u64) -> Interval {
Interval::from_secs(secs).expect("a non-zero interval")
}
#[test]
fn a_zero_delay_is_due_immediately() {
let now = Instant::now();
let due = FireAt::after(now, Duration::ZERO);
assert!(due.is_due_at(now));
assert_eq!(due.remaining_from(now), Duration::ZERO);
}
#[test]
fn a_deadline_reached_exactly_is_due() {
let now = Instant::now();
let due = FireAt::after(now, SECOND);
assert!(!due.is_due_at(now), "not due a second early");
assert!(due.is_due_at(now + SECOND), "due exactly on time");
}
#[test]
fn a_past_deadline_has_no_time_remaining() {
let now = Instant::now();
let due = FireAt::at(
now.checked_sub(Duration::from_mins(1))
.expect("a minute ago"),
);
assert_eq!(due.remaining_from(now), Duration::ZERO);
}
#[test]
fn remaining_is_exact_for_a_future_deadline() {
let now = Instant::now();
let due = FireAt::after(now, Duration::from_secs(30));
assert_eq!(due.remaining_from(now), Duration::from_secs(30));
}
#[test]
fn an_unrepresentable_delay_saturates_into_the_future() {
let now = Instant::now();
let due = FireAt::after(now, Duration::MAX);
assert!(
!due.is_due_at(now + Duration::from_hours(24 * 365)),
"an overflowing delay must land far in the future, not in the past"
);
}
#[test]
fn at_round_trips_through_instant() {
let now = Instant::now();
assert_eq!(FireAt::at(now).instant(), now);
}
#[test]
fn deadlines_order_by_time() {
let now = Instant::now();
let sooner = FireAt::after(now, SECOND);
let later = FireAt::after(now, Duration::from_secs(2));
assert!(sooner < later);
}
#[test]
fn a_zero_interval_cannot_be_built() {
assert_eq!(Interval::new(Duration::ZERO), None);
assert_eq!(Interval::from_secs(0), None);
assert_eq!(Interval::from_millis(0), None);
assert_eq!(Interval::try_from(Duration::ZERO), Err(ZeroInterval));
}
#[test]
fn a_non_zero_interval_keeps_its_period() {
let interval = Interval::try_from(SECOND).expect("one second is not zero");
assert_eq!(interval.get(), SECOND);
assert_eq!(Duration::from(interval), SECOND);
}
#[test]
fn the_zero_interval_error_describes_itself() {
assert!(!ZeroInterval.to_string().is_empty());
}
#[test]
fn the_first_tick_is_one_whole_interval_out() {
let armed_at = Instant::now();
let first = next_fixed_rate(armed_at, interval(5), armed_at);
assert_eq!(first.instant(), armed_at + Duration::from_secs(5));
}
#[test]
fn a_deadline_landed_on_exactly_advances_to_the_next() {
let armed_at = Instant::now();
let now = armed_at + Duration::from_secs(5);
let next = next_fixed_rate(armed_at, interval(5), now);
assert_eq!(next.instant(), armed_at + Duration::from_secs(10));
}
#[test]
fn missed_intervals_are_skipped_rather_than_queued() {
let armed_at = Instant::now();
let now = armed_at + Duration::from_secs(25);
let next = next_fixed_rate(armed_at, interval(10), now);
assert_eq!(
next.instant(),
armed_at + Duration::from_secs(30),
"roll forward to the first future grid point"
);
}
#[test]
fn the_next_deadline_is_always_strictly_in_the_future() {
let armed_at = Instant::now();
let step = interval(3);
for elapsed_secs in 0..40_u64 {
let now = armed_at + Duration::from_secs(elapsed_secs);
let next = next_fixed_rate(armed_at, step, now);
assert!(
next.instant() > now,
"a deadline at or before `now` would spin (elapsed {elapsed_secs}s)"
);
}
}
#[test]
fn deadlines_stay_on_the_grid_however_late() {
let armed_at = Instant::now();
let step = interval(4);
for elapsed_secs in 0..40_u64 {
let now = armed_at + Duration::from_secs(elapsed_secs);
let offset = next_fixed_rate(armed_at, step, now)
.instant()
.duration_since(armed_at);
assert_eq!(
offset.as_secs() % 4,
0,
"every fixed-rate deadline is a whole number of intervals from arming"
);
}
}
#[test]
fn an_enormous_elapsed_time_saturates_into_the_future() {
let armed_at = Instant::now();
let now = armed_at + Duration::from_hours(24 * 365 * 100);
let next = next_fixed_rate(
armed_at,
Interval::new(Duration::from_nanos(1)).unwrap(),
now,
);
assert!(
next.instant() > now,
"saturation must not produce a deadline in the past"
);
}
#[test]
fn a_one_shot_plan_has_no_deadline_after_its_tick() {
let now = Instant::now();
let plan = Plan::Once(FireAt::after(now, SECOND));
assert_eq!(plan.first_deadline().instant(), now + SECOND);
assert!(plan.deadline_after_tick(now + SECOND).is_none());
}
#[test]
fn both_cadences_start_one_interval_after_arming() {
let armed_at = Instant::now();
for cadence in [Cadence::FixedRate, Cadence::FixedDelay] {
let plan = Plan::Repeat {
armed_at,
interval: interval(10),
cadence,
};
assert_eq!(
plan.first_deadline().instant(),
armed_at + Duration::from_secs(10),
"{cadence:?} must wait one whole interval for its first tick"
);
}
}
#[test]
fn a_late_tick_separates_the_two_cadences() {
let armed_at = Instant::now();
let late = armed_at + Duration::from_secs(25);
let fixed_rate = Plan::Repeat {
armed_at,
interval: interval(10),
cadence: Cadence::FixedRate,
}
.deadline_after_tick(late)
.expect("a repeating plan always has a next deadline");
let fixed_delay = Plan::Repeat {
armed_at,
interval: interval(10),
cadence: Cadence::FixedDelay,
}
.deadline_after_tick(late)
.expect("a repeating plan always has a next deadline");
assert_eq!(
fixed_rate.instant(),
armed_at + Duration::from_secs(30),
"fixed-rate returns to the grid"
);
assert_eq!(
fixed_delay.instant(),
armed_at + Duration::from_secs(35),
"fixed-delay measures the interval from when the send finished"
);
}
#[test]
fn cancellation_and_abandonment_are_different_outcomes() {
assert_ne!(
ScheduledSendOutcome::Cancelled,
ScheduledSendOutcome::Abandoned
);
}
}