reddb_server/storage/cache/
mod.rs1pub mod aggregates;
29pub mod bgwriter;
30pub mod blob;
31pub mod compressor;
32pub mod extended_ttl;
33pub mod promotion_pool;
34pub mod result;
35pub mod spill;
36pub mod sweeper;
37
38pub use aggregates::{AggCacheStats, AggValue, AggregationCache, CardinalityEstimate, NumericAgg};
39pub use blob::{
40 BlobCache, BlobCacheConfig, BlobCacheHit, BlobCachePolicy, BlobCachePut, BlobCacheStats,
41 CacheError, L1Admission, L2Compression, DEFAULT_BLOB_L1_BYTES_MAX, DEFAULT_BLOB_L2_BYTES_MAX,
42 DEFAULT_BLOB_MAX_NAMESPACES, DEFAULT_BLOB_NAMESPACE_BYTES_MAX,
43 METRIC_CACHE_BLOB_L1_BYTES_IN_USE, METRIC_CACHE_BLOB_L2_BYTES_IN_USE,
44 METRIC_CACHE_BLOB_L2_FULL_REJECTIONS_TOTAL, METRIC_CACHE_VERSION_MISMATCH_TOTAL,
45};
46pub use compressor::{CompressError, CompressOpts, Compressed, L2BlobCompressor};
47pub use extended_ttl::{EffectiveExpiry, ExpiryDecision, ExtendedTtlPolicy};
48pub use promotion_pool::{
49 AsyncPromotionPool, PoolOpts, PromotionExecutor, PromotionMetrics, PromotionRequest,
50 ScheduleOutcome,
51};
52pub use result::{
53 CacheKey, CachePolicy, MaterializedViewCache, MaterializedViewDef, RefreshPolicy, ResultCache,
54 ResultCacheStats,
55};
56pub use spill::{SpillConfig, SpillError, SpillManager, SpillStats, SpillableGraph};
57pub use sweeper::{
58 BlobCacheSweeper, NamespaceFlushReport, NamespaceSweepStats, OrphanReport, SweepLimit,
59 SweepReport,
60};
61
62pub fn archive_blob_cache_l2(
95 backend: &dyn crate::storage::backend::RemoteBackend,
96 l2_path: &std::path::Path,
97 prefix: &str,
98) -> Result<usize, crate::storage::backend::BackendError> {
99 let mut count = 0usize;
100 if l2_path.is_file() {
101 backend.upload(l2_path, &reddb_file::blob_cache_l2_backup_pager_key(prefix))?;
102 count += 1;
103 }
104 let control = reddb_file::blob_cache_control_path(l2_path);
105 if control.is_file() {
106 backend.upload(
107 &control,
108 &reddb_file::blob_cache_l2_backup_control_key(prefix),
109 )?;
110 count += 1;
111 }
112 Ok(count)
113}
114
115pub fn restore_blob_cache_l2(
124 backend: &dyn crate::storage::backend::RemoteBackend,
125 prefix: &str,
126 l2_path: &std::path::Path,
127) -> Result<usize, crate::storage::backend::BackendError> {
128 if let Some(parent) = l2_path.parent() {
129 if !parent.as_os_str().is_empty() {
130 std::fs::create_dir_all(parent)
131 .map_err(|err| crate::storage::backend::BackendError::Transport(err.to_string()))?;
132 }
133 }
134 let mut count = 0usize;
135 if backend.download(&reddb_file::blob_cache_l2_backup_pager_key(prefix), l2_path)? {
136 count += 1;
137 }
138 let control = reddb_file::blob_cache_control_path(l2_path);
139 if backend.download(
140 &reddb_file::blob_cache_l2_backup_control_key(prefix),
141 &control,
142 )? {
143 count += 1;
144 }
145 Ok(count)
146}
147
148#[cfg(test)]
149mod backup_helpers_tests {
150 use super::*;
151 use crate::storage::backend::LocalBackend;
152 use std::sync::atomic::{AtomicU64, Ordering};
153
154 fn write_file(path: &std::path::Path, bytes: &[u8]) {
155 if let Some(parent) = path.parent() {
156 std::fs::create_dir_all(parent).unwrap();
157 }
158 std::fs::write(path, bytes).unwrap();
159 }
160
161 static SCRATCH_COUNTER: AtomicU64 = AtomicU64::new(0);
167 fn scratch(label: &str) -> std::path::PathBuf {
168 let pid = std::process::id();
169 let n = SCRATCH_COUNTER.fetch_add(1, Ordering::SeqCst);
170 let p = std::env::temp_dir().join(format!("reddb-blobcache-bk-{label}-{pid}-{n}"));
171 let _ = std::fs::remove_dir_all(&p);
172 std::fs::create_dir_all(&p).unwrap();
173 p
174 }
175
176 #[test]
182 fn archive_then_restore_round_trips_l2_pager_and_control_files() {
183 let scratch_dir = scratch("pair-src");
184 let l2_src = scratch_dir.join("cache.rdb");
185 write_file(&l2_src, b"pager-bytes-on-disk");
186 write_file(
187 &reddb_file::blob_cache_control_path(&l2_src),
188 b"control-sidecar-bytes",
189 );
190
191 let backend_root = scratch("pair-be");
192 let prefix = format!("{}/blob_cache/", backend_root.display());
193
194 let uploaded =
195 archive_blob_cache_l2(&LocalBackend, &l2_src, &prefix).expect("archive succeeds");
196 assert_eq!(uploaded, 2, "pager + control sidecar uploaded");
197
198 let dst_dir = scratch("pair-dst");
199 let l2_dst = dst_dir.join("cache.rdb");
200 let downloaded =
201 restore_blob_cache_l2(&LocalBackend, &prefix, &l2_dst).expect("restore succeeds");
202 assert_eq!(downloaded, 2);
203
204 assert_eq!(std::fs::read(&l2_dst).unwrap(), b"pager-bytes-on-disk");
205 assert_eq!(
206 std::fs::read(reddb_file::blob_cache_control_path(&l2_dst)).unwrap(),
207 b"control-sidecar-bytes"
208 );
209
210 let _ = std::fs::remove_dir_all(&scratch_dir);
211 let _ = std::fs::remove_dir_all(&backend_root);
212 let _ = std::fs::remove_dir_all(&dst_dir);
213 }
214
215 #[test]
216 fn archive_missing_l2_path_is_noop() {
217 let backend_root = scratch("be-missing");
218 let prefix = format!("{}/blob_cache/", backend_root.display());
219 let count = archive_blob_cache_l2(
220 &LocalBackend,
221 std::path::Path::new("/nonexistent/path/for/reddb-test.rdb"),
222 &prefix,
223 )
224 .expect("missing path treated as nothing to archive");
225 assert_eq!(count, 0);
226 let _ = std::fs::remove_dir_all(&backend_root);
227 }
228
229 #[test]
230 fn restore_with_no_objects_creates_empty_parent_dir() {
231 let backend_root = scratch("be-empty");
232 let prefix = format!("{}/blob_cache/", backend_root.display());
233 let dst_dir = scratch("dst-empty");
234 let l2_dst = dst_dir.join("cache.rdb");
235 let count =
236 restore_blob_cache_l2(&LocalBackend, &prefix, &l2_dst).expect("empty restore is ok");
237 assert_eq!(count, 0);
238 let _ = std::fs::remove_dir_all(&backend_root);
239 let _ = std::fs::remove_dir_all(&dst_dir);
240 }
241
242 #[test]
257 fn full_round_trip_via_blob_cache_preserves_entries_after_restore() {
258 use crate::storage::cache::blob::{BlobCache, BlobCacheConfig, BlobCachePut};
259
260 let src_dir = scratch("rt-src");
261 let dst_dir = scratch("rt-dst");
262 let backend_root = scratch("rt-be");
263 let l2_src = src_dir.join("blob-cache.rdb");
264 let l2_dst = dst_dir.join("blob-cache.rdb");
265 let prefix = format!("{}/blob_cache/", backend_root.display());
266
267 {
269 let cache = BlobCache::open_with_l2(
270 BlobCacheConfig::default()
271 .with_l1_bytes_max(64 * 1024)
272 .with_shard_count(2)
273 .with_max_namespaces(8)
274 .with_l2_path(&l2_src),
275 )
276 .expect("open l2 src");
277 cache
278 .put("ns-a", "k1", BlobCachePut::new(b"value-1".to_vec()))
279 .expect("put k1");
280 cache
281 .put(
282 "ns-b",
283 "k2",
284 BlobCachePut::new(b"value-2-longer-payload".to_vec()),
285 )
286 .expect("put k2");
287 assert_eq!(cache.l2_path(), Some(l2_src.as_path()));
289 } let uploaded = archive_blob_cache_l2(&LocalBackend, &l2_src, &prefix).expect("archive l2");
293 assert_eq!(uploaded, 2, "pager + control uploaded");
294
295 let restored = restore_blob_cache_l2(&LocalBackend, &prefix, &l2_dst).expect("restore l2");
297 assert_eq!(restored, 2, "pager + control downloaded");
298
299 let restored_cache = BlobCache::open_with_l2(
303 BlobCacheConfig::default()
304 .with_l1_bytes_max(64 * 1024)
305 .with_shard_count(2)
306 .with_max_namespaces(8)
307 .with_l2_path(&l2_dst),
308 )
309 .expect("open l2 dst");
310 let hit_a = restored_cache
311 .get("ns-a", "k1")
312 .expect("k1 survives restore");
313 assert_eq!(hit_a.value(), b"value-1");
314 let hit_b = restored_cache
315 .get("ns-b", "k2")
316 .expect("k2 survives restore");
317 assert_eq!(hit_b.value(), b"value-2-longer-payload");
318
319 let _ = std::fs::remove_dir_all(&src_dir);
320 let _ = std::fs::remove_dir_all(&dst_dir);
321 let _ = std::fs::remove_dir_all(&backend_root);
322 }
323
324 #[test]
330 fn skipped_archive_leaves_restored_cache_cold() {
331 use crate::storage::cache::blob::{BlobCache, BlobCacheConfig, BlobCachePut};
332
333 let src_dir = scratch("cold-src");
334 let dst_dir = scratch("cold-dst");
335 let l2_src = src_dir.join("blob-cache.rdb");
336 let l2_dst = dst_dir.join("blob-cache.rdb");
337
338 {
339 let cache = BlobCache::open_with_l2(BlobCacheConfig::default().with_l2_path(&l2_src))
340 .expect("open l2 src");
341 cache
342 .put("ns", "k", BlobCachePut::new(b"value".to_vec()))
343 .expect("put k");
344 }
345
346 let cold_cache = BlobCache::open_with_l2(BlobCacheConfig::default().with_l2_path(&l2_dst))
349 .expect("open l2 dst");
350 assert!(
351 cold_cache.get("ns", "k").is_none(),
352 "restore without include_blob_cache must yield a cold cache"
353 );
354
355 let _ = std::fs::remove_dir_all(&src_dir);
356 let _ = std::fs::remove_dir_all(&dst_dir);
357 }
358}