1use super::config::{BlobCacheConfig, L2Compression, L2PromotionPolicy};
8use super::entry::{effective_expires_at_unix_ms, jitter_seed, Entry};
9use super::l2::BlobCacheL2;
10use super::l2_backend::BlobCacheL2Backend;
11use super::l2_store::StoreBlobCacheL2;
12use super::shard::{InsertOutcome, Lookup, Shard, ShardSweep};
13
14use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
15use std::hash::{Hash, Hasher};
16#[cfg(test)]
17use std::path::{Path, PathBuf};
18use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
19use std::sync::{Arc, OnceLock, Weak};
20use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
21
22use indexmap::Equivalent;
23use parking_lot::RwLock;
24
25use super::super::compressor::{CompressOpts, Compressed, L2BlobCompressor};
26use super::super::extended_ttl::ExtendedTtlPolicy;
27use super::super::promotion_pool::{
28 AsyncPromotionPool, PoolOpts, PromotionExecutor, PromotionRequest,
29};
30
31#[cfg(test)]
36thread_local! {
37 static PUT_PREPARED_HOOK: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
38 pub(super) static EFFECTIVE_EXPIRY_COMPUTE_CALLS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
39}
40
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub enum CacheError {
43 BlobTooLarge {
44 size: usize,
45 max: usize,
46 },
47 MetadataTooLarge {
48 keys: usize,
49 bytes: usize,
50 max_keys: usize,
51 max_bytes: usize,
52 },
53 TooManyNamespaces {
54 max: usize,
55 },
56 VersionMismatch {
57 existing: u64,
58 attempted: u64,
59 },
60 L2Full {
61 size: u64,
62 max: u64,
63 },
64 L2Io(String),
65}
66
67#[derive(Debug, Clone, PartialEq, Eq, Hash)]
68pub(super) struct BlobCacheKey {
69 pub(super) namespace: String,
70 pub(super) key: String,
71}
72
73impl BlobCacheKey {
74 pub(super) fn new(namespace: impl Into<String>, key: impl Into<String>) -> Self {
75 Self {
76 namespace: namespace.into(),
77 key: key.into(),
78 }
79 }
80
81 pub(super) fn borrowed<'a>(namespace: &'a str, key: &'a str) -> BlobCacheKeyRef<'a> {
82 BlobCacheKeyRef { namespace, key }
83 }
84}
85
86pub(super) struct BlobCacheKeyRef<'a> {
87 pub(super) namespace: &'a str,
88 pub(super) key: &'a str,
89}
90
91impl Hash for BlobCacheKeyRef<'_> {
92 fn hash<H: Hasher>(&self, state: &mut H) {
93 self.namespace.hash(state);
94 self.key.hash(state);
95 }
96}
97
98impl Equivalent<BlobCacheKey> for BlobCacheKeyRef<'_> {
99 fn equivalent(&self, key: &BlobCacheKey) -> bool {
100 self.namespace == key.namespace && self.key == key.key
101 }
102}
103
104#[derive(Debug, Clone, PartialEq, Eq, Hash)]
105struct ScopedLabel {
106 namespace: String,
107 label: String,
108}
109
110impl ScopedLabel {
111 fn new(namespace: impl Into<String>, label: impl Into<String>) -> Self {
112 Self {
113 namespace: namespace.into(),
114 label: label.into(),
115 }
116 }
117}
118
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub struct BlobCacheHit {
121 pub(super) bytes: Arc<[u8]>,
122 pub(super) content_metadata: Option<Arc<BTreeMap<String, String>>>,
123 pub(super) version: Option<u64>,
124 pub(super) expires_at_unix_ms: Option<u64>,
125 pub(super) stale_window_remaining_ms: Option<u64>,
129}
130
131impl BlobCacheHit {
132 pub(crate) fn new(
133 bytes: Arc<[u8]>,
134 content_metadata: Option<Arc<BTreeMap<String, String>>>,
135 version: Option<u64>,
136 expires_at_unix_ms: Option<u64>,
137 ) -> Self {
138 Self {
139 bytes,
140 content_metadata,
141 version,
142 expires_at_unix_ms,
143 stale_window_remaining_ms: None,
144 }
145 }
146
147 pub(crate) fn new_stale(
148 bytes: Arc<[u8]>,
149 content_metadata: Option<Arc<BTreeMap<String, String>>>,
150 version: Option<u64>,
151 expires_at_unix_ms: Option<u64>,
152 window_remaining_ms: u64,
153 ) -> Self {
154 Self {
155 bytes,
156 content_metadata,
157 version,
158 expires_at_unix_ms,
159 stale_window_remaining_ms: Some(window_remaining_ms),
160 }
161 }
162
163 pub fn bytes(&self) -> &Arc<[u8]> {
165 &self.bytes
166 }
167
168 pub fn value(&self) -> &[u8] {
170 &self.bytes
171 }
172
173 pub fn content_metadata(&self) -> &BTreeMap<String, String> {
175 static EMPTY: BTreeMap<String, String> = BTreeMap::new();
176 self.content_metadata.as_deref().unwrap_or(&EMPTY)
177 }
178
179 pub fn version(&self) -> Option<u64> {
181 self.version
182 }
183
184 pub fn expires_at_unix_ms(&self) -> Option<u64> {
186 self.expires_at_unix_ms
187 }
188
189 pub fn remaining_ttl_ms_at(&self, now_ms: u64) -> Option<u64> {
191 self.expires_at_unix_ms
192 .map(|expires_at| expires_at.saturating_sub(now_ms))
193 }
194
195 pub fn is_stale(&self) -> bool {
199 self.stale_window_remaining_ms.is_some()
200 }
201
202 pub fn stale_window_remaining_ms(&self) -> Option<u64> {
205 self.stale_window_remaining_ms
206 }
207}
208
209#[derive(Debug, Clone, Default, PartialEq, Eq)]
210pub struct BlobCachePut {
211 pub bytes: Vec<u8>,
212 pub content_metadata: BTreeMap<String, String>,
213 pub tags: BTreeSet<String>,
214 pub dependencies: BTreeSet<String>,
215 pub policy: BlobCachePolicy,
216}
217
218impl BlobCachePut {
219 pub fn new(bytes: impl Into<Vec<u8>>) -> Self {
220 Self {
221 bytes: bytes.into(),
222 content_metadata: BTreeMap::new(),
223 tags: BTreeSet::new(),
224 dependencies: BTreeSet::new(),
225 policy: BlobCachePolicy::default(),
226 }
227 }
228
229 pub fn with_content_metadata(mut self, content_metadata: BTreeMap<String, String>) -> Self {
230 self.content_metadata = content_metadata;
231 self
232 }
233
234 pub fn with_tags(mut self, tags: impl IntoIterator<Item = impl Into<String>>) -> Self {
235 self.tags = tags.into_iter().map(Into::into).collect();
236 self
237 }
238
239 pub fn with_dependencies(
240 mut self,
241 dependencies: impl IntoIterator<Item = impl Into<String>>,
242 ) -> Self {
243 self.dependencies = dependencies.into_iter().map(Into::into).collect();
244 self
245 }
246
247 pub fn with_policy(mut self, policy: BlobCachePolicy) -> Self {
248 self.policy = policy;
249 self
250 }
251}
252
253#[derive(Debug, Clone, Copy, PartialEq, Eq)]
254pub enum L1Admission {
255 Always,
256 Auto,
257 Never,
258}
259
260#[derive(Debug, Clone, Copy, PartialEq, Eq)]
268pub enum CachePresence {
269 Present,
271 Absent,
273 MaybePresent,
276}
277
278impl From<bool> for CachePresence {
279 fn from(present: bool) -> Self {
280 if present {
281 CachePresence::Present
282 } else {
283 CachePresence::Absent
284 }
285 }
286}
287
288#[derive(Debug, Clone, Copy, PartialEq, Eq)]
289pub struct BlobCachePolicy {
290 ttl_ms: Option<u64>,
291 expires_at_unix_ms: Option<u64>,
292 max_blob_bytes: Option<usize>,
293 l1_admission: L1Admission,
294 priority: u8,
295 version: Option<u64>,
296 extended: ExtendedTtlPolicy,
302}
303
304impl Default for BlobCachePolicy {
305 fn default() -> Self {
306 Self {
307 ttl_ms: None,
308 expires_at_unix_ms: None,
309 max_blob_bytes: None,
310 l1_admission: L1Admission::Auto,
311 priority: 128,
312 version: None,
313 extended: ExtendedTtlPolicy::off(),
314 }
315 }
316}
317
318impl BlobCachePolicy {
319 pub fn ttl_ms(mut self, ttl_ms: u64) -> Self {
322 self.ttl_ms = Some(ttl_ms);
323 self
324 }
325
326 pub fn expires_at_unix_ms(mut self, expires_at_unix_ms: u64) -> Self {
327 self.expires_at_unix_ms = Some(expires_at_unix_ms);
328 self
329 }
330
331 pub fn max_blob_bytes(mut self, max_blob_bytes: usize) -> Self {
332 self.max_blob_bytes = Some(max_blob_bytes);
333 self
334 }
335
336 pub fn l1_admission(mut self, l1_admission: L1Admission) -> Self {
337 self.l1_admission = l1_admission;
338 self
339 }
340
341 pub fn priority(mut self, priority: u8) -> Self {
342 self.priority = priority;
343 self
344 }
345
346 pub fn version(mut self, version: u64) -> Self {
347 self.version = Some(version);
348 self
349 }
350
351 pub fn extended(mut self, extended: ExtendedTtlPolicy) -> Self {
356 self.extended = extended;
357 self
358 }
359
360 pub fn ttl_ms_value(&self) -> Option<u64> {
367 self.ttl_ms
368 }
369
370 pub fn expires_at_unix_ms_value(&self) -> Option<u64> {
371 self.expires_at_unix_ms
372 }
373
374 pub fn max_blob_bytes_value(&self) -> Option<usize> {
375 self.max_blob_bytes
376 }
377
378 pub fn l1_admission_value(&self) -> L1Admission {
379 self.l1_admission
380 }
381
382 pub fn priority_value(&self) -> u8 {
383 self.priority
384 }
385
386 pub fn version_value(&self) -> Option<u64> {
387 self.version
388 }
389
390 pub fn extended_value(&self) -> ExtendedTtlPolicy {
394 self.extended
395 }
396}
397
398#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
399pub struct BlobCacheStats {
400 pub(super) hits: u64,
401 pub(super) misses: u64,
402 pub(super) insertions: u64,
403 pub(super) evictions: u64,
404 pub(super) expirations: u64,
405 pub(super) invalidations: u64,
406 pub(super) namespace_flushes: u64,
407 pub(super) version_mismatches: u64,
408 pub(super) entries: usize,
409 pub(super) bytes_in_use: usize,
410 pub(super) l1_bytes_max: usize,
411 pub(super) namespace_bytes_max: usize,
412 pub(super) l2_bytes_in_use: u64,
413 pub(super) l2_bytes_max: u64,
414 pub(super) l2_full_rejections: u64,
415 pub(super) l2_metadata_reads: u64,
416 pub(super) l2_negative_skips: u64,
417 pub(super) synopsis_metadata_reads: u64,
421 pub(super) synopsis_bytes: u64,
423 pub(super) namespaces: usize,
424 pub(super) max_namespaces: usize,
425 pub(super) promotion_queued: u64,
428 pub(super) promotion_dropped: u64,
429 pub(super) promotion_completed: u64,
430 pub(super) promotion_queue_depth: usize,
431 pub(super) l2_compression_original_bytes: u64,
435 pub(super) l2_compression_stored_bytes: u64,
438 pub(super) l2_compression_skipped_total: u64,
440 pub(super) l2_bytes_saved_total: u64,
442 pub(super) l1_stale_serves_total: u64,
445 pub(super) l1_idle_evicts_total: u64,
448}
449
450impl BlobCacheStats {
451 pub fn hits(&self) -> u64 {
454 self.hits
455 }
456
457 pub fn misses(&self) -> u64 {
459 self.misses
460 }
461
462 pub fn insertions(&self) -> u64 {
463 self.insertions
464 }
465
466 pub fn evictions(&self) -> u64 {
467 self.evictions
468 }
469
470 pub fn expirations(&self) -> u64 {
471 self.expirations
472 }
473
474 pub fn invalidations(&self) -> u64 {
475 self.invalidations
476 }
477
478 pub fn namespace_flushes(&self) -> u64 {
479 self.namespace_flushes
480 }
481
482 pub fn version_mismatches(&self) -> u64 {
483 self.version_mismatches
484 }
485
486 pub fn entries(&self) -> usize {
487 self.entries
488 }
489
490 pub fn bytes_in_use(&self) -> u64 {
493 self.bytes_in_use as u64
494 }
495
496 pub fn l1_bytes_max(&self) -> usize {
497 self.l1_bytes_max
498 }
499
500 pub fn namespace_bytes_max(&self) -> usize {
501 self.namespace_bytes_max
502 }
503
504 pub fn l2_bytes_in_use(&self) -> u64 {
505 self.l2_bytes_in_use
506 }
507
508 pub fn l2_bytes_max(&self) -> u64 {
509 self.l2_bytes_max
510 }
511
512 pub fn l2_full_rejections(&self) -> u64 {
513 self.l2_full_rejections
514 }
515
516 pub fn l2_metadata_reads(&self) -> u64 {
517 self.l2_metadata_reads
518 }
519
520 pub fn l2_negative_skips(&self) -> u64 {
521 self.l2_negative_skips
522 }
523
524 pub fn synopsis_metadata_reads(&self) -> u64 {
530 self.synopsis_metadata_reads
531 }
532
533 pub fn synopsis_bytes(&self) -> u64 {
535 self.synopsis_bytes
536 }
537
538 pub fn namespaces(&self) -> usize {
539 self.namespaces
540 }
541
542 pub fn max_namespaces(&self) -> usize {
543 self.max_namespaces
544 }
545
546 pub fn promotion_queued(&self) -> u64 {
549 self.promotion_queued
550 }
551
552 pub fn promotion_dropped(&self) -> u64 {
555 self.promotion_dropped
556 }
557
558 pub fn promotion_completed(&self) -> u64 {
561 self.promotion_completed
562 }
563
564 pub fn promotion_queue_depth(&self) -> usize {
567 self.promotion_queue_depth
568 }
569
570 pub fn l2_compression_ratio_observed(&self) -> f64 {
577 if self.l2_compression_stored_bytes == 0 {
578 return 1.0;
579 }
580 self.l2_compression_original_bytes as f64 / self.l2_compression_stored_bytes as f64
581 }
582
583 pub fn l2_compression_skipped_total(&self) -> u64 {
587 self.l2_compression_skipped_total
588 }
589
590 pub fn l2_bytes_saved_total(&self) -> u64 {
594 self.l2_bytes_saved_total
595 }
596
597 pub fn l1_stale_serves_total(&self) -> u64 {
601 self.l1_stale_serves_total
602 }
603
604 pub fn l1_idle_evicts_total(&self) -> u64 {
608 self.l1_idle_evicts_total
609 }
610}
611
612#[derive(Clone, Copy)]
613enum IndexedKind {
614 Tag,
615 Dependency,
616}
617
618#[derive(Debug)]
619struct AtomicStats {
620 hits: AtomicU64,
621 misses: AtomicU64,
622 insertions: AtomicU64,
623 evictions: AtomicU64,
624 expirations: AtomicU64,
625 invalidations: AtomicU64,
626 namespace_flushes: AtomicU64,
627 version_mismatches: AtomicU64,
628 l2_full_rejections: AtomicU64,
629 l1_stale_serves: AtomicU64,
633 l1_idle_evicts: AtomicU64,
637}
638
639impl AtomicStats {
640 fn new() -> Self {
641 Self {
642 hits: AtomicU64::new(0),
643 misses: AtomicU64::new(0),
644 insertions: AtomicU64::new(0),
645 evictions: AtomicU64::new(0),
646 expirations: AtomicU64::new(0),
647 invalidations: AtomicU64::new(0),
648 namespace_flushes: AtomicU64::new(0),
649 version_mismatches: AtomicU64::new(0),
650 l2_full_rejections: AtomicU64::new(0),
651 l1_stale_serves: AtomicU64::new(0),
652 l1_idle_evicts: AtomicU64::new(0),
653 }
654 }
655}
656
657pub struct BlobCache {
676 config: BlobCacheConfig,
677 shards: Vec<RwLock<Shard>>,
678 namespaces: RwLock<HashSet<String>>,
679 namespace_generations: RwLock<HashMap<String, u64>>,
680 pending_namespace_fences: RwLock<HashSet<String>>,
681 tag_index: RwLock<HashMap<ScopedLabel, HashSet<BlobCacheKey>>>,
682 dependency_index: RwLock<HashMap<ScopedLabel, HashSet<BlobCacheKey>>>,
683 l2: Option<Arc<dyn BlobCacheL2Backend>>,
684 bytes_in_use: AtomicUsize,
685 namespace_bytes_in_use: RwLock<HashMap<String, usize>>,
686 sweep_shard_cursor: AtomicUsize,
687 namespace_flush_epoch: AtomicU64,
688 namespace_reclaimed_epoch: AtomicU64,
689 stats: AtomicStats,
690 promotion_pool: OnceLock<Arc<AsyncPromotionPool>>,
695}
696
697const _: fn() = || {
702 fn assert_send_sync<T: Send + Sync>() {}
703 assert_send_sync::<BlobCache>();
704};
705
706impl BlobCache {
707 pub fn new(config: BlobCacheConfig) -> Self {
711 Self::try_new(config).expect("open blob-cache L2")
712 }
713
714 pub fn open_with_l2(config: BlobCacheConfig) -> Result<Self, CacheError> {
718 Self::try_new(config)
719 }
720
721 pub fn open_with_internal_l2(
724 config: BlobCacheConfig,
725 store: Arc<crate::storage::UnifiedStore>,
726 ) -> Result<Self, CacheError> {
727 let l2 = (config.l2_bytes_max > 0)
728 .then(|| StoreBlobCacheL2::open(store, config.l2_bytes_max))
729 .transpose()?
730 .map(|backend| Arc::new(backend) as Arc<dyn BlobCacheL2Backend>);
731 Self::with_backend(config, l2)
732 }
733
734 fn try_new(config: BlobCacheConfig) -> Result<Self, CacheError> {
735 let l2 = config
736 .l2_path
737 .clone()
738 .map(|path| BlobCacheL2::open(path, config.l2_bytes_max))
739 .transpose()?
740 .map(|backend| Arc::new(backend) as Arc<dyn BlobCacheL2Backend>);
741 Self::with_backend(config, l2)
742 }
743
744 fn with_backend(
745 config: BlobCacheConfig,
746 l2: Option<Arc<dyn BlobCacheL2Backend>>,
747 ) -> Result<Self, CacheError> {
748 let config = BlobCacheConfig {
749 shard_count: config.shard_count.max(1),
750 ..config
751 };
752 let shards = (0..config.shard_count)
753 .map(|_| RwLock::new(Shard::new()))
754 .collect();
755 Ok(Self {
756 config,
757 shards,
758 namespaces: RwLock::new(HashSet::new()),
759 namespace_generations: RwLock::new(HashMap::new()),
760 pending_namespace_fences: RwLock::new(HashSet::new()),
761 tag_index: RwLock::new(HashMap::new()),
762 dependency_index: RwLock::new(HashMap::new()),
763 l2,
764 bytes_in_use: AtomicUsize::new(0),
765 namespace_bytes_in_use: RwLock::new(HashMap::new()),
766 sweep_shard_cursor: AtomicUsize::new(0),
767 namespace_flush_epoch: AtomicU64::new(0),
768 namespace_reclaimed_epoch: AtomicU64::new(0),
769 stats: AtomicStats::new(),
770 promotion_pool: OnceLock::new(),
771 })
772 }
773
774 pub fn with_defaults() -> Self {
775 Self::new(BlobCacheConfig::default())
776 }
777
778 pub fn l2_path(&self) -> Option<&std::path::Path> {
784 self.config.l2_path.as_deref()
785 }
786
787 pub fn put(
788 &self,
789 namespace: impl Into<String>,
790 key: impl Into<String>,
791 input: BlobCachePut,
792 ) -> Result<(), CacheError> {
793 self.put_at(namespace, key, input, unix_now_ms())
794 }
795
796 fn put_at(
797 &self,
798 namespace: impl Into<String>,
799 key: impl Into<String>,
800 input: BlobCachePut,
801 now_ms: u64,
802 ) -> Result<(), CacheError> {
803 let namespace = namespace.into();
804 let key = BlobCacheKey::new(namespace.clone(), key);
805 self.validate_blob_size(input.bytes.len(), input.policy)?;
806 self.validate_metadata(&input.content_metadata)?;
807 self.ensure_namespace(&namespace)?;
808 let namespace_generation = self.current_generation(&namespace);
809 let tags = input.tags.clone();
810 let dependencies = input.dependencies.clone();
811
812 let shard_idx = self.shard_index(&key);
813 if self.l2.is_some() {
814 self.check_version(
815 &self.shards[shard_idx].read(),
816 &key,
817 input.policy.version_value(),
818 namespace_generation,
819 )?;
820 }
821 let entry = Entry::new(
822 input.bytes,
823 input.content_metadata,
824 input.tags,
825 input.dependencies,
826 input.policy,
827 namespace_generation,
828 now_ms,
829 &namespace,
830 &key.key,
831 );
832 let entry_charge = entry.l1_charge_bytes;
833 let compressed = if self.l2.is_some() {
834 Some(match self.config.l2_compression {
841 L2Compression::Off => Compressed::Raw(entry.bytes.as_ref().to_vec()),
842 L2Compression::On => {
843 let content_type = entry
844 .content_metadata
845 .as_ref()
846 .and_then(|metadata| metadata.get("content-type"))
847 .map(String::as_str);
848 L2BlobCompressor::compress(
849 entry.bytes.as_ref(),
850 content_type,
851 &CompressOpts::default(),
852 )
853 .map_err(|err| CacheError::L2Io(err.to_string()))?
854 }
855 })
856 } else {
857 None
858 };
859 #[cfg(test)]
860 if let Some(hook) = PUT_PREPARED_HOOK.with(|slot| slot.borrow_mut().take()) {
861 hook();
862 }
863 let mut shard = self.shards[shard_idx].write();
864 self.check_version(
867 &shard,
868 &key,
869 input.policy.version_value(),
870 namespace_generation,
871 )?;
872 shard.clear_l2_hit_marker(&key);
873 if let Some(l2) = &self.l2 {
874 let old_l2_size = l2.record_size(&key);
875 let compressed = compressed.expect("L2 payload prepared before publication");
876 match l2.put(&key, &entry, old_l2_size, compressed) {
877 Ok(()) => {}
878 Err(err @ CacheError::L2Full { .. }) => {
879 self.stats
880 .l2_full_rejections
881 .fetch_add(1, Ordering::Relaxed);
882 return Err(err);
883 }
884 Err(err) => return Err(err),
885 }
886 }
887 let outcome = if matches!(input.policy.l1_admission_value(), L1Admission::Never) {
888 let old_entry = shard.remove(&key);
889 InsertOutcome {
890 old_entry,
891 admitted: false,
892 }
893 } else {
894 shard.insert(key.clone(), entry)
895 };
896 let old_charge = outcome
897 .old_entry
898 .as_ref()
899 .map_or(0, |entry| entry.l1_charge_bytes);
900 let new_charge = if outcome.admitted { entry_charge } else { 0 };
901 self.adjust_namespace_bytes(&namespace, old_charge, new_charge);
902 if new_charge >= old_charge {
903 self.bytes_in_use
904 .fetch_add(new_charge - old_charge, Ordering::Relaxed);
905 } else {
906 self.bytes_in_use
907 .fetch_sub(old_charge - new_charge, Ordering::Relaxed);
908 }
909 if let Some(old_entry) = outcome.old_entry.as_ref() {
910 self.deindex_entry(&key, old_entry);
911 }
912 if outcome.admitted {
913 self.index_entry(&key, &tags, &dependencies);
914 }
915 drop(shard);
916
917 self.stats.insertions.fetch_add(1, Ordering::Relaxed);
918 if outcome.admitted {
919 self.evict_namespace_until_within_budget(&namespace, shard_idx);
920 self.evict_until_within_budget(shard_idx);
921 }
922 Ok(())
923 }
924
925 pub fn get(&self, namespace: &str, key: &str) -> Option<BlobCacheHit> {
926 self.get_at(namespace, key, unix_now_ms())
927 }
928
929 fn get_at(&self, namespace: &str, key: &str, now_ms: u64) -> Option<BlobCacheHit> {
930 let namespace_generation = self.current_generation(namespace);
931 let shard_idx = self.shard_index_parts(namespace, key);
932 if let Some(hit) =
933 self.shards[shard_idx]
934 .read()
935 .shared_hit(namespace, key, now_ms, namespace_generation)
936 {
937 self.stats.hits.fetch_add(1, Ordering::Relaxed);
938 return Some(hit);
939 }
940 let mut shard = self.shards[shard_idx].write();
941 match shard.get_by_parts(namespace, key, now_ms, namespace_generation) {
942 Lookup::Hit(hit) => {
943 self.stats.hits.fetch_add(1, Ordering::Relaxed);
944 if hit.is_stale() {
945 self.stats.l1_stale_serves.fetch_add(1, Ordering::Relaxed);
946 }
947 Some(hit)
948 }
949 Lookup::Expired(entry) => {
950 let cache_key = BlobCacheKey::new(namespace, key);
951 self.record_removed_entry(&cache_key, &entry);
952 if let Some(l2) = &self.l2 {
953 l2.delete_key(&cache_key);
954 }
955 drop(shard);
956 self.stats.expirations.fetch_add(1, Ordering::Relaxed);
957 self.stats.misses.fetch_add(1, Ordering::Relaxed);
958 None
959 }
960 Lookup::IdleEvicted(entry) => {
961 let cache_key = BlobCacheKey::new(namespace, key);
962 self.record_removed_entry(&cache_key, &entry);
963 if let Some(l2) = &self.l2 {
964 l2.delete_key(&cache_key);
965 }
966 drop(shard);
967 self.stats.expirations.fetch_add(1, Ordering::Relaxed);
968 self.stats.l1_idle_evicts.fetch_add(1, Ordering::Relaxed);
969 self.stats.misses.fetch_add(1, Ordering::Relaxed);
970 None
971 }
972 Lookup::Stale(entry) => {
973 let cache_key = BlobCacheKey::new(namespace, key);
974 self.record_removed_entry(&cache_key, &entry);
975 drop(shard);
976 self.stats.misses.fetch_add(1, Ordering::Relaxed);
977 None
978 }
979 Lookup::Miss => {
980 drop(shard);
981 let cache_key = BlobCacheKey::new(namespace, key);
982 if let Some(pool) = self.promotion_pool.get() {
983 if let Some(l2) = self.l2.as_ref() {
987 if let Some(entry) = l2.get(&cache_key, now_ms, namespace_generation) {
988 let hit = entry.hit();
989 if self.should_promote_l2_hit(&cache_key, shard_idx) {
990 drop(entry);
995 let request = PromotionRequest {
996 namespace: cache_key.namespace.clone(),
997 key: cache_key.key.clone(),
998 bytes: Arc::clone(hit.bytes()),
999 policy: BlobCachePolicy::default(),
1000 };
1001 let _ = pool.schedule(request);
1002 }
1003 self.stats.hits.fetch_add(1, Ordering::Relaxed);
1004 return Some(hit);
1005 }
1006 }
1007 self.stats.misses.fetch_add(1, Ordering::Relaxed);
1008 return None;
1009 }
1010 if let Some(hit) =
1011 self.rehydrate_l2_entry(&cache_key, now_ms, namespace_generation, shard_idx)
1012 {
1013 self.stats.hits.fetch_add(1, Ordering::Relaxed);
1014 return Some(hit);
1015 }
1016 self.stats.misses.fetch_add(1, Ordering::Relaxed);
1017 None
1018 }
1019 Lookup::Present => unreachable!("get cannot return presence-only lookup"),
1020 }
1021 }
1022
1023 pub fn exists(&self, namespace: &str, key: &str) -> CachePresence {
1041 self.exists_at(namespace, key, unix_now_ms())
1042 }
1043
1044 pub fn expire(&self, namespace: &str, key: &str, ttl_ms: u64) -> Result<bool, CacheError> {
1046 let now_ms = unix_now_ms();
1047 self.update_expiry(namespace, key, Some(now_ms.saturating_add(ttl_ms)), now_ms)
1048 }
1049
1050 pub fn expire_at(
1052 &self,
1053 namespace: &str,
1054 key: &str,
1055 expires_at_unix_ms: u64,
1056 ) -> Result<bool, CacheError> {
1057 self.update_expiry(namespace, key, Some(expires_at_unix_ms), unix_now_ms())
1058 }
1059
1060 pub fn persist(&self, namespace: &str, key: &str) -> Result<bool, CacheError> {
1062 self.update_expiry(namespace, key, None, unix_now_ms())
1063 }
1064
1065 fn update_expiry(
1066 &self,
1067 namespace: &str,
1068 key: &str,
1069 expires_at_unix_ms: Option<u64>,
1070 now_ms: u64,
1071 ) -> Result<bool, CacheError> {
1072 if !self.namespace_exists(namespace) {
1073 return Ok(false);
1074 }
1075 let cache_key = BlobCacheKey::new(namespace, key);
1076 let namespace_generation = self.current_generation(namespace);
1077 let shard_index = self.shard_index(&cache_key);
1078 let mut shard = self.shards[shard_index].write();
1079 let l1_live = shard.can_update_expiry(&cache_key, now_ms, namespace_generation);
1080 let l2_updated = match &self.l2 {
1081 Some(l2) => {
1082 l2.update_expiry(&cache_key, namespace_generation, now_ms, expires_at_unix_ms)?
1083 }
1084 None => false,
1085 };
1086 if l1_live {
1087 shard.update_expiry(&cache_key, expires_at_unix_ms, now_ms);
1088 }
1089 Ok(l1_live || l2_updated)
1090 }
1091
1092 fn exists_at(&self, namespace: &str, key: &str, now_ms: u64) -> CachePresence {
1093 let namespace_generation = self.current_generation(namespace);
1094 let shard_idx = self.shard_index_parts(namespace, key);
1095 let mut shard = self.shards[shard_idx].write();
1096 match shard.contains_by_parts(namespace, key, now_ms, namespace_generation) {
1097 Lookup::Present => {
1098 self.stats.hits.fetch_add(1, Ordering::Relaxed);
1099 CachePresence::Present
1100 }
1101 Lookup::Expired(entry) => {
1102 let cache_key = BlobCacheKey::new(namespace, key);
1103 self.record_removed_entry(&cache_key, &entry);
1104 if let Some(l2) = &self.l2 {
1105 l2.delete_key(&cache_key);
1106 }
1107 drop(shard);
1108 self.stats.expirations.fetch_add(1, Ordering::Relaxed);
1109 self.stats.misses.fetch_add(1, Ordering::Relaxed);
1110 CachePresence::Absent
1111 }
1112 Lookup::IdleEvicted(entry) => {
1113 let cache_key = BlobCacheKey::new(namespace, key);
1114 self.record_removed_entry(&cache_key, &entry);
1115 if let Some(l2) = &self.l2 {
1116 l2.delete_key(&cache_key);
1117 }
1118 drop(shard);
1119 self.stats.expirations.fetch_add(1, Ordering::Relaxed);
1120 self.stats.l1_idle_evicts.fetch_add(1, Ordering::Relaxed);
1121 self.stats.misses.fetch_add(1, Ordering::Relaxed);
1122 CachePresence::Absent
1123 }
1124 Lookup::Stale(entry) => {
1125 let cache_key = BlobCacheKey::new(namespace, key);
1126 self.record_removed_entry(&cache_key, &entry);
1127 drop(shard);
1128 self.stats.misses.fetch_add(1, Ordering::Relaxed);
1129 CachePresence::Absent
1130 }
1131 Lookup::Miss => {
1132 drop(shard);
1133 let Some(l2) = self.l2.as_ref() else {
1134 self.stats.misses.fetch_add(1, Ordering::Relaxed);
1135 return CachePresence::Absent;
1136 };
1137 if l2.synopsis_may_contain(namespace, key) {
1138 self.stats.hits.fetch_add(1, Ordering::Relaxed);
1141 CachePresence::MaybePresent
1142 } else {
1143 self.stats.misses.fetch_add(1, Ordering::Relaxed);
1146 CachePresence::Absent
1147 }
1148 }
1149 Lookup::Hit(_) => unreachable!("exists cannot return a hit payload"),
1150 }
1151 }
1152
1153 pub fn invalidate_key(&self, namespace: &str, key: &str) -> usize {
1159 if !self.namespace_exists(namespace) {
1160 return 0;
1161 }
1162 let cache_key = BlobCacheKey::new(namespace, key);
1163 let shard_idx = self.shard_index(&cache_key);
1164 let mut shard = self.shards[shard_idx].write();
1165 let removed = shard.remove(&cache_key);
1166
1167 if let Some(entry) = removed {
1168 self.record_invalidated_entry(&cache_key, &entry);
1169 drop(shard);
1170 1
1171 } else {
1172 drop(shard);
1173 self.l2
1174 .as_ref()
1175 .and_then(|l2| l2.delete_key(&cache_key))
1176 .map(|_| {
1177 self.stats.invalidations.fetch_add(1, Ordering::Relaxed);
1178 1
1179 })
1180 .unwrap_or(0)
1181 }
1182 }
1183
1184 pub fn invalidate_prefix(&self, namespace: &str, prefix: &str) -> usize {
1186 if !self.namespace_exists(namespace) {
1187 return 0;
1188 }
1189
1190 let mut count = 0usize;
1191 for shard in &self.shards {
1192 let mut shard = shard.write();
1193 let keys = shard
1194 .keys_matching(|key| key.namespace == namespace && key.key.starts_with(prefix));
1195 for key in keys {
1196 if let Some(entry) = shard.remove(&key) {
1197 self.record_invalidated_entry(&key, &entry);
1198 count += 1;
1199 }
1200 }
1201 }
1202
1203 let l2_count = self
1204 .l2
1205 .as_ref()
1206 .map_or(0, |l2| l2.delete_prefix(namespace, prefix));
1207 if l2_count > count {
1208 self.stats
1209 .invalidations
1210 .fetch_add((l2_count - count) as u64, Ordering::Relaxed);
1211 }
1212 count.max(l2_count)
1213 }
1214
1215 pub fn invalidate_tags(&self, namespace: &str, tags: &[&str]) -> usize {
1221 self.invalidate_indexed_many(namespace, tags, IndexedKind::Tag)
1222 }
1223
1224 pub fn invalidate_dependencies(&self, namespace: &str, dependencies: &[&str]) -> usize {
1226 self.invalidate_indexed_many(namespace, dependencies, IndexedKind::Dependency)
1227 }
1228
1229 #[deprecated(
1231 since = "0.1.0",
1232 note = "use `invalidate_tags(namespace, &[tag])` for batched callers"
1233 )]
1234 pub fn invalidate_tag(&self, namespace: &str, tag: &str) -> usize {
1235 self.invalidate_indexed_many(namespace, &[tag], IndexedKind::Tag)
1236 }
1237
1238 #[deprecated(
1240 since = "0.1.0",
1241 note = "use `invalidate_dependencies(namespace, &[dependency])` for batched callers"
1242 )]
1243 pub fn invalidate_dependency(&self, namespace: &str, dependency: &str) -> usize {
1244 self.invalidate_indexed_many(namespace, &[dependency], IndexedKind::Dependency)
1245 }
1246
1247 pub fn invalidate_namespace(&self, namespace: &str) -> bool {
1250 match self.try_invalidate_namespace(namespace) {
1251 Ok(flushed) => flushed,
1252 Err(error) => {
1253 tracing::error!(
1254 namespace,
1255 ?error,
1256 "failed to persist cache namespace generation"
1257 );
1258 false
1259 }
1260 }
1261 }
1262
1263 pub(crate) fn invalidate_namespace_in_memory(&self, namespace: &str) {
1266 if !self.namespace_exists(namespace) {
1267 return;
1268 }
1269 let current = self.current_generation(namespace);
1270 let mut generations = self.namespace_generations.write();
1271 let generation = generations.entry(namespace.to_string()).or_insert(current);
1272 *generation = generation.saturating_add(1);
1273 self.pending_namespace_fences
1274 .write()
1275 .insert(namespace.to_string());
1276 self.namespace_flush_epoch.fetch_add(1, Ordering::Release);
1277 }
1278
1279 pub(crate) fn try_invalidate_namespace(&self, namespace: &str) -> Result<bool, CacheError> {
1280 if !self.namespace_exists(namespace)
1281 && !self.pending_namespace_fences.read().contains(namespace)
1282 {
1283 return Ok(false);
1284 }
1285 let current = self.current_generation(namespace);
1286 let mut generations = self.namespace_generations.write();
1287 let generation = generations.entry(namespace.to_string()).or_insert(current);
1288 *generation = generation.saturating_add(1);
1289 self.namespace_flush_epoch.fetch_add(1, Ordering::Release);
1290 let persisted = if let Some(l2) = &self.l2 {
1291 l2.invalidate_namespace(namespace, *generation)
1292 } else {
1293 Ok(())
1294 };
1295 if persisted.is_ok() {
1296 self.pending_namespace_fences.write().remove(namespace);
1297 }
1298 self.stats.namespace_flushes.fetch_add(1, Ordering::Relaxed);
1299 persisted.map(|()| true)
1300 }
1301
1302 pub fn ram_bytes_in_use(&self) -> u64 {
1307 let l1 = self.bytes_in_use.load(Ordering::Relaxed) as u64;
1308 let l2 = self
1309 .l2
1310 .as_ref()
1311 .map_or(0, |l2| l2.resident_metadata_bytes());
1312 l1.saturating_add(l2)
1313 }
1314
1315 pub fn stats(&self) -> BlobCacheStats {
1316 BlobCacheStats {
1317 hits: self.stats.hits.load(Ordering::Relaxed),
1318 misses: self.stats.misses.load(Ordering::Relaxed),
1319 insertions: self.stats.insertions.load(Ordering::Relaxed),
1320 evictions: self.stats.evictions.load(Ordering::Relaxed),
1321 expirations: self.stats.expirations.load(Ordering::Relaxed),
1322 invalidations: self.stats.invalidations.load(Ordering::Relaxed),
1323 namespace_flushes: self.stats.namespace_flushes.load(Ordering::Relaxed),
1324 version_mismatches: self.stats.version_mismatches.load(Ordering::Relaxed),
1325 entries: self.shards.iter().map(|shard| shard.read().len()).sum(),
1326 bytes_in_use: self.bytes_in_use.load(Ordering::Relaxed),
1327 l1_bytes_max: self.config.l1_bytes_max,
1328 namespace_bytes_max: self.config.namespace_bytes_max,
1329 l2_bytes_in_use: self.l2.as_ref().map_or(0, |l2| l2.stats_bytes_in_use()),
1330 l2_bytes_max: self.config.l2_bytes_max,
1331 l2_full_rejections: self.stats.l2_full_rejections.load(Ordering::Relaxed),
1332 l2_metadata_reads: self.l2.as_ref().map_or(0, |l2| l2.stats_metadata_reads()),
1333 l2_negative_skips: self.l2.as_ref().map_or(0, |l2| l2.stats_negative_skips()),
1334 synopsis_metadata_reads: self
1335 .l2
1336 .as_ref()
1337 .map_or(0, |l2| l2.stats_synopsis_metadata_reads()),
1338 synopsis_bytes: self.l2.as_ref().map_or(0, |l2| l2.stats_synopsis_bytes()),
1339 namespaces: self.namespaces.read().len(),
1340 max_namespaces: self.config.max_namespaces,
1341 promotion_queued: self
1342 .promotion_pool
1343 .get()
1344 .map_or(0, |p| p.metrics().queued_total),
1345 promotion_dropped: self
1346 .promotion_pool
1347 .get()
1348 .map_or(0, |p| p.metrics().dropped_total),
1349 promotion_completed: self
1350 .promotion_pool
1351 .get()
1352 .map_or(0, |p| p.metrics().completed_total),
1353 promotion_queue_depth: self
1354 .promotion_pool
1355 .get()
1356 .map_or(0, |p| p.metrics().queue_depth),
1357 l2_compression_original_bytes: self
1358 .l2
1359 .as_ref()
1360 .map_or(0, |l2| l2.stats_compression_original_bytes()),
1361 l2_compression_stored_bytes: self
1362 .l2
1363 .as_ref()
1364 .map_or(0, |l2| l2.stats_compression_stored_bytes()),
1365 l2_compression_skipped_total: self
1366 .l2
1367 .as_ref()
1368 .map_or(0, |l2| l2.stats_compression_skipped_total()),
1369 l2_bytes_saved_total: self
1370 .l2
1371 .as_ref()
1372 .map_or(0, |l2| l2.stats_bytes_saved_total()),
1373 l1_stale_serves_total: self.stats.l1_stale_serves.load(Ordering::Relaxed),
1374 l1_idle_evicts_total: self.stats.l1_idle_evicts.load(Ordering::Relaxed),
1375 }
1376 }
1377
1378 pub(crate) fn sweep_expired_l1(
1385 &self,
1386 entries_limit: Option<usize>,
1387 millis_limit: Option<u32>,
1388 ) -> BlobCacheSweepOutcome {
1389 let started = Instant::now();
1390 let time_limit = millis_limit.map(|millis| Duration::from_millis(u64::from(millis)));
1391 let now_ms = unix_now_ms();
1392 let hard_entries_limit = entries_limit.unwrap_or(usize::MAX);
1393 let shard_count = self.shards.len();
1394 let first_shard = self.sweep_shard_cursor.fetch_add(1, Ordering::Relaxed) % shard_count;
1395 let flush_epoch = self.namespace_flush_epoch.load(Ordering::Acquire);
1396 let stale_cleanup_pending =
1397 self.namespace_reclaimed_epoch.load(Ordering::Acquire) < flush_epoch;
1398 let mut outcome = BlobCacheSweepOutcome::default();
1399 let mut completed_all_shards = true;
1400
1401 for offset in 0..shard_count {
1402 if outcome.entries_scanned >= hard_entries_limit
1403 || time_limit.is_some_and(|limit| started.elapsed() >= limit)
1404 {
1405 completed_all_shards = false;
1406 break;
1407 }
1408 let shard_index = (first_shard + offset) % shard_count;
1409 let mut shard = self.shards[shard_index].write();
1410 let sweep = shard.sweep_expired(
1411 now_ms,
1412 hard_entries_limit - outcome.entries_scanned,
1413 started,
1414 time_limit,
1415 );
1416 completed_all_shards &= sweep.completed_cycle;
1421 self.record_sweep(sweep, &mut outcome);
1422
1423 if stale_cleanup_pending
1424 && outcome.entries_scanned < hard_entries_limit
1425 && !time_limit.is_some_and(|limit| started.elapsed() >= limit)
1426 {
1427 let namespace_generations = self.namespace_generations.read();
1430 let stale_sweep = shard.sweep_stale_generations(
1431 &namespace_generations,
1432 flush_epoch,
1433 hard_entries_limit - outcome.entries_scanned,
1434 started,
1435 time_limit,
1436 );
1437 completed_all_shards &= stale_sweep.completed_cycle;
1438 self.record_sweep(stale_sweep, &mut outcome);
1439 }
1440 drop(shard);
1441 }
1442
1443 if stale_cleanup_pending
1444 && self
1445 .shards
1446 .iter()
1447 .all(|shard| shard.read().stale_cleanup_completed(flush_epoch))
1448 {
1449 self.namespace_reclaimed_epoch
1450 .fetch_max(flush_epoch, Ordering::Release);
1451 }
1452
1453 if outcome.expirations > 0 {
1454 let expirations = u64::try_from(outcome.expirations).unwrap_or(u64::MAX);
1455 self.stats
1456 .expirations
1457 .fetch_add(expirations, Ordering::Relaxed);
1458 }
1459 outcome.completed = completed_all_shards;
1460 outcome.elapsed_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
1461 outcome
1462 }
1463
1464 pub(crate) fn sweep_expired_l2(
1468 &self,
1469 entries_limit: usize,
1470 millis_limit: Option<u32>,
1471 ) -> BlobCacheSweepOutcome {
1472 let Some(l2) = &self.l2 else {
1473 return BlobCacheSweepOutcome {
1474 completed: true,
1475 ..BlobCacheSweepOutcome::default()
1476 };
1477 };
1478 let outcome = l2.sweep_expired(unix_now_ms(), entries_limit, millis_limit);
1479 if outcome.expirations > 0 {
1480 self.stats.expirations.fetch_add(
1481 u64::try_from(outcome.expirations).unwrap_or(u64::MAX),
1482 Ordering::Relaxed,
1483 );
1484 }
1485 outcome
1486 }
1487
1488 fn record_sweep(&self, sweep: ShardSweep, outcome: &mut BlobCacheSweepOutcome) {
1489 for (key, entry, _) in &sweep.removed {
1490 self.record_removed_entry(key, entry);
1491 if let Some(l2) = &self.l2 {
1492 l2.delete_key(key);
1493 }
1494 }
1495 outcome.entries_scanned += sweep.entries_scanned;
1496 for (namespace, scanned) in sweep.scanned_by_namespace {
1497 outcome
1498 .by_namespace
1499 .entry(namespace)
1500 .or_default()
1501 .entries_scanned += scanned;
1502 }
1503 for (key, entry, expired) in sweep.removed {
1504 let entry_charge_bytes = u64::try_from(entry.l1_charge_bytes).unwrap_or(u64::MAX);
1505 let namespace_stats = outcome
1506 .by_namespace
1507 .entry(key.namespace.clone())
1508 .or_default();
1509 namespace_stats.entries_evicted += 1;
1510 namespace_stats.bytes_reclaimed = namespace_stats
1511 .bytes_reclaimed
1512 .saturating_add(entry_charge_bytes);
1513 outcome.entries_evicted += 1;
1514 outcome.expirations += usize::from(expired);
1515 outcome.bytes_reclaimed = outcome.bytes_reclaimed.saturating_add(entry_charge_bytes);
1516 }
1517 }
1518
1519 pub fn enable_async_promotion(self: &Arc<Self>, opts: PoolOpts) -> Arc<AsyncPromotionPool> {
1530 let weak: Weak<Self> = Arc::downgrade(self);
1531 let executor: PromotionExecutor = Arc::new(move |req| {
1532 let Some(cache) = weak.upgrade() else {
1536 return Ok(());
1537 };
1538 cache.promote_from_l2(&req)
1539 });
1540 let pool = AsyncPromotionPool::new_with_executor(opts, executor);
1541 match self.promotion_pool.set(Arc::clone(&pool)) {
1542 Ok(()) => pool,
1543 Err(losing_pool) => {
1547 losing_pool.shutdown();
1548 Arc::clone(
1549 self.promotion_pool
1550 .get()
1551 .expect("OnceLock set+get inconsistency"),
1552 )
1553 }
1554 }
1555 }
1556
1557 pub fn shutdown_async_promotion(&self) {
1561 if let Some(pool) = self.promotion_pool.get() {
1562 Arc::clone(pool).shutdown();
1563 }
1564 }
1565
1566 #[cfg(test)]
1569 fn promotion_pool_handle(&self) -> Option<Arc<AsyncPromotionPool>> {
1570 self.promotion_pool.get().cloned()
1571 }
1572
1573 #[cfg(test)]
1577 fn enable_async_promotion_with_executor(
1578 self: &Arc<Self>,
1579 opts: PoolOpts,
1580 executor: PromotionExecutor,
1581 ) -> Arc<AsyncPromotionPool> {
1582 let pool = AsyncPromotionPool::new_with_executor(opts, executor);
1583 let _ = self.promotion_pool.set(Arc::clone(&pool));
1584 pool
1585 }
1586
1587 pub fn config(&self) -> &BlobCacheConfig {
1588 &self.config
1589 }
1590
1591 #[cfg(test)]
1592 fn inject_l2_fault_after_blob_write_once(&self) {
1593 self.l2
1594 .as_ref()
1595 .expect("L2 enabled")
1596 .inject_fault_after_blob_write_once();
1597 }
1598
1599 #[cfg(test)]
1600 fn inject_l2_synopsis_maybe_present(&self, namespace: &str, key: &str) {
1601 self.l2
1602 .as_ref()
1603 .expect("L2 enabled")
1604 .inject_synopsis_maybe_present(namespace, key);
1605 }
1606
1607 #[cfg(test)]
1611 fn inject_l2_v1_entry(
1612 &self,
1613 namespace: &str,
1614 key: &str,
1615 payload: &[u8],
1616 ) -> Result<(), CacheError> {
1617 let l2 = self.l2.as_ref().expect("L2 enabled");
1618 let cache_key = BlobCacheKey::new(namespace, key);
1619 l2.inject_v1_entry(&cache_key, payload)
1620 }
1621
1622 fn validate_blob_size(&self, size: usize, policy: BlobCachePolicy) -> Result<(), CacheError> {
1623 let max = policy
1624 .max_blob_bytes_value()
1625 .unwrap_or(self.config.l1_bytes_max);
1626 if size > max {
1627 Err(CacheError::BlobTooLarge { size, max })
1628 } else {
1629 Ok(())
1630 }
1631 }
1632
1633 fn validate_metadata(&self, metadata: &BTreeMap<String, String>) -> Result<(), CacheError> {
1634 let keys = metadata.len();
1635 let bytes = metadata
1636 .iter()
1637 .map(|(key, value)| key.len() + value.len())
1638 .sum::<usize>();
1639 if keys > self.config.content_metadata_keys_max
1640 || bytes > self.config.content_metadata_bytes_max
1641 {
1642 Err(CacheError::MetadataTooLarge {
1643 keys,
1644 bytes,
1645 max_keys: self.config.content_metadata_keys_max,
1646 max_bytes: self.config.content_metadata_bytes_max,
1647 })
1648 } else {
1649 Ok(())
1650 }
1651 }
1652
1653 fn rehydrate_l2_entry(
1654 &self,
1655 key: &BlobCacheKey,
1656 now_ms: u64,
1657 namespace_generation: u64,
1658 shard_idx: usize,
1659 ) -> Option<BlobCacheHit> {
1660 let l2 = self.l2.as_ref()?;
1661 let entry = l2.get(key, now_ms, namespace_generation)?;
1662 let hit = entry.hit();
1663 if self.should_promote_l2_hit(key, shard_idx) {
1664 self.do_l1_promotion_sync(key, entry, shard_idx);
1665 }
1666 Some(hit)
1667 }
1668
1669 fn should_promote_l2_hit(&self, key: &BlobCacheKey, shard_idx: usize) -> bool {
1670 match self.config.l2_promotion_policy {
1671 L2PromotionPolicy::Immediate => true,
1672 L2PromotionPolicy::OnSecondHit => self.shards[shard_idx]
1673 .write()
1674 .l2_hit_should_promote_on_second_hit(key),
1675 }
1676 }
1677
1678 fn do_l1_promotion_sync(&self, key: &BlobCacheKey, entry: Entry, shard_idx: usize) {
1686 let entry_charge = entry.l1_charge_bytes;
1687 let mut shard = self.shards[shard_idx].write();
1688 let outcome = shard.insert(key.clone(), entry);
1689 let old_charge = outcome
1690 .old_entry
1691 .as_ref()
1692 .map_or(0, |entry| entry.l1_charge_bytes);
1693 self.adjust_namespace_bytes(&key.namespace, old_charge, entry_charge);
1694 if entry_charge >= old_charge {
1695 self.bytes_in_use
1696 .fetch_add(entry_charge - old_charge, Ordering::Relaxed);
1697 } else {
1698 self.bytes_in_use
1699 .fetch_sub(old_charge - entry_charge, Ordering::Relaxed);
1700 }
1701 drop(shard);
1702 self.evict_namespace_until_within_budget(&key.namespace, shard_idx);
1703 self.evict_until_within_budget(shard_idx);
1704 }
1705
1706 fn promote_from_l2(&self, req: &PromotionRequest) -> Result<(), String> {
1712 let l2 = self
1713 .l2
1714 .as_ref()
1715 .ok_or_else(|| "promotion executor invoked without L2 configured".to_string())?;
1716 let cache_key = BlobCacheKey::new(req.namespace.as_str(), req.key.as_str());
1717 let now_ms = unix_now_ms();
1718 let namespace_generation = self.current_generation(req.namespace.as_str());
1719 if let Some(entry) = l2.get(&cache_key, now_ms, namespace_generation) {
1720 let shard_idx = self.shard_index(&cache_key);
1721 self.do_l1_promotion_sync(&cache_key, entry, shard_idx);
1722 }
1723 Ok(())
1724 }
1725
1726 fn ensure_namespace(&self, namespace: &str) -> Result<(), CacheError> {
1727 {
1728 let namespaces = self.namespaces.read();
1729 if namespaces.contains(namespace) {
1730 return Ok(());
1731 }
1732 }
1733 let generation = self.current_generation(namespace);
1734 let mut namespaces = self.namespaces.write();
1735 if namespaces.contains(namespace) {
1736 return Ok(());
1737 }
1738 if namespaces.len() >= self.config.max_namespaces {
1739 return Err(CacheError::TooManyNamespaces {
1740 max: self.config.max_namespaces,
1741 });
1742 }
1743 namespaces.insert(namespace.to_string());
1744 self.namespace_generations
1745 .write()
1746 .entry(namespace.to_string())
1747 .or_insert(generation);
1748 self.namespace_bytes_in_use
1749 .write()
1750 .entry(namespace.to_string())
1751 .or_insert(0);
1752 Ok(())
1753 }
1754
1755 fn namespace_exists(&self, namespace: &str) -> bool {
1756 self.namespaces.read().contains(namespace)
1757 || self
1758 .l2
1759 .as_ref()
1760 .is_some_and(|l2| l2.has_namespace(namespace))
1761 }
1762
1763 pub(crate) fn current_generation(&self, namespace: &str) -> u64 {
1764 if let Some(generation) = self.namespace_generations.read().get(namespace).copied() {
1765 return generation;
1766 }
1767 let Some(generation) = self
1768 .l2
1769 .as_ref()
1770 .and_then(|l2| l2.namespace_generation(namespace))
1771 else {
1772 return self
1773 .namespace_generations
1774 .read()
1775 .get(namespace)
1776 .copied()
1777 .unwrap_or(0);
1778 };
1779 let mut generations = self.namespace_generations.write();
1780 if let Some(current) = generations.get(namespace) {
1781 *current
1782 } else if generations.len() < self.config.max_namespaces {
1783 *generations
1784 .entry(namespace.to_string())
1785 .or_insert(generation)
1786 } else {
1787 generation
1788 }
1789 }
1790
1791 fn index_entry(
1792 &self,
1793 key: &BlobCacheKey,
1794 tags: &BTreeSet<String>,
1795 dependencies: &BTreeSet<String>,
1796 ) {
1797 if !tags.is_empty() {
1798 let mut index = self.tag_index.write();
1799 for tag in tags {
1800 index
1801 .entry(ScopedLabel::new(key.namespace.as_str(), tag.as_str()))
1802 .or_default()
1803 .insert(key.clone());
1804 }
1805 }
1806 if !dependencies.is_empty() {
1807 let mut index = self.dependency_index.write();
1808 for dependency in dependencies {
1809 index
1810 .entry(ScopedLabel::new(
1811 key.namespace.as_str(),
1812 dependency.as_str(),
1813 ))
1814 .or_default()
1815 .insert(key.clone());
1816 }
1817 }
1818 }
1819
1820 fn deindex_entry(&self, key: &BlobCacheKey, entry: &Entry) {
1821 Self::remove_indexed_labels(&self.tag_index, key, &entry.tags);
1822 Self::remove_indexed_labels(&self.dependency_index, key, &entry.dependencies);
1823 }
1824
1825 fn remove_indexed_labels(
1826 index: &RwLock<HashMap<ScopedLabel, HashSet<BlobCacheKey>>>,
1827 key: &BlobCacheKey,
1828 labels: &BTreeSet<String>,
1829 ) {
1830 if labels.is_empty() {
1831 return;
1832 }
1833 let mut index = index.write();
1834 for label in labels {
1835 let scoped = ScopedLabel::new(key.namespace.as_str(), label.as_str());
1836 let should_remove = if let Some(keys) = index.get_mut(&scoped) {
1837 keys.remove(key);
1838 keys.is_empty()
1839 } else {
1840 false
1841 };
1842 if should_remove {
1843 index.remove(&scoped);
1844 }
1845 }
1846 }
1847
1848 fn record_removed_entry(&self, key: &BlobCacheKey, entry: &Entry) {
1849 self.bytes_in_use
1850 .fetch_sub(entry.l1_charge_bytes, Ordering::Relaxed);
1851 self.adjust_namespace_bytes(&key.namespace, entry.l1_charge_bytes, 0);
1852 self.deindex_entry(key, entry);
1853 }
1854
1855 fn record_invalidated_entry(&self, key: &BlobCacheKey, entry: &Entry) {
1856 self.record_removed_entry(key, entry);
1857 if let Some(l2) = &self.l2 {
1858 l2.delete_key(key);
1859 }
1860 self.stats.invalidations.fetch_add(1, Ordering::Relaxed);
1861 }
1862
1863 fn invalidate_indexed_many(
1864 &self,
1865 namespace: &str,
1866 labels: &[&str],
1867 kind: IndexedKind,
1868 ) -> usize {
1869 if labels.is_empty() || !self.namespace_exists(namespace) {
1870 return 0;
1871 }
1872
1873 let mut candidates: HashMap<BlobCacheKey, HashSet<String>> = HashMap::new();
1878 {
1879 let index = match kind {
1880 IndexedKind::Tag => self.tag_index.read(),
1881 IndexedKind::Dependency => self.dependency_index.read(),
1882 };
1883 for label in labels {
1884 let scoped = ScopedLabel::new(namespace, *label);
1885 if let Some(keys) = index.get(&scoped) {
1886 for key in keys {
1887 candidates
1888 .entry(key.clone())
1889 .or_default()
1890 .insert((*label).to_string());
1891 }
1892 }
1893 }
1894 }
1895
1896 let mut by_shard: HashMap<usize, Vec<(BlobCacheKey, HashSet<String>)>> = HashMap::new();
1899 for (key, matched_labels) in candidates {
1900 let shard_idx = self.shard_index(&key);
1901 by_shard
1902 .entry(shard_idx)
1903 .or_default()
1904 .push((key, matched_labels));
1905 }
1906
1907 let mut count = 0usize;
1908 for (shard_idx, keys) in by_shard {
1909 let mut shard = self.shards[shard_idx].write();
1910 for (key, matched_labels) in keys {
1911 let still_matches = match kind {
1912 IndexedKind::Tag => shard.entry_has_any_tag(&key, &matched_labels),
1913 IndexedKind::Dependency => {
1914 shard.entry_has_any_dependency(&key, &matched_labels)
1915 }
1916 };
1917 if still_matches {
1918 if let Some(entry) = shard.remove(&key) {
1919 self.record_invalidated_entry(&key, &entry);
1920 count += 1;
1921 }
1922 }
1923 }
1924 }
1925 let l2_count = self
1930 .l2
1931 .as_ref()
1932 .map_or(0, |l2| l2.delete_namespace(namespace));
1933 if l2_count > 0 {
1934 self.stats
1935 .invalidations
1936 .fetch_add(l2_count as u64, Ordering::Relaxed);
1937 }
1938 count.saturating_add(l2_count)
1939 }
1940
1941 fn shard_index(&self, key: &BlobCacheKey) -> usize {
1942 self.shard_index_parts(&key.namespace, &key.key)
1943 }
1944
1945 fn shard_index_parts(&self, namespace: &str, key: &str) -> usize {
1946 let mut hasher = std::collections::hash_map::DefaultHasher::new();
1947 namespace.hash(&mut hasher);
1948 key.hash(&mut hasher);
1949 (hasher.finish() as usize) % self.shards.len()
1950 }
1951
1952 fn check_version(
1953 &self,
1954 shard: &Shard,
1955 key: &BlobCacheKey,
1956 attempted: Option<u64>,
1957 namespace_generation: u64,
1958 ) -> Result<(), CacheError> {
1959 let Some(attempted) = attempted else {
1960 return Ok(());
1961 };
1962 let Some(existing) = shard.existing_version(key, namespace_generation) else {
1963 return Ok(());
1964 };
1965 if existing >= attempted {
1966 self.stats
1967 .version_mismatches
1968 .fetch_add(1, Ordering::Relaxed);
1969 Err(CacheError::VersionMismatch {
1970 existing,
1971 attempted,
1972 })
1973 } else {
1974 Ok(())
1975 }
1976 }
1977
1978 fn evict_until_within_budget(&self, preferred_start: usize) {
1979 while self.bytes_in_use.load(Ordering::Relaxed) > self.config.l1_bytes_max {
1980 let mut evicted = false;
1981 for offset in 0..self.shards.len() {
1982 let idx = (preferred_start + offset) % self.shards.len();
1983 let mut shard = self.shards[idx].write();
1984 if let Some((key, entry)) = shard.evict_one() {
1985 self.stats.evictions.fetch_add(1, Ordering::Relaxed);
1986 self.record_removed_entry(&key, &entry);
1987 drop(shard);
1988 evicted = true;
1989 break;
1990 }
1991 }
1992 if !evicted {
1993 break;
1994 }
1995 }
1996 }
1997
1998 fn evict_namespace_until_within_budget(&self, namespace: &str, preferred_start: usize) {
1999 while self.namespace_bytes(namespace) > self.config.namespace_bytes_max {
2000 let mut evicted = false;
2001 for offset in 0..self.shards.len() {
2002 let idx = (preferred_start + offset) % self.shards.len();
2003 let mut shard = self.shards[idx].write();
2004 if let Some((key, entry)) = shard.remove_one_from_namespace(namespace) {
2005 self.stats.evictions.fetch_add(1, Ordering::Relaxed);
2006 self.record_removed_entry(&key, &entry);
2007 drop(shard);
2008 evicted = true;
2009 break;
2010 }
2011 }
2012 if !evicted {
2013 break;
2014 }
2015 }
2016 }
2017
2018 fn namespace_bytes(&self, namespace: &str) -> usize {
2019 self.namespace_bytes_in_use
2020 .read()
2021 .get(namespace)
2022 .copied()
2023 .unwrap_or(0)
2024 }
2025
2026 fn adjust_namespace_bytes(&self, namespace: &str, old_charge: usize, new_charge: usize) {
2027 let mut usage = self.namespace_bytes_in_use.write();
2028 let bytes = usage.entry(namespace.to_string()).or_insert(0);
2029 *bytes = bytes.saturating_sub(old_charge).saturating_add(new_charge);
2030 }
2031}
2032
2033#[derive(Debug, Default)]
2034pub(crate) struct BlobCacheSweepOutcome {
2035 pub(crate) entries_scanned: usize,
2036 pub(crate) entries_evicted: usize,
2037 pub(crate) expirations: usize,
2038 pub(crate) bytes_reclaimed: u64,
2039 pub(crate) elapsed_ms: u32,
2040 pub(crate) completed: bool,
2041 pub(crate) by_namespace: BTreeMap<String, BlobCacheNamespaceSweep>,
2042}
2043
2044#[derive(Debug, Default)]
2045pub(crate) struct BlobCacheNamespaceSweep {
2046 pub(crate) entries_scanned: usize,
2047 pub(crate) entries_evicted: usize,
2048 pub(crate) bytes_reclaimed: u64,
2049}
2050
2051fn unix_now_ms() -> u64 {
2052 SystemTime::now()
2053 .duration_since(UNIX_EPOCH)
2054 .map(|duration| duration.as_millis() as u64)
2055 .unwrap_or(0)
2056}
2057
2058impl Default for BlobCache {
2059 fn default() -> Self {
2060 Self::with_defaults()
2061 }
2062}
2063
2064#[cfg(test)]
2065mod tests;