use std::sync::{
Arc, RwLock,
atomic::{AtomicU64, Ordering},
};
use crate::drive::registry::{Flip, GenerationLedger, Registry, RootKey};
use super::{
Culled, CurrentRow, GenerationsOptions, GenerationsOverride, GenerationsStore,
GenerationsStoreError, Scope,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct CuratorReport {
pub flipped: u64,
pub swept: u64,
pub refused: u64,
}
#[derive(Debug, Default)]
struct Counters {
flipped: AtomicU64,
swept: AtomicU64,
refused: AtomicU64,
}
impl Counters {
fn report(&self) -> CuratorReport {
CuratorReport {
flipped: self.flipped.load(Ordering::Relaxed),
swept: self.swept.load(Ordering::Relaxed),
refused: self.refused.load(Ordering::Relaxed),
}
}
}
pub struct Curator<Root> {
owed: flume::Sender<(Root, Flip)>,
options: Arc<RwLock<GenerationsOptions>>,
counters: Arc<Counters>,
}
impl<Root> core::fmt::Debug for Curator<Root> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Curator")
.field("queued", &self.owed.len())
.field("report", &self.counters.report())
.finish()
}
}
impl<Root> Curator<Root>
where
Root: RootKey,
{
#[must_use]
pub fn new(
store: Arc<dyn GenerationsStore<Root>>,
scope: Scope,
options: GenerationsOptions,
) -> (Self, CuratorBody<Root>) {
let (owed, taken) = flume::unbounded();
let counters = Arc::new(Counters::default());
let options = Arc::new(RwLock::new(options));
let seat = Self {
owed,
options: Arc::clone(&options),
counters: Arc::clone(&counters),
};
let body = CuratorBody {
taken,
store,
scope,
options,
counters,
};
(seat, body)
}
#[must_use = "the body is what performs the flips; a dropped one leaves the pointers untouched"]
pub fn seated(
registry: &Arc<Registry<Root>>,
store: Arc<dyn GenerationsStore<Root>>,
scope: Scope,
options: GenerationsOptions,
) -> Option<CuratorBody<Root>> {
let (seat, body) = Self::new(store, scope, options);
registry
.curating(Arc::new(seat) as Arc<dyn GenerationLedger<Root>>)
.then_some(body)
}
pub fn apply_knobs(&self, over: &GenerationsOverride) {
let mut current = self
.options
.write()
.unwrap_or_else(|held| held.into_inner());
if let Some(keep) = over.keep() {
current.set_keep(keep);
}
}
#[must_use]
pub fn options(&self) -> GenerationsOptions {
self
.options
.read()
.unwrap_or_else(|held| held.into_inner())
.clone()
}
#[inline]
#[must_use]
pub fn report(&self) -> CuratorReport {
self.counters.report()
}
#[inline]
#[must_use]
pub fn queued(&self) -> usize {
self.owed.len()
}
}
impl<Root> GenerationLedger<Root> for Curator<Root>
where
Root: RootKey,
{
#[inline]
fn flipped(&self, key: &Root, act: Flip) {
let _gone = self.owed.send((key.clone(), act));
}
}
pub struct CuratorBody<Root: RootKey> {
taken: flume::Receiver<(Root, Flip)>,
store: Arc<dyn GenerationsStore<Root>>,
scope: Scope,
options: Arc<RwLock<GenerationsOptions>>,
counters: Arc<Counters>,
}
impl<Root: RootKey> core::fmt::Debug for CuratorBody<Root> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("CuratorBody")
.field("queued", &self.taken.len())
.field("scope", &self.scope)
.field("report", &self.counters.report())
.finish()
}
}
impl<Root: RootKey> CuratorBody<Root> {
pub async fn run(self) {
while let Ok((key, act)) = self.taken.recv_async().await {
self.perform(&key, act).await;
}
}
pub async fn perform(&self, key: &Root, act: Flip) {
let row = CurrentRow::new(key.clone(), self.scope.clone(), act.run(), act.at());
if self.refused(self.store.point(&row).await) {
return;
}
self.counters.flipped.fetch_add(1, Ordering::Relaxed);
let keep = self.keep();
match self.store.sweep(key, act.run(), keep).await {
Ok(Culled { rows, .. }) => {
self.counters.swept.fetch_add(rows, Ordering::Relaxed);
}
refusal => {
let _counted = self.refused(refusal.map(|_swept| ()));
}
}
}
fn keep(&self) -> core::num::NonZeroUsize {
self
.options
.read()
.unwrap_or_else(|held| held.into_inner())
.keep()
}
fn refused(&self, outcome: Result<(), GenerationsStoreError>) -> bool {
let Err(refusal) = outcome else {
return false;
};
self.counters.refused.fetch_add(1, Ordering::Relaxed);
#[cfg(feature = "tracing")]
{
let engine = core::error::Error::source(&refusal).map(ToString::to_string);
tracing::error!(
verb = refusal.verb(),
table = refusal.table(),
error = %refusal,
engine = engine.as_deref().unwrap_or("—"),
"the generations store refused an act; nothing was erased"
);
}
#[cfg(not(feature = "tracing"))]
let _unreported = refusal;
true
}
#[inline]
#[must_use]
pub const fn scope(&self) -> &Scope {
&self.scope
}
#[inline]
#[must_use]
pub fn report(&self) -> CuratorReport {
self.counters.report()
}
}
pub async fn prepare<Root>(
store: &dyn GenerationsStore<Root>,
) -> Result<usize, GenerationsStoreError>
where
Root: RootKey,
{
store.ready().await?;
store.roll().await.map(|pointers| pointers.len())
}