use std::collections::HashMap;
use tributary_proto::Epoch;
use crate::{
route::{RoutableEvent, fan_out},
subscription::Subscription,
};
#[cfg(test)]
mod tests;
#[derive(Debug, Default)]
pub(crate) struct EpochLedger {
base: HashMap<Subscription, Epoch>,
high_water: HashMap<Subscription, Epoch>,
}
impl EpochLedger {
pub(crate) fn new() -> Self {
Self::default()
}
pub(crate) fn stamp(&mut self, sub: Subscription, raw: Epoch) -> Epoch {
let base = self.base.get(&sub).copied().unwrap_or(Epoch::START);
let natural = base.as_u64().saturating_add(raw.as_u64());
let hw = self.high_water.get(&sub).copied().unwrap_or(Epoch::START);
let stamp = Epoch::new(natural.max(hw.as_u64()));
self.bump(sub, stamp);
stamp
}
pub(crate) fn stamp_rescan(&mut self, sub: Subscription, raw: Epoch) -> Epoch {
let base = self.base.get(&sub).copied().unwrap_or(Epoch::START);
let natural = base.as_u64().saturating_add(raw.as_u64());
let hw = self.high_water.get(&sub).copied().unwrap_or(Epoch::START);
let stamp = Epoch::new(natural.max(hw.next().as_u64()));
self.bump(sub, stamp);
stamp
}
pub(crate) fn repoint(&mut self, sub: Subscription) -> Epoch {
let hw = self.high_water.get(&sub).copied().unwrap_or(Epoch::START);
let rescan = hw.next();
self.base.insert(sub, rescan);
self.bump(sub, rescan);
rescan
}
pub(crate) fn shed_rescan(&mut self, sub: Subscription) -> Epoch {
let hw = self.high_water.get(&sub).copied().unwrap_or(Epoch::START);
let rescan = hw.next();
self.bump(sub, rescan);
rescan
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn stamp_and_fan_out<'a, C, E, D>(
&mut self,
event: &E,
raw: Epoch,
subscribers: &[Subscription],
canonical_of: impl Fn(Subscription) -> Option<&'a [C]>,
admits: impl Fn(Subscription, &E::Delivered) -> bool,
sub_of: impl Fn(&E::Delivered) -> Subscription,
stamp_into: impl Fn(E::Delivered, Epoch) -> D,
) -> Vec<D>
where
C: PartialEq + 'a,
E: RoutableEvent<C>,
{
let is_rescan = event.is_rescan();
fan_out(event, subscribers, canonical_of, admits)
.into_iter()
.map(|delivered| {
let sub = sub_of(&delivered);
let stamp = if is_rescan {
self.stamp_rescan(sub, raw)
} else {
self.stamp(sub, raw)
};
stamp_into(delivered, stamp)
})
.collect()
}
pub(crate) fn remove(&mut self, sub: Subscription) {
self.base.remove(&sub);
self.high_water.remove(&sub);
}
fn bump(&mut self, sub: Subscription, stamp: Epoch) {
self
.high_water
.entry(sub)
.and_modify(|current| *current = (*current).max(stamp))
.or_insert(stamp);
}
#[cfg(all(test, feature = "tokio"))]
pub(crate) fn tracked_len(&self) -> (usize, usize) {
(self.base.len(), self.high_water.len())
}
}