1use std::any::Any;
20use std::collections::HashMap;
21use std::future::Future;
22use std::sync::{Arc, Mutex, PoisonError, Weak};
23
24use futures::channel::oneshot;
25use futures::future::{FutureExt, Shared};
26use lru::LruCache;
27use object_store::ObjectStore;
28use object_store::path::Path;
29
30use crate::error::{ItzmaError, Result};
31
32pub const DEFAULT_DECODED_MAX_BYTES: u64 = 256 * 1024 * 1024;
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37#[non_exhaustive]
38pub struct DecodedCacheOptions {
39 pub max_bytes: u64,
43}
44
45impl Default for DecodedCacheOptions {
46 fn default() -> Self {
47 Self {
48 max_bytes: DEFAULT_DECODED_MAX_BYTES,
49 }
50 }
51}
52
53impl DecodedCacheOptions {
54 #[must_use]
56 pub fn max_bytes(mut self, max_bytes: u64) -> Self {
57 self.max_bytes = max_bytes;
58 self
59 }
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
64pub(crate) enum What {
65 SegmentMeta,
67 Bloom,
69 Zones,
71 IdBlock(usize),
73 AttrBlock(usize),
74 TombstoneBlock(usize),
75 IndexHead,
77 Sq8Head,
79 Partition(u32),
81 SparseDirectory,
83 View,
85}
86
87#[derive(Debug, Clone, PartialEq, Eq, Hash)]
88struct Key {
89 store: usize,
90 path: Path,
91 what: What,
92}
93
94type Value = Arc<dyn Any + Send + Sync>;
95type Pending = Shared<oneshot::Receiver<()>>;
96
97struct Inner {
98 ready: LruCache<Key, (Value, u64)>,
99 pending: HashMap<Key, Pending>,
100 used: u64,
101 stores: HashMap<usize, Weak<dyn ObjectStore>>,
105}
106
107pub struct DecodedCache {
117 max_bytes: u64,
118 inner: Mutex<Inner>,
119}
120
121impl std::fmt::Debug for DecodedCache {
122 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123 let inner = self.lock();
124 f.debug_struct("DecodedCache")
125 .field("max_bytes", &self.max_bytes)
126 .field("used", &inner.used)
127 .field("entries", &inner.ready.len())
128 .finish()
129 }
130}
131
132impl DecodedCache {
133 #[must_use]
135 pub fn new(options: DecodedCacheOptions) -> Arc<Self> {
136 Arc::new(Self {
137 max_bytes: options.max_bytes,
138 inner: Mutex::new(Inner {
139 ready: LruCache::unbounded(),
140 pending: HashMap::new(),
141 used: 0,
142 stores: HashMap::new(),
143 }),
144 })
145 }
146
147 fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
148 self.inner.lock().unwrap_or_else(PoisonError::into_inner)
149 }
150
151 pub(crate) fn store_id(store: &Arc<dyn ObjectStore>) -> usize {
153 Arc::as_ptr(store).cast::<()>() as usize
154 }
155
156 pub(crate) fn handle(self: &Arc<Self>, store: &Arc<dyn ObjectStore>) -> DecodedRef {
158 let id = Self::store_id(store);
159 let mut inner = self.lock();
160 let known = inner.stores.get(&id).map(|weak| weak.strong_count() > 0);
161 if known == Some(false) {
162 Self::purge(&mut inner, id);
163 }
164 inner.stores.insert(id, Arc::downgrade(store));
165 DecodedRef {
166 cache: self.clone(),
167 store: id,
168 }
169 }
170
171 #[cfg(test)]
173 pub(crate) fn forget_dead(&self, id: usize) {
174 let mut inner = self.lock();
175 if inner.stores.get(&id).is_some_and(|w| w.strong_count() == 0) {
176 Self::purge(&mut inner, id);
177 }
178 }
179
180 #[cfg(test)]
181 pub(crate) fn entries_of(&self, id: usize) -> usize {
182 self.lock()
183 .ready
184 .iter()
185 .filter(|(k, _)| k.store == id)
186 .count()
187 }
188
189 fn purge(inner: &mut Inner, id: usize) {
190 let dead: Vec<Key> = inner
191 .ready
192 .iter()
193 .filter(|(key, _)| key.store == id)
194 .map(|(key, _)| key.clone())
195 .collect();
196 for key in dead {
197 if let Some((_, weight)) = inner.ready.pop(&key) {
198 inner.used -= weight;
199 }
200 }
201 inner.stores.remove(&id);
202 }
203
204 fn insert(&self, inner: &mut Inner, key: Key, value: Value, weight: u64) {
205 if weight > self.max_bytes {
206 return;
207 }
208 if let Some((_, old)) = inner.ready.put(key, (value, weight)) {
209 inner.used -= old;
210 }
211 inner.used += weight;
212 while inner.used > self.max_bytes {
213 match inner.ready.pop_lru() {
214 Some((_, (_, w))) => inner.used -= w,
215 None => break,
216 }
217 }
218 }
219}
220
221struct Claim {
224 cache: Arc<DecodedCache>,
225 keys: Vec<Key>,
226 _wake: Vec<oneshot::Sender<()>>,
227}
228
229impl Drop for Claim {
230 fn drop(&mut self) {
231 let mut inner = self.cache.lock();
232 for key in &self.keys {
233 inner.pending.remove(key);
234 }
235 }
236}
237
238#[derive(Clone)]
240pub(crate) struct DecodedRef {
241 cache: Arc<DecodedCache>,
242 store: usize,
243}
244
245impl std::fmt::Debug for DecodedRef {
246 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
247 f.debug_struct("DecodedRef")
248 .field("store", &self.store)
249 .finish()
250 }
251}
252
253impl DecodedRef {
254 fn key(&self, path: &Path, what: What) -> Key {
255 Key {
256 store: self.store,
257 path: path.clone(),
258 what,
259 }
260 }
261
262 pub(crate) async fn get_or_load<T, F, Fut>(
265 &self,
266 path: &Path,
267 what: What,
268 load: F,
269 ) -> Result<Arc<T>>
270 where
271 T: Send + Sync + 'static,
272 F: FnOnce() -> Fut,
273 Fut: Future<Output = Result<(T, u64)>>,
274 {
275 let mut load = Some(load);
276 let mut got = self
277 .get_or_load_many(path, &[what], |_| {
278 let load = load.take();
279 async move {
280 match load {
281 Some(load) => Ok(vec![load().await?]),
282 None => Err(ItzmaError::InvalidQuery("a cache load ran twice")),
286 }
287 }
288 })
289 .await?;
290 got.pop()
291 .ok_or(ItzmaError::InvalidQuery("a cache load gave no value"))
292 }
293
294 pub(crate) async fn get_or_load_many<T, F, Fut>(
299 &self,
300 path: &Path,
301 whats: &[What],
302 mut load: F,
303 ) -> Result<Vec<Arc<T>>>
304 where
305 T: Send + Sync + 'static,
306 F: FnMut(Vec<usize>) -> Fut,
307 Fut: Future<Output = Result<Vec<(T, u64)>>>,
308 {
309 let keys: Vec<Key> = whats.iter().map(|w| self.key(path, *w)).collect();
310 let mut out: Vec<Option<Arc<T>>> = vec![None; keys.len()];
311 loop {
312 let mut claimed = Vec::new();
313 let mut senders = Vec::new();
314 let mut waits = Vec::new();
315 {
316 let mut inner = self.cache.lock();
317 for (at, key) in keys.iter().enumerate() {
318 if out[at].is_some() {
319 continue;
320 }
321 let hit = inner.ready.get(key).map(|(value, _)| value.clone());
322 if let Some(typed) = hit.and_then(|value| value.downcast::<T>().ok()) {
323 out[at] = Some(typed);
324 } else if let Some(pending) = inner.pending.get(key) {
325 waits.push(pending.clone());
326 } else {
327 let (tx, rx) = oneshot::channel();
328 inner.pending.insert(key.clone(), rx.shared());
329 senders.push(tx);
330 claimed.push(at);
331 }
332 }
333 }
334 if claimed.is_empty() && waits.is_empty() {
335 break;
336 }
337 if !claimed.is_empty() {
338 let claim = Claim {
339 cache: self.cache.clone(),
340 keys: claimed.iter().map(|at| keys[*at].clone()).collect(),
341 _wake: senders,
342 };
343 let values = load(claimed.clone()).await?;
344 if values.len() != claimed.len() {
345 return Err(ItzmaError::InvalidQuery(
346 "a cache load gave the wrong number of values",
347 ));
348 }
349 let mut inner = self.cache.lock();
350 for (at, (value, weight)) in claimed.iter().zip(values) {
351 let value = Arc::new(value);
352 let shared: Value = value.clone();
353 self.cache
354 .insert(&mut inner, keys[*at].clone(), shared, weight);
355 out[*at] = Some(value);
356 }
357 drop(inner);
358 drop(claim);
359 }
360 for wait in waits {
361 let _ = wait.await;
362 }
363 }
364 Ok(out.into_iter().flatten().collect())
365 }
366}
367
368#[cfg(test)]
369mod tests {
370 use std::sync::Arc;
371 use std::sync::atomic::{AtomicUsize, Ordering};
372
373 use futures::channel::oneshot;
374 use futures::future::FutureExt;
375 use object_store::ObjectStore;
376 use object_store::memory::InMemory;
377 use object_store::path::Path;
378
379 use super::*;
380 use crate::error::ItzmaError;
381
382 fn store() -> Arc<dyn ObjectStore> {
383 Arc::new(InMemory::new())
384 }
385
386 fn cache(max_bytes: u64) -> Arc<DecodedCache> {
387 DecodedCache::new(DecodedCacheOptions::default().max_bytes(max_bytes))
388 }
389
390 fn path(name: &str) -> Path {
391 Path::from(name)
392 }
393
394 async fn counted(
396 calls: &AtomicUsize,
397 value: u64,
398 weight: u64,
399 ) -> crate::error::Result<(u64, u64)> {
400 calls.fetch_add(1, Ordering::SeqCst);
401 Ok((value, weight))
402 }
403
404 #[tokio::test]
405 async fn two_concurrent_gets_of_one_key_load_once() {
406 let s = store();
407 let handle = cache(1 << 20).handle(&s);
408 let calls = AtomicUsize::new(0);
409 let (open, gate) = oneshot::channel::<()>();
410 let gate = gate.shared();
411 let a = path("a");
412
413 let first = handle.get_or_load(&a, What::IndexHead, || async {
414 calls.fetch_add(1, Ordering::SeqCst);
415 let _ = gate.clone().await;
416 Ok::<_, ItzmaError>((7u64, 8))
417 });
418 let second = handle.get_or_load(&a, What::IndexHead, || async {
419 calls.fetch_add(1, Ordering::SeqCst);
420 Ok::<_, ItzmaError>((9u64, 8))
421 });
422 let release = async {
423 tokio::task::yield_now().await;
424 let _ = open.send(());
425 };
426 let (a, b, ()) = futures::join!(first, second, release);
427 assert_eq!(calls.load(Ordering::SeqCst), 1, "the waiter must not load");
428 assert!(Arc::ptr_eq(&a.unwrap(), &b.unwrap()));
429 }
430
431 #[tokio::test]
432 async fn a_hit_does_not_load_and_moves_the_entry_to_the_front() {
433 let s = store();
434 let handle = cache(100).handle(&s);
435 let calls = AtomicUsize::new(0);
436 let get = |name: &'static str, weight: u64| {
437 let handle = handle.clone();
438 let calls = &calls;
439 async move {
440 handle
441 .get_or_load(&path(name), What::IndexHead, || counted(calls, 1, weight))
442 .await
443 .unwrap()
444 }
445 };
446 get("a", 60).await;
447 get("b", 30).await;
448 get("a", 60).await;
449 assert_eq!(calls.load(Ordering::SeqCst), 2, "the third get is a hit");
450
451 get("c", 30).await;
453 get("a", 60).await;
454 assert_eq!(calls.load(Ordering::SeqCst), 3, "a stayed");
455 get("b", 30).await;
456 assert_eq!(calls.load(Ordering::SeqCst), 4, "b was evicted");
457 }
458
459 #[tokio::test]
460 async fn a_value_bigger_than_the_cache_is_returned_and_not_kept() {
461 let s = store();
462 let handle = cache(10).handle(&s);
463 let calls = AtomicUsize::new(0);
464 for _ in 0..2 {
465 let got = handle
466 .get_or_load(&path("big"), What::View, || counted(&calls, 5, 11))
467 .await
468 .unwrap();
469 assert_eq!(*got, 5);
470 }
471 assert_eq!(calls.load(Ordering::SeqCst), 2);
472 }
473
474 #[tokio::test]
475 async fn a_failed_load_is_not_kept_and_the_next_caller_loads_again() {
476 let s = store();
477 let handle = cache(1 << 20).handle(&s);
478 let failed = handle
479 .get_or_load(&path("a"), What::Bloom, || async {
480 Err::<(u64, u64), _>(ItzmaError::EmptyBatch)
481 })
482 .await;
483 assert!(matches!(failed, Err(ItzmaError::EmptyBatch)), "{failed:?}");
484 let calls = AtomicUsize::new(0);
485 let got = handle
486 .get_or_load(&path("a"), What::Bloom, || counted(&calls, 3, 1))
487 .await
488 .unwrap();
489 assert_eq!((*got, calls.load(Ordering::SeqCst)), (3, 1));
490 }
491
492 #[tokio::test]
494 async fn a_waiter_loads_itself_when_the_loader_fails_or_is_dropped() {
495 for drop_the_loader in [false, true] {
496 let s = store();
497 let handle = cache(1 << 20).handle(&s);
498 let (open, gate) = oneshot::channel::<()>();
499 let gate = gate.shared();
500 let a = path("a");
501 let mut first = handle
502 .get_or_load(&a, What::IndexHead, || async {
503 let _ = gate.clone().await;
504 Err::<(u64, u64), _>(ItzmaError::EmptyBatch)
505 })
506 .boxed();
507 assert!(futures::poll!(&mut first).is_pending());
509 let calls = AtomicUsize::new(0);
510 let second = handle.get_or_load(&a, What::IndexHead, || counted(&calls, 4, 1));
511
512 let driver = async move {
515 if drop_the_loader {
516 drop(first);
517 } else {
518 let _ = open.send(());
519 assert!(first.await.is_err());
520 }
521 };
522 let (got, ()) = futures::join!(second, driver);
523 assert_eq!(*got.unwrap(), 4, "drop: {drop_the_loader}");
524 assert_eq!(calls.load(Ordering::SeqCst), 1);
525 }
526 }
527
528 #[tokio::test]
529 async fn many_loads_only_the_missing_keys_in_one_call() {
530 let s = store();
531 let handle = cache(1 << 20).handle(&s);
532 let p = path("idx");
533 handle
534 .get_or_load(&p, What::Partition(1), || async {
535 Ok::<_, ItzmaError>((10u64, 1))
536 })
537 .await
538 .unwrap();
539 let asked = std::sync::Mutex::new(Vec::new());
540 let got = handle
541 .get_or_load_many(
542 &p,
543 &[What::Partition(0), What::Partition(1), What::Partition(2)],
544 |missing: Vec<usize>| {
545 asked.lock().unwrap().push(missing.clone());
546 async move { Ok(missing.iter().map(|i| (*i as u64 * 100, 1)).collect()) }
547 },
548 )
549 .await
550 .unwrap();
551 let values: Vec<u64> = got.iter().map(|v| **v).collect();
552 assert_eq!(values, [0, 10, 200]);
553 assert_eq!(*asked.lock().unwrap(), [vec![0, 2]]);
554 }
555
556 #[tokio::test]
557 async fn two_stores_never_share_an_entry() {
558 let (s1, s2) = (store(), store());
559 let shared = cache(1 << 20);
560 let (h1, h2) = (shared.handle(&s1), shared.handle(&s2));
561 let calls = AtomicUsize::new(0);
562 let a = h1
563 .get_or_load(&path("x"), What::IndexHead, || counted(&calls, 1, 1))
564 .await
565 .unwrap();
566 let b = h2
567 .get_or_load(&path("x"), What::IndexHead, || counted(&calls, 2, 1))
568 .await
569 .unwrap();
570 assert_eq!((*a, *b), (1, 2));
571 }
572
573 #[tokio::test]
576 async fn a_dead_stores_entries_are_dropped_when_its_address_comes_back() {
577 let shared = cache(1 << 20);
578 let s1 = store();
579 let id = DecodedCache::store_id(&s1);
580 shared
581 .handle(&s1)
582 .get_or_load(&path("x"), What::IndexHead, || async {
583 Ok::<_, ItzmaError>((1u64, 1))
584 })
585 .await
586 .unwrap();
587 drop(s1);
588 shared.forget_dead(id);
589 assert_eq!(shared.entries_of(id), 0);
590 }
591
592 #[test]
593 fn options_default_to_256_mib() {
594 assert_eq!(DecodedCacheOptions::default().max_bytes, 256 << 20);
595 assert_eq!(DecodedCacheOptions::default().max_bytes(5).max_bytes, 5);
596 }
597}