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