Skip to main content

nopace_memory/
lib.rs

1use std::{
2    collections::BTreeMap, convert::Infallible, future::Future, pin::Pin, sync::Arc, time::Duration,
3};
4
5use nopace_core::{
6    AdmissionRequest, Completion, CompletionResult, LeaseRenewal, LeaseRenewalResult, PartitionKey,
7    PolicyId, ResetReport, Retention, ScopeKey, ScopeState, Store, StoreDecision, StorePeek,
8    StoreSnapshot, UnixMillis, collect_at, decide_at, finish_at, peek_at, renew_at, reset_policy,
9    snapshot_at,
10};
11pub use nopace_core::{Clock, SystemClock};
12use tokio::sync::{Mutex, Notify};
13
14#[derive(Clone, Debug)]
15pub struct ManualClock {
16    now: Arc<std::sync::atomic::AtomicU64>,
17    notify: Arc<Notify>,
18}
19impl ManualClock {
20    pub fn new(now: UnixMillis) -> Self {
21        Self {
22            now: Arc::new(std::sync::atomic::AtomicU64::new(now)),
23            notify: Arc::new(Notify::new()),
24        }
25    }
26    pub fn advance(&self, duration: Duration) {
27        self.now.fetch_add(
28            duration.as_millis().min(u64::MAX as u128) as u64,
29            std::sync::atomic::Ordering::SeqCst,
30        );
31        self.notify.notify_waiters();
32    }
33    pub fn set(&self, now: UnixMillis) {
34        self.now.store(now, std::sync::atomic::Ordering::SeqCst);
35        self.notify.notify_waiters();
36    }
37}
38impl Clock for ManualClock {
39    fn now_millis(&self) -> UnixMillis {
40        self.now.load(std::sync::atomic::Ordering::SeqCst)
41    }
42
43    fn sleep(&self, duration: Duration) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
44        let target = self
45            .now_millis()
46            .saturating_add(duration.as_millis().min(u64::MAX as u128) as u64);
47        Box::pin(async move {
48            while self.now_millis() < target {
49                self.notify.notified().await;
50            }
51        })
52    }
53}
54
55#[derive(Clone, Debug)]
56pub struct MemoryStore<C = SystemClock> {
57    state: Arc<Mutex<BTreeMap<ScopeKey, ScopeState>>>,
58    clock: C,
59    retention: Retention,
60}
61
62impl MemoryStore<SystemClock> {
63    pub fn new() -> Self {
64        Self::with_clock(SystemClock)
65    }
66}
67impl Default for MemoryStore<SystemClock> {
68    fn default() -> Self {
69        Self::new()
70    }
71}
72
73impl<C> MemoryStore<C> {
74    pub fn with_clock(clock: C) -> Self {
75        Self {
76            state: Arc::new(Mutex::new(BTreeMap::new())),
77            clock,
78            retention: Retention::default(),
79        }
80    }
81
82    pub fn with_retention(mut self, retention: Retention) -> Self {
83        self.retention = retention;
84        self
85    }
86}
87
88impl<C: Clock + Clone> MemoryStore<C> {
89    pub async fn collect(&self) {
90        let mut states = self.state.lock().await;
91        let now = self.clock.now_millis();
92        for state in states.values_mut() {
93            collect_at(state, now, self.retention);
94        }
95    }
96
97    pub async fn snapshot(&self, scope: &ScopeKey) -> Option<StoreSnapshot> {
98        self.state.lock().await.get(scope).map(snapshot_at)
99    }
100
101    pub async fn reset_policy(
102        &self,
103        scope: &ScopeKey,
104        policy: &PolicyId,
105        partition: Option<&PartitionKey>,
106    ) -> ResetReport {
107        self.state
108            .lock()
109            .await
110            .get_mut(scope)
111            .map(|state| reset_policy(state, policy, partition))
112            .unwrap_or_default()
113    }
114}
115
116impl<C: Clock + Clone> Store for MemoryStore<C> {
117    type Error = Infallible;
118
119    async fn decide(&self, request: AdmissionRequest) -> Result<StoreDecision, Self::Error> {
120        let mut state = self.state.lock().await;
121        let scope = state.entry(request.scope.clone()).or_default();
122        Ok(decide_at(
123            scope,
124            &request,
125            self.clock.now_millis(),
126            self.retention,
127        ))
128    }
129
130    async fn peek(&self, request: AdmissionRequest) -> Result<StorePeek, Self::Error> {
131        let state = self.state.lock().await;
132        let scope = state.get(&request.scope).cloned().unwrap_or_default();
133        Ok(peek_at(&scope, &request, self.clock.now_millis()))
134    }
135
136    async fn renew(&self, renewal: LeaseRenewal) -> Result<LeaseRenewalResult, Self::Error> {
137        let mut state = self.state.lock().await;
138        let scope = state.entry(renewal.scope.clone()).or_default();
139        Ok(renew_at(
140            scope,
141            &renewal,
142            self.clock.now_millis(),
143            self.retention,
144        ))
145    }
146
147    async fn finish(&self, completion: Completion) -> Result<CompletionResult, Self::Error> {
148        let mut state = self.state.lock().await;
149        let scope = state.entry(completion.scope.clone()).or_default();
150        Ok(finish_at(
151            scope,
152            &completion,
153            self.clock.now_millis(),
154            self.retention,
155        ))
156    }
157}