use std::time::Instant;
use smol_bytes::Utf8Bytes;
use crate::{Timestamp, drive::generations::RunId};
#[cfg(test)]
mod tests;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Stamp {
monotonic: Instant,
wall: Timestamp,
run: RunId,
}
impl Stamp {
#[inline]
#[must_use]
pub const fn new(monotonic: Instant, wall: Timestamp, run: RunId) -> Self {
Self {
monotonic,
wall,
run,
}
}
#[inline]
#[must_use]
pub fn now() -> Self {
Self {
monotonic: Instant::now(),
wall: Timestamp::from(jiff::Timestamp::now()),
run: RunId::mint(),
}
}
#[inline]
#[must_use]
pub const fn monotonic(&self) -> Instant {
self.monotonic
}
#[inline]
#[must_use]
pub const fn wall(&self) -> Timestamp {
self.wall
}
#[inline]
#[must_use]
pub const fn run(&self) -> RunId {
self.run
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum RetireOrigin {
Vanished,
User,
Other(Utf8Bytes),
}
impl RetireOrigin {
pub const VANISHED: &'static str = "vanished";
pub const USER: &'static str = "user";
#[inline]
#[must_use]
pub const fn restores_itself(&self) -> bool {
matches!(self, Self::Vanished)
}
#[inline]
#[must_use]
pub const fn outranks(&self, other: &Self) -> bool {
!self.restores_itself() && other.restores_itself()
}
#[inline]
#[must_use]
pub fn as_str(&self) -> &str {
match self {
Self::Vanished => Self::VANISHED,
Self::User => Self::USER,
Self::Other(word) => word.as_str(),
}
}
}
impl<T> From<T> for RetireOrigin
where
T: Into<Utf8Bytes>,
{
fn from(word: T) -> Self {
let word = word.into();
match word.as_str() {
Self::VANISHED => Self::Vanished,
Self::USER => Self::User,
_ => Self::Other(word),
}
}
}
impl core::fmt::Display for RetireOrigin {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RootState {
Idle,
Analyzing {
inflight: u32,
since: Instant,
},
Retiring {
inflight: u32,
since: Instant,
},
Retired {
at: Timestamp,
origin: RetireOrigin,
late_tails: bool,
},
Restoring,
}
impl RootState {
#[inline]
#[must_use]
pub const fn is_busy(&self) -> bool {
matches!(self, Self::Retiring { .. } | Self::Restoring)
}
#[inline]
#[must_use]
pub const fn inflight(&self) -> u32 {
match self {
Self::Analyzing { inflight, .. } | Self::Retiring { inflight, .. } => *inflight,
Self::Idle | Self::Retired { .. } | Self::Restoring => 0,
}
}
#[inline]
#[must_use]
pub const fn has_late_tails(&self) -> bool {
matches!(
self,
Self::Retired {
late_tails: true,
..
}
)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum RootAction {
Intake,
Dispatched,
Observed,
Retire(RetireOrigin),
Restore,
Reappear,
Restored,
Lapsed,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[must_use = "an ignored answer hides a refused action and a queued one alike"]
pub enum RootAdvance {
Moved,
Unchanged,
Queued,
Coalesced,
Declined,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[must_use = "a dropped act leaves the ledger disagreeing with the registry"]
pub enum Retirement {
Recorded {
at: Timestamp,
origin: RetireOrigin,
late_tails: bool,
},
Erased,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[must_use = "a dropped flip leaves the closure reading the generation this run replaced"]
pub struct Flip {
run: RunId,
at: Timestamp,
}
impl Flip {
#[inline]
pub const fn new(run: RunId, at: Timestamp) -> Self {
Self { run, at }
}
#[inline]
#[must_use]
pub const fn run(&self) -> RunId {
self.run
}
#[inline]
#[must_use]
pub const fn at(&self) -> Timestamp {
self.at
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Entry {
state: RootState,
retiring_as: Option<RetireOrigin>,
refused_dispatch: bool,
running_as: Option<RunId>,
queued: Vec<RootAction>,
}
impl Entry {
#[inline]
pub(super) fn idle() -> Self {
Self {
state: RootState::Idle,
retiring_as: None,
refused_dispatch: false,
running_as: None,
queued: Vec::new(),
}
}
#[inline]
pub(super) fn rebuilt(at: Timestamp, origin: RetireOrigin, late_tails: bool) -> Self {
Self {
state: RootState::Retired {
at,
origin,
late_tails,
},
retiring_as: None,
refused_dispatch: false,
running_as: None,
queued: Vec::new(),
}
}
#[inline]
pub(super) fn state(&self) -> RootState {
self.state.clone()
}
#[inline]
pub(super) const fn state_ref(&self) -> &RootState {
&self.state
}
#[cfg(test)]
pub(super) fn queued(&self) -> &[RootAction] {
&self.queued
}
#[cfg(test)]
pub(super) fn retiring_as(&self) -> Option<RetireOrigin> {
self.retiring_as.clone()
}
#[cfg(test)]
pub(super) const fn running_as(&self) -> Option<RunId> {
self.running_as
}
#[inline]
pub(super) fn is_vacant(&self) -> bool {
matches!(self.state, RootState::Idle)
&& self.queued.is_empty()
&& self.retiring_as.is_none()
&& self.running_as.is_none()
&& !self.refused_dispatch
}
pub(super) fn advance(
&mut self,
action: RootAction,
stamp: Stamp,
owed: &mut dyn FnMut(Retirement),
turned: &mut dyn FnMut(Flip),
) -> RootAdvance {
let advance = if self.state.is_busy() {
self.busy(action, stamp, owed)
} else {
self.apply(action, stamp, owed, turned)
};
self.drain(stamp, owed, turned);
advance
}
fn busy(
&mut self,
action: RootAction,
stamp: Stamp,
owed: &mut dyn FnMut(Retirement),
) -> RootAdvance {
match (self.state.clone(), action) {
(RootState::Retiring { inflight, since }, RootAction::Observed) => {
let left = inflight.saturating_sub(1);
if left == 0 {
self.land(stamp.wall(), false, owed);
} else {
self.state = RootState::Retiring {
inflight: left,
since,
};
}
RootAdvance::Moved
}
(RootState::Restoring, RootAction::Restored) => {
self.state = RootState::Idle;
RootAdvance::Moved
}
(RootState::Retiring { .. }, RootAction::Lapsed) => {
self.land(stamp.wall(), true, owed);
RootAdvance::Moved
}
(RootState::Retiring { .. }, RootAction::Dispatched) => {
self.refused_dispatch = true;
RootAdvance::Declined
}
(
_,
RootAction::Dispatched | RootAction::Observed | RootAction::Restored | RootAction::Lapsed,
) => RootAdvance::Declined,
(RootState::Retiring { .. }, RootAction::Retire(origin))
if self
.retiring_as
.as_ref()
.is_none_or(|pending| origin.outranks(pending)) =>
{
self.retiring_as = Some(origin);
RootAdvance::Moved
}
(RootState::Retiring { .. }, RootAction::Retire(_))
| (RootState::Restoring, RootAction::Restore | RootAction::Reappear)
if self.queued.is_empty() =>
{
RootAdvance::Unchanged
}
(_, action) => {
if self.queued.last() == Some(&action) {
return RootAdvance::Coalesced;
}
self.queued.push(action);
RootAdvance::Queued
}
}
}
fn apply(
&mut self,
action: RootAction,
stamp: Stamp,
owed: &mut dyn FnMut(Retirement),
turned: &mut dyn FnMut(Flip),
) -> RootAdvance {
match (self.state.clone(), action) {
(RootState::Idle, RootAction::Intake) => {
self.open(stamp, 0);
RootAdvance::Moved
}
(RootState::Idle, RootAction::Dispatched) => {
self.open(stamp, 1);
RootAdvance::Moved
}
(RootState::Idle, RootAction::Retire(origin)) => self.retire(origin, stamp, owed),
(RootState::Idle, RootAction::Reappear) => RootAdvance::Unchanged,
(
RootState::Idle,
RootAction::Observed | RootAction::Restore | RootAction::Restored | RootAction::Lapsed,
) => RootAdvance::Declined,
(RootState::Analyzing { .. }, RootAction::Intake) => RootAdvance::Unchanged,
(RootState::Analyzing { inflight, since }, RootAction::Dispatched) => {
self.state = RootState::Analyzing {
inflight: inflight.saturating_add(1),
since,
};
RootAdvance::Moved
}
(RootState::Analyzing { inflight: 0, .. }, RootAction::Observed) => RootAdvance::Declined,
(RootState::Analyzing { inflight, since }, RootAction::Observed) => {
let left = inflight - 1;
if left == 0 {
self.state = RootState::Idle;
self.close(stamp.wall(), turned);
} else {
self.state = RootState::Analyzing {
inflight: left,
since,
};
}
RootAdvance::Moved
}
(RootState::Analyzing { .. }, RootAction::Retire(origin)) => self.retire(origin, stamp, owed),
(RootState::Analyzing { .. }, RootAction::Reappear) => RootAdvance::Unchanged,
(
RootState::Analyzing { .. },
RootAction::Restore | RootAction::Restored | RootAction::Lapsed,
) => RootAdvance::Declined,
(
RootState::Retired {
at,
origin,
late_tails,
},
RootAction::Retire(second),
) => {
if second.outranks(&origin) {
self.state = RootState::Retired {
at,
origin: second.clone(),
late_tails,
};
owed(Retirement::Recorded {
at,
origin: second,
late_tails,
});
RootAdvance::Moved
} else {
RootAdvance::Unchanged
}
}
(RootState::Retired { .. }, RootAction::Restore) => self.restore(owed),
(RootState::Retired { origin, .. }, RootAction::Reappear) => {
if origin.restores_itself() {
self.restore(owed)
} else {
RootAdvance::Declined
}
}
(
RootState::Retired { .. },
RootAction::Intake
| RootAction::Dispatched
| RootAction::Observed
| RootAction::Restored
| RootAction::Lapsed,
) => RootAdvance::Declined,
(RootState::Retiring { .. } | RootState::Restoring, _) => RootAdvance::Declined,
}
}
fn retire(
&mut self,
origin: RetireOrigin,
stamp: Stamp,
owed: &mut dyn FnMut(Retirement),
) -> RootAdvance {
let inflight = match self.state {
RootState::Analyzing { inflight, .. } => inflight,
_ => 0,
};
self.retiring_as = Some(origin);
self.running_as = None;
if inflight == 0 {
self.land(stamp.wall(), false, owed);
} else {
self.state = RootState::Retiring {
inflight,
since: stamp.monotonic(),
};
}
RootAdvance::Moved
}
fn land(&mut self, at: Timestamp, late_tails: bool, owed: &mut dyn FnMut(Retirement)) {
let origin = self.retiring_as.take().unwrap_or(RetireOrigin::Vanished);
let late_tails = late_tails || core::mem::take(&mut self.refused_dispatch);
self.state = RootState::Retired {
at,
origin: origin.clone(),
late_tails,
};
owed(Retirement::Recorded {
at,
origin,
late_tails,
});
}
fn restore(&mut self, owed: &mut dyn FnMut(Retirement)) -> RootAdvance {
self.state = RootState::Restoring;
self.retiring_as = None;
self.refused_dispatch = false;
owed(Retirement::Erased);
RootAdvance::Moved
}
fn drain(
&mut self,
stamp: Stamp,
owed: &mut dyn FnMut(Retirement),
turned: &mut dyn FnMut(Flip),
) {
while !self.state.is_busy() && !self.queued.is_empty() {
let next = self.queued.remove(0);
let _spent = self.apply(next, stamp, owed, turned);
}
}
#[inline]
fn open(&mut self, stamp: Stamp, inflight: u32) {
self.state = RootState::Analyzing {
inflight,
since: stamp.monotonic(),
};
self.running_as = Some(stamp.run());
}
#[inline]
fn close(&mut self, at: Timestamp, turned: &mut dyn FnMut(Flip)) {
if let Some(run) = self.running_as.take() {
turned(Flip::new(run, at));
}
}
}