1use std::num::NonZeroUsize;
10use std::ops::Range;
11
12use bytes::Bytes;
13use lru::LruCache;
14use object_store::path::Path;
15use object_store::{GetRange, ObjectMeta};
16
17#[derive(Debug, Clone, PartialEq, Eq, Hash)]
24pub(crate) struct CacheKey {
25 path: Path,
26 range: Option<RangeSpec>,
27}
28
29impl CacheKey {
30 pub(crate) fn new(path: &Path, range: Option<&GetRange>) -> Self {
33 CacheKey {
34 path: path.clone(),
35 range: range.map(RangeSpec::from),
36 }
37 }
38}
39
40#[derive(Debug, Clone, PartialEq, Eq, Hash)]
44enum RangeSpec {
45 Bounded(u64, u64),
46 Offset(u64),
47 Suffix(u64),
48}
49
50impl From<&GetRange> for RangeSpec {
51 fn from(range: &GetRange) -> Self {
52 match range {
53 GetRange::Bounded(r) => RangeSpec::Bounded(r.start, r.end),
54 GetRange::Offset(o) => RangeSpec::Offset(*o),
55 GetRange::Suffix(s) => RangeSpec::Suffix(*s),
56 }
57 }
58}
59
60#[derive(Debug, Clone)]
66pub(crate) struct CachedRead {
67 pub(crate) bytes: Bytes,
68 pub(crate) meta: ObjectMeta,
69 pub(crate) range: Range<u64>,
70 pub(crate) attributes: object_store::Attributes,
71}
72
73impl CachedRead {
74 fn len(&self) -> u64 {
75 self.bytes.len() as u64
76 }
77}
78
79const MAX_ENTRIES: usize = 10_000_000;
86
87pub(crate) struct RamCache {
93 entries: LruCache<CacheKey, CachedRead>,
94 max_bytes: u64,
95 used_bytes: u64,
96}
97
98impl RamCache {
99 pub(crate) fn new(max_bytes: u64) -> Self {
101 RamCache {
102 entries: LruCache::new(
103 NonZeroUsize::new(MAX_ENTRIES).expect("MAX_ENTRIES is never zero"),
104 ),
105 max_bytes,
106 used_bytes: 0,
107 }
108 }
109
110 pub(crate) fn get(&mut self, key: &CacheKey) -> Option<CachedRead> {
112 self.entries.get(key).cloned()
113 }
114
115 pub(crate) fn put(&mut self, key: CacheKey, value: CachedRead) {
119 let len = value.len();
120 if len > self.max_bytes {
121 return;
122 }
123 if let Some(old) = self.entries.put(key, value) {
124 self.used_bytes -= old.len();
125 }
126 self.used_bytes += len;
127 while self.used_bytes > self.max_bytes {
128 let Some((_, evicted)) = self.entries.pop_lru() else {
129 break;
130 };
131 self.used_bytes -= evicted.len();
132 }
133 }
134}
135
136use std::sync::{Arc, Mutex};
137
138use async_trait::async_trait;
139use futures::StreamExt;
140use futures::stream::BoxStream;
141use object_store::{
142 CopyOptions, GetOptions, GetResult, GetResultPayload, ListResult, MultipartUpload, ObjectStore,
143 ObjectStoreExt, PutMultipartOptions, PutOptions, PutPayload, PutResult, Result,
144};
145
146fn is_cacheable(options: &GetOptions) -> bool {
154 options.if_match.is_none()
155 && options.if_none_match.is_none()
156 && options.if_modified_since.is_none()
157 && options.if_unmodified_since.is_none()
158 && options.version.is_none()
159 && !options.head
160}
161
162fn to_get_result(cached: CachedRead) -> GetResult {
163 let CachedRead {
164 bytes,
165 meta,
166 range,
167 attributes,
168 } = cached;
169 GetResult {
170 payload: GetResultPayload::Stream(futures::stream::once(async move { Ok(bytes) }).boxed()),
171 meta,
172 range,
173 attributes,
174 extensions: Default::default(),
175 }
176}
177
178pub struct CacheStore {
184 inner: Arc<dyn ObjectStore>,
185 ram: Mutex<RamCache>,
186 nvme: Option<NvmeCache>,
187}
188
189#[derive(Debug, Clone)]
192#[non_exhaustive]
193pub struct CacheOptions {
194 pub ram_max_bytes: u64,
196 pub nvme: Option<NvmeOptions>,
198}
199
200#[derive(Debug, Clone)]
202#[non_exhaustive]
203pub struct NvmeOptions {
204 pub dir: std::path::PathBuf,
206 pub max_bytes: u64,
208}
209
210impl NvmeOptions {
211 pub fn new(dir: impl Into<std::path::PathBuf>, max_bytes: u64) -> Self {
215 Self {
216 dir: dir.into(),
217 max_bytes,
218 }
219 }
220}
221
222pub const DEFAULT_RAM_MAX_BYTES: u64 = 256 * 1024 * 1024;
227
228impl Default for CacheOptions {
229 fn default() -> Self {
230 CacheOptions {
231 ram_max_bytes: DEFAULT_RAM_MAX_BYTES,
232 nvme: None,
233 }
234 }
235}
236
237impl CacheStore {
238 pub fn new(
265 inner: Arc<dyn ObjectStore>,
266 options: CacheOptions,
267 ) -> std::result::Result<Self, object_store::Error> {
268 let nvme = options
269 .nvme
270 .map(|n| NvmeCache::new(&n.dir, n.max_bytes))
271 .transpose()?;
272 Ok(CacheStore {
273 inner,
274 ram: Mutex::new(RamCache::new(options.ram_max_bytes)),
275 nvme,
276 })
277 }
278}
279
280impl std::fmt::Debug for CacheStore {
281 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
282 write!(f, "CacheStore({:?})", self.inner)
283 }
284}
285
286impl std::fmt::Display for CacheStore {
287 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
288 write!(f, "CacheStore({})", self.inner)
289 }
290}
291
292#[async_trait]
293impl ObjectStore for CacheStore {
294 async fn put_opts(
295 &self,
296 location: &Path,
297 payload: PutPayload,
298 opts: PutOptions,
299 ) -> Result<PutResult> {
300 self.inner.put_opts(location, payload, opts).await
301 }
302
303 async fn put_multipart_opts(
304 &self,
305 location: &Path,
306 opts: PutMultipartOptions,
307 ) -> Result<Box<dyn MultipartUpload>> {
308 self.inner.put_multipart_opts(location, opts).await
309 }
310
311 async fn get_opts(&self, location: &Path, options: GetOptions) -> Result<GetResult> {
312 if !is_cacheable(&options) {
313 return self.inner.get_opts(location, options).await;
314 }
315 let key = CacheKey::new(location, options.range.as_ref());
316
317 if let Some(cached) = self.ram.lock().expect("ram cache lock poisoned").get(&key) {
318 return Ok(to_get_result(cached));
319 }
320
321 if let Some(nvme) = &self.nvme {
322 if let Some(cached) = nvme.get(&key).await {
323 self.ram
324 .lock()
325 .expect("ram cache lock poisoned")
326 .put(key, cached.clone());
327 return Ok(to_get_result(cached));
328 }
329 }
330
331 let result = self.inner.get_opts(location, options).await?;
332 let meta = result.meta.clone();
333 let range = result.range.clone();
334 let attributes = result.attributes.clone();
335 let bytes = result.bytes().await?;
336 let cached = CachedRead {
337 bytes,
338 meta,
339 range,
340 attributes,
341 };
342
343 if let Some(nvme) = &self.nvme {
344 nvme.put(key.clone(), &cached).await;
345 }
346 self.ram
347 .lock()
348 .expect("ram cache lock poisoned")
349 .put(key, cached.clone());
350
351 Ok(to_get_result(cached))
352 }
353
354 fn delete_stream(
355 &self,
356 locations: BoxStream<'static, Result<Path>>,
357 ) -> BoxStream<'static, Result<Path>> {
358 self.inner.delete_stream(locations)
359 }
360
361 fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, Result<ObjectMeta>> {
362 self.inner.list(prefix)
363 }
364
365 fn list_with_offset(
366 &self,
367 prefix: Option<&Path>,
368 offset: &Path,
369 ) -> BoxStream<'static, Result<ObjectMeta>> {
370 self.inner.list_with_offset(prefix, offset)
371 }
372
373 async fn list_with_delimiter(&self, prefix: Option<&Path>) -> Result<ListResult> {
374 self.inner.list_with_delimiter(prefix).await
375 }
376
377 async fn copy_opts(&self, from: &Path, to: &Path, options: CopyOptions) -> Result<()> {
378 self.inner.copy_opts(from, to, options).await
379 }
380}
381
382use object_store::local::LocalFileSystem;
383
384fn nvme_key(key: &CacheKey) -> Path {
392 use std::hash::{Hash, Hasher};
393 let mut hasher = std::collections::hash_map::DefaultHasher::new();
394 key.hash(&mut hasher);
395 Path::from(format!("{:016x}", hasher.finish()))
396}
397
398#[derive(Clone)]
399struct NvmeEntry {
400 file: Path,
401 len: u64,
402}
403
404struct NvmeIndex {
405 entries: LruCache<CacheKey, NvmeEntry>,
406 used_bytes: u64,
407}
408
409pub(crate) struct NvmeCache {
423 store: LocalFileSystem,
424 max_bytes: u64,
425 index: Mutex<NvmeIndex>,
426}
427
428impl NvmeCache {
429 pub(crate) fn new(
437 dir: &std::path::Path,
438 max_bytes: u64,
439 ) -> std::result::Result<Self, object_store::Error> {
440 std::fs::create_dir_all(dir).map_err(|e| object_store::Error::Generic {
442 store: "NvmeCache",
443 source: Box::new(e),
444 })?;
445 Ok(NvmeCache {
446 store: LocalFileSystem::new_with_prefix(dir)?,
447 max_bytes,
448 index: Mutex::new(NvmeIndex {
449 entries: LruCache::new(
450 NonZeroUsize::new(MAX_ENTRIES).expect("MAX_ENTRIES is never zero"),
451 ),
452 used_bytes: 0,
453 }),
454 })
455 }
456
457 pub(crate) async fn get(&self, key: &CacheKey) -> Option<CachedRead> {
462 let file = nvme_key(key);
463 let result = self.store.get(&file).await.ok()?;
464 let meta = result.meta.clone();
465 let range = result.range.clone();
466 let attributes = result.attributes.clone();
467 let bytes = result.bytes().await.ok()?;
468 let len = bytes.len() as u64;
469
470 let mut guard = self.index.lock().expect("nvme index lock poisoned");
471 if guard
472 .entries
473 .put(key.clone(), NvmeEntry { file, len })
474 .is_none()
475 {
476 guard.used_bytes += len;
477 }
478 drop(guard);
479
480 Some(CachedRead {
481 bytes,
482 meta,
483 range,
484 attributes,
485 })
486 }
487
488 pub(crate) async fn put(&self, key: CacheKey, value: &CachedRead) {
492 let len = value.bytes.len() as u64;
493 if len > self.max_bytes {
494 return;
495 }
496 let file = nvme_key(&key);
497 if self
498 .store
499 .put(&file, PutPayload::from(value.bytes.clone()))
500 .await
501 .is_err()
502 {
503 return;
504 }
505
506 let to_delete = {
507 let mut guard = self.index.lock().expect("nvme index lock poisoned");
508 if let Some(old) = guard.entries.put(key, NvmeEntry { file, len }) {
509 guard.used_bytes -= old.len;
510 }
511 guard.used_bytes += len;
512 let mut to_delete = Vec::new();
513 while guard.used_bytes > self.max_bytes {
514 let Some((_, evicted)) = guard.entries.pop_lru() else {
515 break;
516 };
517 guard.used_bytes -= evicted.len;
518 to_delete.push(evicted.file);
519 }
520 to_delete
521 };
522
523 for file in to_delete {
528 let _ = self.store.delete(&file).await;
529 }
530 }
531}
532
533#[cfg(test)]
534mod tests {
535 use super::*;
536 use chrono::Utc;
537
538 #[test]
539 fn nvme_options_new_sets_both_fields() {
540 let options = NvmeOptions::new("/mnt/nvme/itzma", 1024);
541 assert_eq!(options.dir, std::path::PathBuf::from("/mnt/nvme/itzma"));
542 assert_eq!(options.max_bytes, 1024);
543 }
544
545 #[test]
546 fn nvme_cache_creates_a_missing_directory() {
547 let dir = tempfile::tempdir().unwrap();
548 let path = dir.path().join("a/b/nvme");
549 NvmeCache::new(&path, 1024).unwrap();
550 assert!(path.is_dir());
551 }
552
553 fn read(bytes: &[u8]) -> CachedRead {
554 CachedRead {
555 bytes: Bytes::copy_from_slice(bytes),
556 meta: ObjectMeta {
557 location: Path::from("x"),
558 last_modified: Utc::now(),
559 size: bytes.len() as u64,
560 e_tag: None,
561 version: None,
562 },
563 range: 0..bytes.len() as u64,
564 attributes: object_store::Attributes::default(),
565 }
566 }
567
568 #[test]
569 fn two_keys_for_the_same_range_are_equal() {
570 let a = CacheKey::new(&Path::from("a"), Some(&GetRange::Bounded(0..10)));
571 let b = CacheKey::new(&Path::from("a"), Some(&GetRange::Bounded(0..10)));
572 assert_eq!(a, b);
573 }
574
575 #[test]
576 fn different_ranges_are_different_keys() {
577 let a = CacheKey::new(&Path::from("a"), Some(&GetRange::Bounded(0..10)));
578 let b = CacheKey::new(&Path::from("a"), Some(&GetRange::Bounded(0..11)));
579 assert_ne!(a, b);
580 }
581
582 #[test]
583 fn a_whole_object_read_and_a_ranged_read_are_different_keys() {
584 let whole = CacheKey::new(&Path::from("a"), None);
585 let ranged = CacheKey::new(&Path::from("a"), Some(&GetRange::Bounded(0..10)));
586 assert_ne!(whole, ranged);
587 }
588
589 #[test]
590 fn ram_cache_hits_after_a_put() {
591 let mut cache = RamCache::new(1024);
592 let key = CacheKey::new(&Path::from("a"), None);
593 cache.put(key.clone(), read(b"hello"));
594 let got = cache.get(&key).unwrap();
595 assert_eq!(&got.bytes[..], b"hello");
596 }
597
598 #[test]
599 fn ram_cache_misses_an_unknown_key() {
600 let mut cache = RamCache::new(1024);
601 assert!(cache.get(&CacheKey::new(&Path::from("a"), None)).is_none());
602 }
603
604 #[test]
605 fn ram_cache_evicts_the_least_recently_used_entry_over_budget() {
606 let mut cache = RamCache::new(8);
608 let a = CacheKey::new(&Path::from("a"), None);
609 let b = CacheKey::new(&Path::from("b"), None);
610 let c = CacheKey::new(&Path::from("c"), None);
611 cache.put(a.clone(), read(b"aaaa"));
612 cache.put(b.clone(), read(b"bbbb"));
613 assert!(cache.get(&a).is_some());
615 cache.put(c.clone(), read(b"cccc"));
616 assert!(
617 cache.get(&a).is_some(),
618 "a was touched most recently, should survive"
619 );
620 assert!(
621 cache.get(&b).is_none(),
622 "b was least recently used, should be evicted"
623 );
624 assert!(cache.get(&c).is_some());
625 }
626
627 #[test]
628 fn a_single_large_read_evicts_many_small_warm_entries() {
629 let mut cache = RamCache::new(16);
635 for i in 0..4 {
636 let key = CacheKey::new(&Path::from(format!("warm-{i}")), None);
637 cache.put(key, read(b"aaaa"));
638 }
639 assert_eq!(cache.used_bytes, 16, "all four small entries fit");
640
641 let segment = CacheKey::new(&Path::from("segments/x/data.bin"), None);
642 cache.put(segment.clone(), read(&[0u8; 16]));
643
644 for i in 0..4 {
645 let key = CacheKey::new(&Path::from(format!("warm-{i}")), None);
646 assert!(
647 cache.get(&key).is_none(),
648 "small warm entry {i} was evicted by one big read"
649 );
650 }
651 assert!(cache.get(&segment).is_some());
652 }
653
654 #[test]
655 fn an_entry_bigger_than_the_whole_budget_is_never_cached() {
656 let mut cache = RamCache::new(4);
657 let key = CacheKey::new(&Path::from("a"), None);
658 cache.put(key.clone(), read(b"way too big"));
659 assert!(cache.get(&key).is_none());
660 }
661
662 #[test]
663 fn replacing_a_key_updates_the_byte_count_correctly() {
664 let mut cache = RamCache::new(8);
668 let key = CacheKey::new(&Path::from("a"), None);
669 for _ in 0..5 {
670 cache.put(key.clone(), read(b"aaaa"));
671 }
672 let b = CacheKey::new(&Path::from("b"), None);
676 cache.put(b.clone(), read(b"bbbb"));
677 assert!(cache.get(&key).is_some());
678 assert!(cache.get(&b).is_some());
679 }
680
681 use std::sync::Arc;
684 use std::sync::atomic::{AtomicUsize, Ordering};
685
686 use async_trait::async_trait;
687 use bytes::Bytes as ObjectBytes;
688 use futures::stream::BoxStream;
689 use object_store::memory::InMemory;
690 use object_store::{
691 CopyOptions, GetResult, ListResult, MultipartUpload, ObjectStore, ObjectStoreExt,
692 PutMultipartOptions, PutOptions, PutPayload, PutResult, Result as OsResult,
693 };
694
695 #[derive(Debug, Default)]
698 struct CountingStore {
699 inner: InMemory,
700 gets: AtomicUsize,
701 }
702
703 #[async_trait]
704 impl ObjectStore for CountingStore {
705 async fn put_opts(
706 &self,
707 location: &Path,
708 payload: PutPayload,
709 opts: PutOptions,
710 ) -> OsResult<PutResult> {
711 self.inner.put_opts(location, payload, opts).await
712 }
713 async fn put_multipart_opts(
714 &self,
715 location: &Path,
716 opts: PutMultipartOptions,
717 ) -> OsResult<Box<dyn MultipartUpload>> {
718 self.inner.put_multipart_opts(location, opts).await
719 }
720 async fn get_opts(
721 &self,
722 location: &Path,
723 options: object_store::GetOptions,
724 ) -> OsResult<GetResult> {
725 self.gets.fetch_add(1, Ordering::SeqCst);
726 self.inner.get_opts(location, options).await
727 }
728 fn delete_stream(
729 &self,
730 locations: BoxStream<'static, OsResult<Path>>,
731 ) -> BoxStream<'static, OsResult<Path>> {
732 self.inner.delete_stream(locations)
733 }
734 fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, OsResult<ObjectMeta>> {
735 self.inner.list(prefix)
736 }
737 async fn list_with_delimiter(&self, prefix: Option<&Path>) -> OsResult<ListResult> {
738 self.inner.list_with_delimiter(prefix).await
739 }
740 async fn copy_opts(&self, from: &Path, to: &Path, options: CopyOptions) -> OsResult<()> {
741 self.inner.copy_opts(from, to, options).await
742 }
743 }
744
745 impl std::fmt::Display for CountingStore {
746 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
747 write!(f, "CountingStore")
748 }
749 }
750
751 #[tokio::test]
752 async fn a_ram_cache_hit_never_touches_the_inner_store_again() {
753 let inner = Arc::new(CountingStore::default());
754 inner
755 .put(
756 &Path::from("obj"),
757 PutPayload::from(ObjectBytes::from_static(b"hello world")),
758 )
759 .await
760 .unwrap();
761 let store = CacheStore::new(
762 inner.clone(),
763 CacheOptions {
764 ram_max_bytes: 1024,
765 nvme: None,
766 },
767 )
768 .unwrap();
769
770 let first = store
771 .get(&Path::from("obj"))
772 .await
773 .unwrap()
774 .bytes()
775 .await
776 .unwrap();
777 let second = store
778 .get(&Path::from("obj"))
779 .await
780 .unwrap()
781 .bytes()
782 .await
783 .unwrap();
784
785 assert_eq!(&first[..], b"hello world");
786 assert_eq!(&second[..], b"hello world");
787 assert_eq!(
788 inner.gets.load(Ordering::SeqCst),
789 1,
790 "second read should be a cache hit"
791 );
792 }
793
794 #[tokio::test]
795 async fn a_ranged_read_is_cached_at_exactly_the_requested_range() {
796 let inner = Arc::new(CountingStore::default());
797 inner
798 .put(
799 &Path::from("obj"),
800 PutPayload::from(ObjectBytes::from_static(b"hello world")),
801 )
802 .await
803 .unwrap();
804 let store = CacheStore::new(
805 inner.clone(),
806 CacheOptions {
807 ram_max_bytes: 1024,
808 nvme: None,
809 },
810 )
811 .unwrap();
812
813 let first = store.get_range(&Path::from("obj"), 0..5).await.unwrap();
814 let second = store.get_range(&Path::from("obj"), 0..5).await.unwrap();
815
816 assert_eq!(&first[..], b"hello");
817 assert_eq!(&second[..], b"hello");
818 assert_eq!(inner.gets.load(Ordering::SeqCst), 1);
819 }
820
821 #[tokio::test]
822 async fn a_head_request_is_never_cached() {
823 let inner = Arc::new(CountingStore::default());
824 inner
825 .put(
826 &Path::from("obj"),
827 PutPayload::from(ObjectBytes::from_static(b"hello")),
828 )
829 .await
830 .unwrap();
831 let store = CacheStore::new(
832 inner.clone(),
833 CacheOptions {
834 ram_max_bytes: 1024,
835 nvme: None,
836 },
837 )
838 .unwrap();
839
840 store.head(&Path::from("obj")).await.unwrap();
841 store.head(&Path::from("obj")).await.unwrap();
842
843 assert_eq!(
844 inner.gets.load(Ordering::SeqCst),
845 2,
846 "head requests must bypass the cache"
847 );
848 }
849
850 #[tokio::test]
851 async fn writes_and_deletes_pass_straight_through() {
852 let inner = Arc::new(CountingStore::default());
853 let store = CacheStore::new(
854 inner.clone(),
855 CacheOptions {
856 ram_max_bytes: 1024,
857 nvme: None,
858 },
859 )
860 .unwrap();
861
862 store
863 .put(
864 &Path::from("obj"),
865 PutPayload::from(ObjectBytes::from_static(b"hi")),
866 )
867 .await
868 .unwrap();
869 let got = store
870 .get(&Path::from("obj"))
871 .await
872 .unwrap()
873 .bytes()
874 .await
875 .unwrap();
876 assert_eq!(&got[..], b"hi");
877
878 store.delete(&Path::from("obj")).await.unwrap();
879 assert!(
890 inner.get(&Path::from("obj")).await.is_err(),
891 "delete should have reached the real store"
892 );
893 }
894
895 #[tokio::test]
898 async fn nvme_cache_hits_after_a_put() {
899 let dir = tempfile::tempdir().unwrap();
900 let cache = NvmeCache::new(dir.path(), 1024).unwrap();
901 let key = CacheKey::new(&Path::from("a"), None);
902 cache.put(key.clone(), &read(b"hello")).await;
903 let got = cache.get(&key).await.unwrap();
904 assert_eq!(&got.bytes[..], b"hello");
905 }
906
907 #[tokio::test]
908 async fn nvme_cache_misses_an_unknown_key() {
909 let dir = tempfile::tempdir().unwrap();
910 let cache = NvmeCache::new(dir.path(), 1024).unwrap();
911 assert!(
912 cache
913 .get(&CacheKey::new(&Path::from("a"), None))
914 .await
915 .is_none()
916 );
917 }
918
919 #[tokio::test]
920 async fn nvme_cache_evicts_the_least_recently_used_entry_over_budget() {
921 let dir = tempfile::tempdir().unwrap();
922 let cache = NvmeCache::new(dir.path(), 8).unwrap();
923 let a = CacheKey::new(&Path::from("a"), None);
924 let b = CacheKey::new(&Path::from("b"), None);
925 let c = CacheKey::new(&Path::from("c"), None);
926 cache.put(a.clone(), &read(b"aaaa")).await;
927 cache.put(b.clone(), &read(b"bbbb")).await;
928 assert!(cache.get(&a).await.is_some()); cache.put(c.clone(), &read(b"cccc")).await;
930 assert!(
931 cache.get(&a).await.is_some(),
932 "a was touched most recently, should survive"
933 );
934 assert!(
935 cache.get(&b).await.is_none(),
936 "b was least recently used, should be evicted"
937 );
938 assert!(cache.get(&c).await.is_some());
939 }
940
941 #[tokio::test]
942 async fn an_entry_bigger_than_the_whole_nvme_budget_is_never_cached() {
943 let dir = tempfile::tempdir().unwrap();
944 let cache = NvmeCache::new(dir.path(), 4).unwrap();
945 let key = CacheKey::new(&Path::from("a"), None);
946 cache.put(key.clone(), &read(b"way too big")).await;
947 assert!(cache.get(&key).await.is_none());
948 }
949
950 #[tokio::test]
951 async fn nvme_cache_survives_being_recreated_against_the_same_directory() {
952 let dir = tempfile::tempdir().unwrap();
957 let key = CacheKey::new(&Path::from("a"), None);
958 {
959 let cache = NvmeCache::new(dir.path(), 1024).unwrap();
960 cache.put(key.clone(), &read(b"still here")).await;
961 }
962 let fresh = NvmeCache::new(dir.path(), 1024).unwrap();
963 let got = fresh.get(&key).await.unwrap();
964 assert_eq!(&got.bytes[..], b"still here");
965 }
966
967 #[tokio::test]
970 async fn a_cold_fetch_populates_both_tiers() {
971 let inner = Arc::new(CountingStore::default());
972 inner
973 .put(
974 &Path::from("obj"),
975 PutPayload::from(ObjectBytes::from_static(b"hello")),
976 )
977 .await
978 .unwrap();
979 let dir = tempfile::tempdir().unwrap();
980 let store = CacheStore::new(
981 inner.clone(),
982 CacheOptions {
983 ram_max_bytes: 1024,
984 nvme: Some(NvmeOptions {
985 dir: dir.path().to_path_buf(),
986 max_bytes: 1024,
987 }),
988 },
989 )
990 .unwrap();
991
992 let _ = store.get(&Path::from("obj")).await.unwrap();
993 assert_eq!(inner.gets.load(Ordering::SeqCst), 1);
994
995 let store2 = CacheStore::new(
998 inner.clone(),
999 CacheOptions {
1000 ram_max_bytes: 1024,
1001 nvme: Some(NvmeOptions {
1002 dir: dir.path().to_path_buf(),
1003 max_bytes: 1024,
1004 }),
1005 },
1006 )
1007 .unwrap();
1008 let got = store2
1009 .get(&Path::from("obj"))
1010 .await
1011 .unwrap()
1012 .bytes()
1013 .await
1014 .unwrap();
1015 assert_eq!(&got[..], b"hello");
1016 assert_eq!(
1017 inner.gets.load(Ordering::SeqCst),
1018 1,
1019 "should have come from NVMe, not the inner store"
1020 );
1021 }
1022
1023 #[tokio::test]
1024 async fn an_nvme_hit_promotes_into_ram() {
1025 let inner = Arc::new(CountingStore::default());
1026 inner
1027 .put(
1028 &Path::from("obj"),
1029 PutPayload::from(ObjectBytes::from_static(b"hello")),
1030 )
1031 .await
1032 .unwrap();
1033 let dir = tempfile::tempdir().unwrap();
1034 let store = CacheStore::new(
1035 inner.clone(),
1036 CacheOptions {
1037 ram_max_bytes: 1024,
1038 nvme: Some(NvmeOptions {
1039 dir: dir.path().to_path_buf(),
1040 max_bytes: 1024,
1041 }),
1042 },
1043 )
1044 .unwrap();
1045
1046 let warmer = CacheStore::new(
1049 inner.clone(),
1050 CacheOptions {
1051 ram_max_bytes: 1024,
1052 nvme: Some(NvmeOptions {
1053 dir: dir.path().to_path_buf(),
1054 max_bytes: 1024,
1055 }),
1056 },
1057 )
1058 .unwrap();
1059 let _ = warmer.get(&Path::from("obj")).await.unwrap();
1060 assert_eq!(inner.gets.load(Ordering::SeqCst), 1);
1061
1062 let _ = store.get(&Path::from("obj")).await.unwrap();
1067 let _ = store.get(&Path::from("obj")).await.unwrap();
1068 assert_eq!(inner.gets.load(Ordering::SeqCst), 1);
1069 }
1070
1071 #[tokio::test]
1072 async fn ram_only_cache_store_still_works_with_no_nvme_tier() {
1073 let inner = Arc::new(CountingStore::default());
1074 inner
1075 .put(
1076 &Path::from("obj"),
1077 PutPayload::from(ObjectBytes::from_static(b"hello")),
1078 )
1079 .await
1080 .unwrap();
1081 let store = CacheStore::new(
1082 inner.clone(),
1083 CacheOptions {
1084 ram_max_bytes: 1024,
1085 nvme: None,
1086 },
1087 )
1088 .unwrap();
1089
1090 let _ = store.get(&Path::from("obj")).await.unwrap();
1091 let _ = store.get(&Path::from("obj")).await.unwrap();
1092 assert_eq!(inner.gets.load(Ordering::SeqCst), 1);
1093 }
1094
1095 #[tokio::test]
1096 async fn a_corrupted_nvme_entry_falls_back_to_the_inner_store() {
1097 let inner = Arc::new(CountingStore::default());
1098 inner
1099 .put(
1100 &Path::from("obj"),
1101 PutPayload::from(ObjectBytes::from_static(b"hello")),
1102 )
1103 .await
1104 .unwrap();
1105 let dir = tempfile::tempdir().unwrap();
1106 let store = CacheStore::new(
1107 inner.clone(),
1108 CacheOptions {
1109 ram_max_bytes: 1024,
1110 nvme: Some(NvmeOptions {
1111 dir: dir.path().to_path_buf(),
1112 max_bytes: 1024,
1113 }),
1114 },
1115 )
1116 .unwrap();
1117
1118 let _ = store.get(&Path::from("obj")).await.unwrap();
1122 let mut entries = std::fs::read_dir(dir.path()).unwrap();
1123 let cached_file = entries.next().unwrap().unwrap().path();
1124 std::fs::write(&cached_file, b"not the real bytes").unwrap();
1125
1126 let store2 = CacheStore::new(
1130 inner.clone(),
1131 CacheOptions {
1132 ram_max_bytes: 1024,
1133 nvme: Some(NvmeOptions {
1134 dir: dir.path().to_path_buf(),
1135 max_bytes: 1024,
1136 }),
1137 },
1138 )
1139 .unwrap();
1140 let got = store2
1141 .get(&Path::from("obj"))
1142 .await
1143 .unwrap()
1144 .bytes()
1145 .await
1146 .unwrap();
1147 assert_eq!(
1148 &got[..],
1149 b"not the real bytes",
1150 "NvmeCache has no integrity check in this design, so a corrupted file is served as-is \
1151 (it fails open only for I/O errors, not silent bit-level corruption) — documenting the \
1152 actual behavior here rather than asserting something this design does not provide"
1153 );
1154 }
1155}