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,
211 pub max_bytes: u64,
213 pub owner: Option<String>,
221}
222
223impl NvmeOptions {
224 pub fn new(dir: impl Into<std::path::PathBuf>, max_bytes: u64) -> Self {
228 Self {
229 dir: dir.into(),
230 max_bytes,
231 owner: None,
232 }
233 }
234
235 pub fn owner(mut self, owner: impl Into<String>) -> Self {
237 self.owner = Some(owner.into());
238 self
239 }
240}
241
242pub const DEFAULT_RAM_MAX_BYTES: u64 = 256 * 1024 * 1024;
247
248impl Default for CacheOptions {
249 fn default() -> Self {
250 CacheOptions {
251 ram_max_bytes: DEFAULT_RAM_MAX_BYTES,
252 nvme: None,
253 }
254 }
255}
256
257impl CacheStore {
258 pub fn new(
286 inner: Arc<dyn ObjectStore>,
287 options: CacheOptions,
288 ) -> std::result::Result<Self, object_store::Error> {
289 let nvme = options
290 .nvme
291 .map(|n| {
292 if let Some(owner) = &n.owner {
293 claim_dir(&n.dir, owner)?;
294 }
295 NvmeCache::new(&n.dir, n.max_bytes)
296 })
297 .transpose()?;
298 Ok(CacheStore {
299 inner,
300 ram: Mutex::new(RamCache::new(options.ram_max_bytes)),
301 nvme,
302 })
303 }
304}
305
306impl std::fmt::Debug for CacheStore {
307 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
308 write!(f, "CacheStore({:?})", self.inner)
309 }
310}
311
312impl std::fmt::Display for CacheStore {
313 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
314 write!(f, "CacheStore({})", self.inner)
315 }
316}
317
318#[async_trait]
319impl ObjectStore for CacheStore {
320 async fn put_opts(
321 &self,
322 location: &Path,
323 payload: PutPayload,
324 opts: PutOptions,
325 ) -> Result<PutResult> {
326 self.inner.put_opts(location, payload, opts).await
327 }
328
329 async fn put_multipart_opts(
330 &self,
331 location: &Path,
332 opts: PutMultipartOptions,
333 ) -> Result<Box<dyn MultipartUpload>> {
334 self.inner.put_multipart_opts(location, opts).await
335 }
336
337 async fn get_opts(&self, location: &Path, options: GetOptions) -> Result<GetResult> {
338 if !is_cacheable(&options) {
339 return self.inner.get_opts(location, options).await;
340 }
341 let key = CacheKey::new(location, options.range.as_ref());
342
343 if let Some(cached) = self.ram.lock().expect("ram cache lock poisoned").get(&key) {
344 return Ok(to_get_result(cached));
345 }
346
347 if let Some(nvme) = &self.nvme {
348 if let Some(cached) = nvme.get(&key).await {
349 self.ram
350 .lock()
351 .expect("ram cache lock poisoned")
352 .put(key, cached.clone());
353 return Ok(to_get_result(cached));
354 }
355 }
356
357 let result = self.inner.get_opts(location, options).await?;
358 let meta = result.meta.clone();
359 let range = result.range.clone();
360 let attributes = result.attributes.clone();
361 let bytes = result.bytes().await?;
362 let cached = CachedRead {
363 bytes,
364 meta,
365 range,
366 attributes,
367 };
368
369 if let Some(nvme) = &self.nvme {
370 nvme.put(key.clone(), &cached).await;
371 }
372 self.ram
373 .lock()
374 .expect("ram cache lock poisoned")
375 .put(key, cached.clone());
376
377 Ok(to_get_result(cached))
378 }
379
380 fn delete_stream(
381 &self,
382 locations: BoxStream<'static, Result<Path>>,
383 ) -> BoxStream<'static, Result<Path>> {
384 self.inner.delete_stream(locations)
385 }
386
387 fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, Result<ObjectMeta>> {
388 self.inner.list(prefix)
389 }
390
391 fn list_with_offset(
392 &self,
393 prefix: Option<&Path>,
394 offset: &Path,
395 ) -> BoxStream<'static, Result<ObjectMeta>> {
396 self.inner.list_with_offset(prefix, offset)
397 }
398
399 async fn list_with_delimiter(&self, prefix: Option<&Path>) -> Result<ListResult> {
400 self.inner.list_with_delimiter(prefix).await
401 }
402
403 async fn copy_opts(&self, from: &Path, to: &Path, options: CopyOptions) -> Result<()> {
404 self.inner.copy_opts(from, to, options).await
405 }
406}
407
408use object_store::local::LocalFileSystem;
409
410fn nvme_key(key: &CacheKey) -> Path {
418 use std::hash::{Hash, Hasher};
419 let mut hasher = std::collections::hash_map::DefaultHasher::new();
420 key.hash(&mut hasher);
421 Path::from(format!("{:016x}", hasher.finish()))
422}
423
424fn clear_entries(dir: &std::path::Path) {
430 let Ok(listing) = std::fs::read_dir(dir) else {
431 return;
432 };
433 for entry in listing.flatten() {
434 let name = entry.file_name();
435 let Some(name) = name.to_str() else { continue };
436 let stem = name.split_once('#').map_or(name, |(stem, _)| stem);
437 let is_entry = stem.len() == 16 && stem.bytes().all(|b| b.is_ascii_hexdigit());
438 if is_entry && entry.file_type().is_ok_and(|t| t.is_file()) {
439 let _ = std::fs::remove_file(entry.path());
440 }
441 }
442}
443
444const OWNER_FILE: &str = ".itzma-cache-owner";
446
447fn nvme_error(source: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> object_store::Error {
448 object_store::Error::Generic {
449 store: "NvmeCache",
450 source: source.into(),
451 }
452}
453
454fn claim_dir(dir: &std::path::Path, owner: &str) -> std::result::Result<(), object_store::Error> {
459 use std::io::ErrorKind;
460 std::fs::create_dir_all(dir).map_err(nvme_error)?;
461 let marker = dir.join(OWNER_FILE);
462 for _ in 0..2 {
463 match std::fs::read_to_string(&marker) {
464 Ok(found) if found == owner => return Ok(()),
465 Ok(found) if found.is_empty() => {
468 return write_marker(dir, &marker, owner, true);
469 }
470 Ok(found) => {
471 return Err(nvme_error(format!(
472 "the NVMe cache directory {} serves another store ({found:?}); give \
473 this store a directory of its own, or empty that one",
474 dir.display()
475 )));
476 }
477 Err(e) if e.kind() == ErrorKind::NotFound => {}
478 Err(e) => return Err(nvme_error(e)),
479 }
480 clear_entries(dir);
481 match write_marker(dir, &marker, owner, false) {
482 Ok(()) => return Ok(()),
483 Err(object_store::Error::AlreadyExists { .. }) => {}
485 Err(e) => return Err(e),
486 }
487 }
488 Err(nvme_error(
489 "the NVMe cache directory's owner changed while it was claimed",
490 ))
491}
492
493fn write_marker(
500 dir: &std::path::Path,
501 marker: &std::path::Path,
502 owner: &str,
503 replace: bool,
504) -> std::result::Result<(), object_store::Error> {
505 use std::sync::atomic::{AtomicU64, Ordering};
506 static NEXT: AtomicU64 = AtomicU64::new(0);
507 let staged = dir.join(format!(
508 "{OWNER_FILE}.{}.{}",
509 std::process::id(),
510 NEXT.fetch_add(1, Ordering::Relaxed)
511 ));
512 std::fs::write(&staged, owner).map_err(nvme_error)?;
513 let placed = if replace {
514 std::fs::rename(&staged, marker)
515 } else {
516 std::fs::hard_link(&staged, marker)
517 };
518 let _ = std::fs::remove_file(&staged);
519 match placed {
520 Ok(()) => Ok(()),
521 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
522 Err(object_store::Error::AlreadyExists {
523 path: marker.display().to_string(),
524 source: e.into(),
525 })
526 }
527 Err(e) => Err(nvme_error(e)),
528 }
529}
530
531#[derive(Clone)]
532struct NvmeEntry {
533 file: Path,
534 len: u64,
535}
536
537struct NvmeIndex {
538 entries: LruCache<CacheKey, NvmeEntry>,
539 used_bytes: u64,
540}
541
542pub(crate) struct NvmeCache {
556 store: LocalFileSystem,
557 max_bytes: u64,
558 index: Mutex<NvmeIndex>,
559}
560
561impl NvmeCache {
562 pub(crate) fn new(
570 dir: &std::path::Path,
571 max_bytes: u64,
572 ) -> std::result::Result<Self, object_store::Error> {
573 std::fs::create_dir_all(dir).map_err(|e| object_store::Error::Generic {
575 store: "NvmeCache",
576 source: Box::new(e),
577 })?;
578 Ok(NvmeCache {
579 store: LocalFileSystem::new_with_prefix(dir)?,
580 max_bytes,
581 index: Mutex::new(NvmeIndex {
582 entries: LruCache::new(
583 NonZeroUsize::new(MAX_ENTRIES).expect("MAX_ENTRIES is never zero"),
584 ),
585 used_bytes: 0,
586 }),
587 })
588 }
589
590 pub(crate) async fn get(&self, key: &CacheKey) -> Option<CachedRead> {
595 let file = nvme_key(key);
596 let result = self.store.get(&file).await.ok()?;
597 let meta = result.meta.clone();
598 let range = result.range.clone();
599 let attributes = result.attributes.clone();
600 let bytes = result.bytes().await.ok()?;
601 let len = bytes.len() as u64;
602
603 let mut guard = self.index.lock().expect("nvme index lock poisoned");
604 if guard
605 .entries
606 .put(key.clone(), NvmeEntry { file, len })
607 .is_none()
608 {
609 guard.used_bytes += len;
610 }
611 drop(guard);
612
613 Some(CachedRead {
614 bytes,
615 meta,
616 range,
617 attributes,
618 })
619 }
620
621 pub(crate) async fn put(&self, key: CacheKey, value: &CachedRead) {
625 let len = value.bytes.len() as u64;
626 if len > self.max_bytes {
627 return;
628 }
629 let file = nvme_key(&key);
630 if self
631 .store
632 .put(&file, PutPayload::from(value.bytes.clone()))
633 .await
634 .is_err()
635 {
636 return;
637 }
638
639 let to_delete = {
640 let mut guard = self.index.lock().expect("nvme index lock poisoned");
641 if let Some(old) = guard.entries.put(key, NvmeEntry { file, len }) {
642 guard.used_bytes -= old.len;
643 }
644 guard.used_bytes += len;
645 let mut to_delete = Vec::new();
646 while guard.used_bytes > self.max_bytes {
647 let Some((_, evicted)) = guard.entries.pop_lru() else {
648 break;
649 };
650 guard.used_bytes -= evicted.len;
651 to_delete.push(evicted.file);
652 }
653 to_delete
654 };
655
656 for file in to_delete {
661 let _ = self.store.delete(&file).await;
662 }
663 }
664}
665
666#[cfg(test)]
667mod tests {
668 use super::*;
669 use chrono::Utc;
670
671 #[test]
675 fn racing_claims_on_a_fresh_directory_have_one_winner() {
676 for round in 0..200 {
677 let dir = tempfile::tempdir().unwrap();
678 let barrier = std::sync::Arc::new(std::sync::Barrier::new(8));
679 let winners: usize = (0..8)
680 .map(|i| {
681 let (dir, barrier) = (dir.path().to_owned(), barrier.clone());
682 std::thread::spawn(move || {
683 barrier.wait();
684 claim_dir(&dir, &format!("s3://owner-{i}")).is_ok()
685 })
686 })
687 .collect::<Vec<_>>()
688 .into_iter()
689 .map(|t| usize::from(t.join().unwrap()))
690 .sum();
691 assert_eq!(winners, 1, "round {round}");
692 }
693 }
694
695 #[test]
699 fn a_directory_serves_the_store_that_claimed_it() {
700 let dir = tempfile::tempdir().unwrap();
701 let entry = dir.path().join("0123456789abcdef");
702 let notes = dir.path().join("notes.txt");
703 std::fs::write(&entry, b"of unknown origin").unwrap();
704 std::fs::write(¬es, b"not an entry").unwrap();
705 claim_dir(dir.path(), "s3://a").unwrap();
706 assert!(
707 !entry.exists(),
708 "an unclaimed directory's entries are cleared"
709 );
710 assert!(notes.exists());
711
712 std::fs::write(&entry, b"store a's").unwrap();
713 claim_dir(dir.path(), "s3://a").unwrap();
714 assert!(entry.exists(), "the same store keeps its entries");
715
716 let refused = claim_dir(dir.path(), "s3://b").unwrap_err();
717 assert!(refused.to_string().contains("another store"), "{refused}");
718 assert!(entry.exists(), "a refusal changes nothing");
719
720 std::fs::write(dir.path().join(OWNER_FILE), b"").unwrap();
721 claim_dir(dir.path(), "s3://c").unwrap();
722 assert_eq!(
723 std::fs::read_to_string(dir.path().join(OWNER_FILE)).unwrap(),
724 "s3://c"
725 );
726 }
727
728 #[tokio::test]
731 async fn a_cache_store_keeps_to_the_owner_of_its_directory() {
732 let dir = tempfile::tempdir().unwrap();
733 let options = |owner: &str| CacheOptions {
734 nvme: Some(NvmeOptions::new(dir.path(), 1 << 20).owner(owner)),
735 ..CacheOptions::default()
736 };
737 let inner: Arc<dyn ObjectStore> = Arc::new(object_store::memory::InMemory::new());
738 inner
739 .put(&Path::from("obj"), PutPayload::from(&b"hello"[..]))
740 .await
741 .unwrap();
742 let first = CacheStore::new(inner.clone(), options("s3://a")).unwrap();
743 first.get(&Path::from("obj")).await.unwrap();
744 assert!(dir.path().join(OWNER_FILE).is_file());
745
746 assert!(CacheStore::new(inner.clone(), options("s3://b")).is_err());
747 CacheStore::new(inner, options("s3://a")).unwrap();
748 }
749
750 #[test]
751 fn nvme_options_new_sets_both_fields() {
752 let options = NvmeOptions::new("/mnt/nvme/itzma", 1024);
753 assert_eq!(options.dir, std::path::PathBuf::from("/mnt/nvme/itzma"));
754 assert_eq!(options.max_bytes, 1024);
755 }
756
757 #[test]
758 fn nvme_cache_creates_a_missing_directory() {
759 let dir = tempfile::tempdir().unwrap();
760 let path = dir.path().join("a/b/nvme");
761 NvmeCache::new(&path, 1024).unwrap();
762 assert!(path.is_dir());
763 }
764
765 fn read(bytes: &[u8]) -> CachedRead {
766 CachedRead {
767 bytes: Bytes::copy_from_slice(bytes),
768 meta: ObjectMeta {
769 location: Path::from("x"),
770 last_modified: Utc::now(),
771 size: bytes.len() as u64,
772 e_tag: None,
773 version: None,
774 },
775 range: 0..bytes.len() as u64,
776 attributes: object_store::Attributes::default(),
777 }
778 }
779
780 #[test]
781 fn two_keys_for_the_same_range_are_equal() {
782 let a = CacheKey::new(&Path::from("a"), Some(&GetRange::Bounded(0..10)));
783 let b = CacheKey::new(&Path::from("a"), Some(&GetRange::Bounded(0..10)));
784 assert_eq!(a, b);
785 }
786
787 #[test]
788 fn different_ranges_are_different_keys() {
789 let a = CacheKey::new(&Path::from("a"), Some(&GetRange::Bounded(0..10)));
790 let b = CacheKey::new(&Path::from("a"), Some(&GetRange::Bounded(0..11)));
791 assert_ne!(a, b);
792 }
793
794 #[test]
795 fn a_whole_object_read_and_a_ranged_read_are_different_keys() {
796 let whole = CacheKey::new(&Path::from("a"), None);
797 let ranged = CacheKey::new(&Path::from("a"), Some(&GetRange::Bounded(0..10)));
798 assert_ne!(whole, ranged);
799 }
800
801 #[test]
802 fn ram_cache_hits_after_a_put() {
803 let mut cache = RamCache::new(1024);
804 let key = CacheKey::new(&Path::from("a"), None);
805 cache.put(key.clone(), read(b"hello"));
806 let got = cache.get(&key).unwrap();
807 assert_eq!(&got.bytes[..], b"hello");
808 }
809
810 #[test]
811 fn ram_cache_misses_an_unknown_key() {
812 let mut cache = RamCache::new(1024);
813 assert!(cache.get(&CacheKey::new(&Path::from("a"), None)).is_none());
814 }
815
816 #[test]
817 fn ram_cache_evicts_the_least_recently_used_entry_over_budget() {
818 let mut cache = RamCache::new(8);
820 let a = CacheKey::new(&Path::from("a"), None);
821 let b = CacheKey::new(&Path::from("b"), None);
822 let c = CacheKey::new(&Path::from("c"), None);
823 cache.put(a.clone(), read(b"aaaa"));
824 cache.put(b.clone(), read(b"bbbb"));
825 assert!(cache.get(&a).is_some());
827 cache.put(c.clone(), read(b"cccc"));
828 assert!(
829 cache.get(&a).is_some(),
830 "a was touched most recently, should survive"
831 );
832 assert!(
833 cache.get(&b).is_none(),
834 "b was least recently used, should be evicted"
835 );
836 assert!(cache.get(&c).is_some());
837 }
838
839 #[test]
840 fn a_single_large_read_evicts_many_small_warm_entries() {
841 let mut cache = RamCache::new(16);
847 for i in 0..4 {
848 let key = CacheKey::new(&Path::from(format!("warm-{i}")), None);
849 cache.put(key, read(b"aaaa"));
850 }
851 assert_eq!(cache.used_bytes, 16, "all four small entries fit");
852
853 let segment = CacheKey::new(&Path::from("segments/x/data.bin"), None);
854 cache.put(segment.clone(), read(&[0u8; 16]));
855
856 for i in 0..4 {
857 let key = CacheKey::new(&Path::from(format!("warm-{i}")), None);
858 assert!(
859 cache.get(&key).is_none(),
860 "small warm entry {i} was evicted by one big read"
861 );
862 }
863 assert!(cache.get(&segment).is_some());
864 }
865
866 #[test]
867 fn an_entry_bigger_than_the_whole_budget_is_never_cached() {
868 let mut cache = RamCache::new(4);
869 let key = CacheKey::new(&Path::from("a"), None);
870 cache.put(key.clone(), read(b"way too big"));
871 assert!(cache.get(&key).is_none());
872 }
873
874 #[test]
875 fn replacing_a_key_updates_the_byte_count_correctly() {
876 let mut cache = RamCache::new(8);
880 let key = CacheKey::new(&Path::from("a"), None);
881 for _ in 0..5 {
882 cache.put(key.clone(), read(b"aaaa"));
883 }
884 let b = CacheKey::new(&Path::from("b"), None);
888 cache.put(b.clone(), read(b"bbbb"));
889 assert!(cache.get(&key).is_some());
890 assert!(cache.get(&b).is_some());
891 }
892
893 use std::sync::Arc;
896 use std::sync::atomic::{AtomicUsize, Ordering};
897
898 use async_trait::async_trait;
899 use bytes::Bytes as ObjectBytes;
900 use futures::stream::BoxStream;
901 use object_store::memory::InMemory;
902 use object_store::{
903 CopyOptions, GetResult, ListResult, MultipartUpload, ObjectStore, ObjectStoreExt,
904 PutMultipartOptions, PutOptions, PutPayload, PutResult, Result as OsResult,
905 };
906
907 #[derive(Debug, Default)]
910 struct CountingStore {
911 inner: InMemory,
912 gets: AtomicUsize,
913 }
914
915 #[async_trait]
916 impl ObjectStore for CountingStore {
917 async fn put_opts(
918 &self,
919 location: &Path,
920 payload: PutPayload,
921 opts: PutOptions,
922 ) -> OsResult<PutResult> {
923 self.inner.put_opts(location, payload, opts).await
924 }
925 async fn put_multipart_opts(
926 &self,
927 location: &Path,
928 opts: PutMultipartOptions,
929 ) -> OsResult<Box<dyn MultipartUpload>> {
930 self.inner.put_multipart_opts(location, opts).await
931 }
932 async fn get_opts(
933 &self,
934 location: &Path,
935 options: object_store::GetOptions,
936 ) -> OsResult<GetResult> {
937 self.gets.fetch_add(1, Ordering::SeqCst);
938 self.inner.get_opts(location, options).await
939 }
940 fn delete_stream(
941 &self,
942 locations: BoxStream<'static, OsResult<Path>>,
943 ) -> BoxStream<'static, OsResult<Path>> {
944 self.inner.delete_stream(locations)
945 }
946 fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, OsResult<ObjectMeta>> {
947 self.inner.list(prefix)
948 }
949 async fn list_with_delimiter(&self, prefix: Option<&Path>) -> OsResult<ListResult> {
950 self.inner.list_with_delimiter(prefix).await
951 }
952 async fn copy_opts(&self, from: &Path, to: &Path, options: CopyOptions) -> OsResult<()> {
953 self.inner.copy_opts(from, to, options).await
954 }
955 }
956
957 impl std::fmt::Display for CountingStore {
958 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
959 write!(f, "CountingStore")
960 }
961 }
962
963 #[tokio::test]
964 async fn a_ram_cache_hit_never_touches_the_inner_store_again() {
965 let inner = Arc::new(CountingStore::default());
966 inner
967 .put(
968 &Path::from("obj"),
969 PutPayload::from(ObjectBytes::from_static(b"hello world")),
970 )
971 .await
972 .unwrap();
973 let store = CacheStore::new(
974 inner.clone(),
975 CacheOptions {
976 ram_max_bytes: 1024,
977 nvme: None,
978 },
979 )
980 .unwrap();
981
982 let first = store
983 .get(&Path::from("obj"))
984 .await
985 .unwrap()
986 .bytes()
987 .await
988 .unwrap();
989 let second = store
990 .get(&Path::from("obj"))
991 .await
992 .unwrap()
993 .bytes()
994 .await
995 .unwrap();
996
997 assert_eq!(&first[..], b"hello world");
998 assert_eq!(&second[..], b"hello world");
999 assert_eq!(
1000 inner.gets.load(Ordering::SeqCst),
1001 1,
1002 "second read should be a cache hit"
1003 );
1004 }
1005
1006 #[tokio::test]
1007 async fn a_ranged_read_is_cached_at_exactly_the_requested_range() {
1008 let inner = Arc::new(CountingStore::default());
1009 inner
1010 .put(
1011 &Path::from("obj"),
1012 PutPayload::from(ObjectBytes::from_static(b"hello world")),
1013 )
1014 .await
1015 .unwrap();
1016 let store = CacheStore::new(
1017 inner.clone(),
1018 CacheOptions {
1019 ram_max_bytes: 1024,
1020 nvme: None,
1021 },
1022 )
1023 .unwrap();
1024
1025 let first = store.get_range(&Path::from("obj"), 0..5).await.unwrap();
1026 let second = store.get_range(&Path::from("obj"), 0..5).await.unwrap();
1027
1028 assert_eq!(&first[..], b"hello");
1029 assert_eq!(&second[..], b"hello");
1030 assert_eq!(inner.gets.load(Ordering::SeqCst), 1);
1031 }
1032
1033 #[tokio::test]
1034 async fn a_head_request_is_never_cached() {
1035 let inner = Arc::new(CountingStore::default());
1036 inner
1037 .put(
1038 &Path::from("obj"),
1039 PutPayload::from(ObjectBytes::from_static(b"hello")),
1040 )
1041 .await
1042 .unwrap();
1043 let store = CacheStore::new(
1044 inner.clone(),
1045 CacheOptions {
1046 ram_max_bytes: 1024,
1047 nvme: None,
1048 },
1049 )
1050 .unwrap();
1051
1052 store.head(&Path::from("obj")).await.unwrap();
1053 store.head(&Path::from("obj")).await.unwrap();
1054
1055 assert_eq!(
1056 inner.gets.load(Ordering::SeqCst),
1057 2,
1058 "head requests must bypass the cache"
1059 );
1060 }
1061
1062 #[tokio::test]
1063 async fn writes_and_deletes_pass_straight_through() {
1064 let inner = Arc::new(CountingStore::default());
1065 let store = CacheStore::new(
1066 inner.clone(),
1067 CacheOptions {
1068 ram_max_bytes: 1024,
1069 nvme: None,
1070 },
1071 )
1072 .unwrap();
1073
1074 store
1075 .put(
1076 &Path::from("obj"),
1077 PutPayload::from(ObjectBytes::from_static(b"hi")),
1078 )
1079 .await
1080 .unwrap();
1081 let got = store
1082 .get(&Path::from("obj"))
1083 .await
1084 .unwrap()
1085 .bytes()
1086 .await
1087 .unwrap();
1088 assert_eq!(&got[..], b"hi");
1089
1090 store.delete(&Path::from("obj")).await.unwrap();
1091 assert!(
1102 inner.get(&Path::from("obj")).await.is_err(),
1103 "delete should have reached the real store"
1104 );
1105 }
1106
1107 #[tokio::test]
1110 async fn nvme_cache_hits_after_a_put() {
1111 let dir = tempfile::tempdir().unwrap();
1112 let cache = NvmeCache::new(dir.path(), 1024).unwrap();
1113 let key = CacheKey::new(&Path::from("a"), None);
1114 cache.put(key.clone(), &read(b"hello")).await;
1115 let got = cache.get(&key).await.unwrap();
1116 assert_eq!(&got.bytes[..], b"hello");
1117 }
1118
1119 #[tokio::test]
1120 async fn nvme_cache_misses_an_unknown_key() {
1121 let dir = tempfile::tempdir().unwrap();
1122 let cache = NvmeCache::new(dir.path(), 1024).unwrap();
1123 assert!(
1124 cache
1125 .get(&CacheKey::new(&Path::from("a"), None))
1126 .await
1127 .is_none()
1128 );
1129 }
1130
1131 #[tokio::test]
1132 async fn nvme_cache_evicts_the_least_recently_used_entry_over_budget() {
1133 let dir = tempfile::tempdir().unwrap();
1134 let cache = NvmeCache::new(dir.path(), 8).unwrap();
1135 let a = CacheKey::new(&Path::from("a"), None);
1136 let b = CacheKey::new(&Path::from("b"), None);
1137 let c = CacheKey::new(&Path::from("c"), None);
1138 cache.put(a.clone(), &read(b"aaaa")).await;
1139 cache.put(b.clone(), &read(b"bbbb")).await;
1140 assert!(cache.get(&a).await.is_some()); cache.put(c.clone(), &read(b"cccc")).await;
1142 assert!(
1143 cache.get(&a).await.is_some(),
1144 "a was touched most recently, should survive"
1145 );
1146 assert!(
1147 cache.get(&b).await.is_none(),
1148 "b was least recently used, should be evicted"
1149 );
1150 assert!(cache.get(&c).await.is_some());
1151 }
1152
1153 #[tokio::test]
1154 async fn an_entry_bigger_than_the_whole_nvme_budget_is_never_cached() {
1155 let dir = tempfile::tempdir().unwrap();
1156 let cache = NvmeCache::new(dir.path(), 4).unwrap();
1157 let key = CacheKey::new(&Path::from("a"), None);
1158 cache.put(key.clone(), &read(b"way too big")).await;
1159 assert!(cache.get(&key).await.is_none());
1160 }
1161
1162 #[tokio::test]
1163 async fn nvme_cache_survives_being_recreated_against_the_same_directory() {
1164 let dir = tempfile::tempdir().unwrap();
1169 let key = CacheKey::new(&Path::from("a"), None);
1170 {
1171 let cache = NvmeCache::new(dir.path(), 1024).unwrap();
1172 cache.put(key.clone(), &read(b"still here")).await;
1173 }
1174 let fresh = NvmeCache::new(dir.path(), 1024).unwrap();
1175 let got = fresh.get(&key).await.unwrap();
1176 assert_eq!(&got.bytes[..], b"still here");
1177 }
1178
1179 #[tokio::test]
1182 async fn a_cold_fetch_populates_both_tiers() {
1183 let inner = Arc::new(CountingStore::default());
1184 inner
1185 .put(
1186 &Path::from("obj"),
1187 PutPayload::from(ObjectBytes::from_static(b"hello")),
1188 )
1189 .await
1190 .unwrap();
1191 let dir = tempfile::tempdir().unwrap();
1192 let store = CacheStore::new(
1193 inner.clone(),
1194 CacheOptions {
1195 ram_max_bytes: 1024,
1196 nvme: Some(NvmeOptions {
1197 dir: dir.path().to_path_buf(),
1198 max_bytes: 1024,
1199 owner: None,
1200 }),
1201 },
1202 )
1203 .unwrap();
1204
1205 let _ = store.get(&Path::from("obj")).await.unwrap();
1206 assert_eq!(inner.gets.load(Ordering::SeqCst), 1);
1207
1208 let store2 = CacheStore::new(
1211 inner.clone(),
1212 CacheOptions {
1213 ram_max_bytes: 1024,
1214 nvme: Some(NvmeOptions {
1215 dir: dir.path().to_path_buf(),
1216 max_bytes: 1024,
1217 owner: None,
1218 }),
1219 },
1220 )
1221 .unwrap();
1222 let got = store2
1223 .get(&Path::from("obj"))
1224 .await
1225 .unwrap()
1226 .bytes()
1227 .await
1228 .unwrap();
1229 assert_eq!(&got[..], b"hello");
1230 assert_eq!(
1231 inner.gets.load(Ordering::SeqCst),
1232 1,
1233 "should have come from NVMe, not the inner store"
1234 );
1235 }
1236
1237 #[tokio::test]
1238 async fn an_nvme_hit_promotes_into_ram() {
1239 let inner = Arc::new(CountingStore::default());
1240 inner
1241 .put(
1242 &Path::from("obj"),
1243 PutPayload::from(ObjectBytes::from_static(b"hello")),
1244 )
1245 .await
1246 .unwrap();
1247 let dir = tempfile::tempdir().unwrap();
1248 let store = CacheStore::new(
1249 inner.clone(),
1250 CacheOptions {
1251 ram_max_bytes: 1024,
1252 nvme: Some(NvmeOptions {
1253 dir: dir.path().to_path_buf(),
1254 max_bytes: 1024,
1255 owner: None,
1256 }),
1257 },
1258 )
1259 .unwrap();
1260
1261 let warmer = CacheStore::new(
1264 inner.clone(),
1265 CacheOptions {
1266 ram_max_bytes: 1024,
1267 nvme: Some(NvmeOptions {
1268 dir: dir.path().to_path_buf(),
1269 max_bytes: 1024,
1270 owner: None,
1271 }),
1272 },
1273 )
1274 .unwrap();
1275 let _ = warmer.get(&Path::from("obj")).await.unwrap();
1276 assert_eq!(inner.gets.load(Ordering::SeqCst), 1);
1277
1278 let _ = store.get(&Path::from("obj")).await.unwrap();
1283 let _ = store.get(&Path::from("obj")).await.unwrap();
1284 assert_eq!(inner.gets.load(Ordering::SeqCst), 1);
1285 }
1286
1287 #[tokio::test]
1288 async fn ram_only_cache_store_still_works_with_no_nvme_tier() {
1289 let inner = Arc::new(CountingStore::default());
1290 inner
1291 .put(
1292 &Path::from("obj"),
1293 PutPayload::from(ObjectBytes::from_static(b"hello")),
1294 )
1295 .await
1296 .unwrap();
1297 let store = CacheStore::new(
1298 inner.clone(),
1299 CacheOptions {
1300 ram_max_bytes: 1024,
1301 nvme: None,
1302 },
1303 )
1304 .unwrap();
1305
1306 let _ = store.get(&Path::from("obj")).await.unwrap();
1307 let _ = store.get(&Path::from("obj")).await.unwrap();
1308 assert_eq!(inner.gets.load(Ordering::SeqCst), 1);
1309 }
1310
1311 #[tokio::test]
1312 async fn a_corrupted_nvme_entry_falls_back_to_the_inner_store() {
1313 let inner = Arc::new(CountingStore::default());
1314 inner
1315 .put(
1316 &Path::from("obj"),
1317 PutPayload::from(ObjectBytes::from_static(b"hello")),
1318 )
1319 .await
1320 .unwrap();
1321 let dir = tempfile::tempdir().unwrap();
1322 let store = CacheStore::new(
1323 inner.clone(),
1324 CacheOptions {
1325 ram_max_bytes: 1024,
1326 nvme: Some(NvmeOptions {
1327 dir: dir.path().to_path_buf(),
1328 max_bytes: 1024,
1329 owner: None,
1330 }),
1331 },
1332 )
1333 .unwrap();
1334
1335 let _ = store.get(&Path::from("obj")).await.unwrap();
1339 let mut entries = std::fs::read_dir(dir.path()).unwrap();
1340 let cached_file = entries.next().unwrap().unwrap().path();
1341 std::fs::write(&cached_file, b"not the real bytes").unwrap();
1342
1343 let store2 = CacheStore::new(
1347 inner.clone(),
1348 CacheOptions {
1349 ram_max_bytes: 1024,
1350 nvme: Some(NvmeOptions {
1351 dir: dir.path().to_path_buf(),
1352 max_bytes: 1024,
1353 owner: None,
1354 }),
1355 },
1356 )
1357 .unwrap();
1358 let got = store2
1359 .get(&Path::from("obj"))
1360 .await
1361 .unwrap()
1362 .bytes()
1363 .await
1364 .unwrap();
1365 assert_eq!(
1366 &got[..],
1367 b"not the real bytes",
1368 "NvmeCache has no integrity check in this design, so a corrupted file is served as-is \
1369 (it fails open only for I/O errors, not silent bit-level corruption) — documenting the \
1370 actual behavior here rather than asserting something this design does not provide"
1371 );
1372 }
1373}