nopace-memory 0.2.0

In-memory store for nopace
Documentation
use std::{
    collections::BTreeMap, convert::Infallible, future::Future, pin::Pin, sync::Arc, time::Duration,
};

use nopace_core::{
    AdmissionRequest, Completion, CompletionResult, LeaseRenewal, LeaseRenewalResult, PartitionKey,
    PolicyId, ResetReport, Retention, ScopeKey, ScopeState, Store, StoreDecision, StorePeek,
    StoreSnapshot, UnixMillis, collect_at, decide_at, finish_at, peek_at, renew_at, reset_policy,
    snapshot_at,
};
pub use nopace_core::{Clock, SystemClock};
use tokio::sync::{Mutex, Notify};

#[derive(Clone, Debug)]
pub struct ManualClock {
    now: Arc<std::sync::atomic::AtomicU64>,
    notify: Arc<Notify>,
}
impl ManualClock {
    pub fn new(now: UnixMillis) -> Self {
        Self {
            now: Arc::new(std::sync::atomic::AtomicU64::new(now)),
            notify: Arc::new(Notify::new()),
        }
    }
    pub fn advance(&self, duration: Duration) {
        self.now.fetch_add(
            duration.as_millis().min(u64::MAX as u128) as u64,
            std::sync::atomic::Ordering::SeqCst,
        );
        self.notify.notify_waiters();
    }
    pub fn set(&self, now: UnixMillis) {
        self.now.store(now, std::sync::atomic::Ordering::SeqCst);
        self.notify.notify_waiters();
    }
}
impl Clock for ManualClock {
    fn now_millis(&self) -> UnixMillis {
        self.now.load(std::sync::atomic::Ordering::SeqCst)
    }

    fn sleep(&self, duration: Duration) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
        let target = self
            .now_millis()
            .saturating_add(duration.as_millis().min(u64::MAX as u128) as u64);
        Box::pin(async move {
            while self.now_millis() < target {
                self.notify.notified().await;
            }
        })
    }
}

#[derive(Clone, Debug)]
pub struct MemoryStore<C = SystemClock> {
    state: Arc<Mutex<BTreeMap<ScopeKey, ScopeState>>>,
    clock: C,
    retention: Retention,
}

impl MemoryStore<SystemClock> {
    pub fn new() -> Self {
        Self::with_clock(SystemClock)
    }
}
impl Default for MemoryStore<SystemClock> {
    fn default() -> Self {
        Self::new()
    }
}

impl<C> MemoryStore<C> {
    pub fn with_clock(clock: C) -> Self {
        Self {
            state: Arc::new(Mutex::new(BTreeMap::new())),
            clock,
            retention: Retention::default(),
        }
    }

    pub fn with_retention(mut self, retention: Retention) -> Self {
        self.retention = retention;
        self
    }
}

impl<C: Clock + Clone> MemoryStore<C> {
    pub async fn collect(&self) {
        let mut states = self.state.lock().await;
        let now = self.clock.now_millis();
        for state in states.values_mut() {
            collect_at(state, now);
        }
    }

    pub async fn snapshot(&self, scope: &ScopeKey) -> Option<StoreSnapshot> {
        self.state.lock().await.get(scope).map(snapshot_at)
    }

    pub async fn reset_policy(
        &self,
        scope: &ScopeKey,
        policy: &PolicyId,
        partition: Option<&PartitionKey>,
    ) -> ResetReport {
        self.state
            .lock()
            .await
            .get_mut(scope)
            .map(|state| reset_policy(state, policy, partition))
            .unwrap_or_default()
    }
}

impl<C: Clock + Clone> Store for MemoryStore<C> {
    type Error = Infallible;

    async fn decide(&self, request: AdmissionRequest) -> Result<StoreDecision, Self::Error> {
        let mut state = self.state.lock().await;
        let scope = state.entry(request.scope.clone()).or_default();
        Ok(decide_at(
            scope,
            &request,
            self.clock.now_millis(),
            self.retention,
        ))
    }

    async fn peek(&self, request: AdmissionRequest) -> Result<StorePeek, Self::Error> {
        let state = self.state.lock().await;
        let scope = state.get(&request.scope).cloned().unwrap_or_default();
        Ok(peek_at(&scope, &request, self.clock.now_millis()))
    }

    async fn renew(&self, renewal: LeaseRenewal) -> Result<LeaseRenewalResult, Self::Error> {
        let mut state = self.state.lock().await;
        let scope = state.entry(renewal.scope.clone()).or_default();
        Ok(renew_at(
            scope,
            &renewal,
            self.clock.now_millis(),
            self.retention,
        ))
    }

    async fn finish(&self, completion: Completion) -> Result<CompletionResult, Self::Error> {
        let mut state = self.state.lock().await;
        let scope = state.entry(completion.scope.clone()).or_default();
        Ok(finish_at(
            scope,
            &completion,
            self.clock.now_millis(),
            self.retention,
        ))
    }
}