bhandaar 0.1.0-alpha.1

On-disk LRU/TTL file cache for Rust with cross-process concurrency via flock(2)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
use std::fs::File;
use std::io::{self, Read};
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;

use crate::error::BhandaarError;
use crate::eviction;
use crate::hasher;
use crate::metadata::EntryMeta;
use crate::shard::{self, Shard};
use crate::store;

/// Counter for unique temp file names during atomic put operations.
static PUT_TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);

/// On-disk LRU/TTL file cache with cross-process concurrency.
pub struct Bhandaar {
    config: crate::BhandaarConfig,
    shards: Vec<Shard>,
    total_size: AtomicU64,
}

impl Bhandaar {
    /// Create a new Bhandaar cache instance.
    pub fn new(config: crate::BhandaarConfig) -> std::io::Result<Self> {
        std::fs::create_dir_all(&config.root)?;

        let shards: Vec<Shard> = (0..config.shards).map(|_| Shard::new()).collect();

        let cache = Self {
            config,
            shards,
            total_size: AtomicU64::new(0),
        };

        cache.rebuild_index()?;
        Ok(cache)
    }

    // ========================================================================
    // Streaming API
    // ========================================================================

    /// Get a file handle for streaming reads.
    pub fn get_file(&self, key: &str) -> Result<Option<File>, BhandaarError> {
        let idx = shard::shard_index(key, self.config.shards);
        let shard = &self.shards[idx];

        let data_path = self.data_path(key);
        let meta_path = self.meta_path(key);

        // Read metadata
        let mut meta = match store::read_meta(&meta_path) {
            Ok(m) => m,
            Err(BhandaarError::CorruptedMetadata(_)) | Err(BhandaarError::SerializationError(_)) => {
                let _ = store::delete_file(&data_path);
                let _ = store::delete_file(&meta_path);
                shard.remove(key);
                return Ok(None);
            }
            Err(e) => return Err(e),
        };

        // Check TTL
        if meta.is_expired() {
            let _ = store::delete_file(&data_path);
            let _ = store::delete_file(&meta_path);
            shard.remove(key);
            self.total_size.fetch_sub(meta.size, Ordering::SeqCst);
            return Ok(None);
        }

        // Open file for reading
        let file = File::open(&data_path).map_err(|e| {
            let _ = store::delete_file(&meta_path);
            shard.remove(key);
            BhandaarError::Io(e)
        })?;

        // Update last_accessed (best effort)
        meta.touch();
        let _ = store::write_meta(&meta_path, &meta);

        Ok(Some(file))
    }

    /// Put data from a reader (streaming write).
    pub fn put_reader<R: Read>(
        &self,
        key: &str,
        mut reader: R,
        size: u64,
    ) -> Result<(), BhandaarError> {
        self.put_reader_with_ttl(key, &mut reader, size, self.config.default_ttl)
    }

    /// Put data from a reader with explicit TTL.
    pub fn put_reader_with_ttl<R: Read>(
        &self,
        key: &str,
        mut reader: R,
        size: u64,
        ttl: Option<Duration>,
    ) -> Result<(), BhandaarError> {
        let idx = shard::shard_index(key, self.config.shards);
        let shard = &self.shards[idx];

        let data_path = self.data_path(key);
        let meta_path = self.meta_path(key);

        // Ensure parent directory exists
        if let Some(parent) = data_path.parent() {
            std::fs::create_dir_all(parent).map_err(BhandaarError::Io)?;
        }

        // Write to a unique temp file to avoid concurrent writers clobbering each other
        let counter = PUT_TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
        let temp_path = data_path.with_file_name(format!(
            "{}.{}.put.tmp",
            data_path.file_stem().unwrap().to_str().unwrap(),
            counter
        ));

        let mut file = File::create(&temp_path).map_err(BhandaarError::Io)?;
        io::copy(&mut reader, &mut file).map_err(BhandaarError::Io)?;
        file.sync_all().map_err(BhandaarError::Io)?;

        // Write metadata to temp file too
        let temp_meta_path = meta_path.with_file_name(format!(
            "{}.{}.put.meta.tmp",
            meta_path.file_stem().unwrap().to_str().unwrap(),
            counter
        ));
        let meta = EntryMeta::new(key.to_string(), size, ttl);
        store::write_meta(&temp_meta_path, &meta)?;

        // Atomically claim the key — if another thread already inserted, clean up our temp files
        if !shard.insert_if_absent(key.to_string(), data_path.clone()) {
            let _ = store::delete_file(&temp_path);
            let _ = store::delete_file(&temp_meta_path);
            return Err(BhandaarError::AlreadyExists(key.to_string()));
        }

        // We won the race — rename temp files to final paths
        // Note: there's a brief window where the shard has the final path but the file
        // is still at the temp path. A concurrent reader might get NotFound during this
        // window. This is acceptable for a cache (advisory by nature).
        let _ = std::fs::rename(&temp_path, &data_path);
        let _ = std::fs::rename(&temp_meta_path, &meta_path);

        self.total_size.fetch_add(size, Ordering::SeqCst);
        self.evict_if_needed();

        Ok(())
    }

    /// Put data from a reader, inferring size from the reader.
    pub fn put_reader_auto_size<R: Read>(
        &self,
        key: &str,
        mut reader: R,
        ttl: Option<Duration>,
    ) -> Result<u64, BhandaarError> {
        let idx = shard::shard_index(key, self.config.shards);
        let shard = &self.shards[idx];

        let data_path = self.data_path(key);
        let meta_path = self.meta_path(key);

        if let Some(parent) = data_path.parent() {
            std::fs::create_dir_all(parent).map_err(BhandaarError::Io)?;
        }

        // Write to unique temp file
        let counter = PUT_TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
        let temp_path = data_path.with_file_name(format!(
            "{}.{}.put.tmp",
            data_path.file_stem().unwrap().to_str().unwrap(),
            counter
        ));

        let mut file = File::create(&temp_path).map_err(BhandaarError::Io)?;
        let size = io::copy(&mut reader, &mut file).map_err(BhandaarError::Io)?;
        file.sync_all().map_err(BhandaarError::Io)?;

        let temp_meta_path = meta_path.with_file_name(format!(
            "{}.{}.put.meta.tmp",
            meta_path.file_stem().unwrap().to_str().unwrap(),
            counter
        ));
        let meta = EntryMeta::new(key.to_string(), size, ttl);
        store::write_meta(&temp_meta_path, &meta)?;

        if !shard.insert_if_absent(key.to_string(), data_path.clone()) {
            let _ = store::delete_file(&temp_path);
            let _ = store::delete_file(&temp_meta_path);
            return Err(BhandaarError::AlreadyExists(key.to_string()));
        }

        let _ = std::fs::rename(&temp_path, &data_path);
        let _ = std::fs::rename(&temp_meta_path, &meta_path);

        self.total_size.fetch_add(size, Ordering::SeqCst);
        self.evict_if_needed();

        Ok(size)
    }

    // ========================================================================
    // In-memory API
    // ========================================================================

    /// Get data by key (loads entire file into memory).
    pub fn get(&self, key: &str) -> Result<Option<Vec<u8>>, BhandaarError> {
        let idx = shard::shard_index(key, self.config.shards);
        let shard = &self.shards[idx];

        let data_path = self.data_path(key);
        let meta_path = self.meta_path(key);

        let mut meta = match store::read_meta(&meta_path) {
            Ok(m) => m,
            Err(BhandaarError::CorruptedMetadata(_)) | Err(BhandaarError::SerializationError(_)) => {
                let _ = store::delete_file(&data_path);
                let _ = store::delete_file(&meta_path);
                shard.remove(key);
                return Ok(None);
            }
            Err(e) => return Err(e),
        };

        if meta.is_expired() {
            let _ = store::delete_file(&data_path);
            let _ = store::delete_file(&meta_path);
            shard.remove(key);
            self.total_size.fetch_sub(meta.size, Ordering::SeqCst);
            return Ok(None);
        }

        let data = store::read_data(&data_path).map_err(|e| {
            let _ = store::delete_file(&meta_path);
            shard.remove(key);
            BhandaarError::Io(e)
        })?;

        meta.touch();
        let _ = store::write_meta(&meta_path, &meta);

        Ok(Some(data))
    }

    /// Put data with optional TTL.
    pub fn put(&self, key: &str, data: &[u8]) -> Result<(), BhandaarError> {
        self.put_with_ttl(key, data, self.config.default_ttl)
    }

    /// Put data with explicit TTL.
    pub fn put_with_ttl(
        &self,
        key: &str,
        data: &[u8],
        ttl: Option<Duration>,
    ) -> Result<(), BhandaarError> {
        let idx = shard::shard_index(key, self.config.shards);
        let shard = &self.shards[idx];

        let data_path = self.data_path(key);
        let meta_path = self.meta_path(key);

        // Write to unique temp file
        let counter = PUT_TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
        let temp_path = data_path.with_file_name(format!(
            "{}.{}.put.tmp",
            data_path.file_stem().unwrap().to_str().unwrap(),
            counter
        ));

        store::write_data(&temp_path, data).map_err(BhandaarError::Io)?;

        let temp_meta_path = meta_path.with_file_name(format!(
            "{}.{}.put.meta.tmp",
            meta_path.file_stem().unwrap().to_str().unwrap(),
            counter
        ));
        let meta = EntryMeta::new(key.to_string(), data.len() as u64, ttl);
        store::write_meta(&temp_meta_path, &meta)?;

        // Atomically claim the key
        if !shard.insert_if_absent(key.to_string(), data_path.clone()) {
            let _ = store::delete_file(&temp_path);
            let _ = store::delete_file(&temp_meta_path);
            return Err(BhandaarError::AlreadyExists(key.to_string()));
        }

        // Rename temp files to final paths
        let _ = std::fs::rename(&temp_path, &data_path);
        let _ = std::fs::rename(&temp_meta_path, &meta_path);

        self.total_size.fetch_add(data.len() as u64, Ordering::SeqCst);
        self.evict_if_needed();

        Ok(())
    }

    // ========================================================================
    // Common operations
    // ========================================================================

    /// Remove an entry by key.
    pub fn remove(&self, key: &str) -> Result<bool, BhandaarError> {
        let idx = shard::shard_index(key, self.config.shards);
        let shard = &self.shards[idx];

        match shard.remove(key) {
            Some(data_path) => {
                let meta_path = data_path.with_extension("dat.meta");
                if let Ok(meta) = store::read_meta(&meta_path) {
                    self.total_size.fetch_sub(meta.size, Ordering::SeqCst);
                }
                let _ = store::delete_file(&data_path);
                let _ = store::delete_file(&meta_path);
                Ok(true)
            }
            None => Ok(false),
        }
    }

    /// Check if a key exists (and is not expired).
    pub fn contains(&self, key: &str) -> Result<bool, BhandaarError> {
        let idx = shard::shard_index(key, self.config.shards);
        let shard = &self.shards[idx];

        if !shard.contains(key) {
            return Ok(false);
        }

        let meta_path = self.meta_path(key);
        match store::read_meta(&meta_path) {
            Ok(meta) => Ok(!meta.is_expired()),
            Err(_) => Ok(false),
        }
    }

    /// Get the current total size of cached data.
    pub fn size(&self) -> u64 {
        self.total_size.load(Ordering::SeqCst)
    }

    /// Clear all entries from the cache.
    pub fn clear(&self) -> Result<(), BhandaarError> {
        for shard in &self.shards {
            let entries = shard.entries();
            for (key, data_path) in entries {
                let meta_path = data_path.with_extension("dat.meta");
                let _ = store::delete_file(&data_path);
                let _ = store::delete_file(&meta_path);
                shard.remove(&key);
            }
        }
        self.total_size.store(0, Ordering::SeqCst);
        Ok(())
    }

    /// Get all keys in the cache.
    pub fn keys(&self) -> Result<Vec<String>, BhandaarError> {
        let mut all_keys = Vec::new();
        for shard in &self.shards {
            let entries = shard.entries();
            for (key, _) in entries {
                all_keys.push(key);
            }
        }
        Ok(all_keys)
    }

    /// Get cache configuration.
    pub fn config(&self) -> &crate::BhandaarConfig {
        &self.config
    }

    // ========================================================================
    // Private helpers
    // ========================================================================

    fn data_path(&self, key: &str) -> PathBuf {
        self.config.root.join(hasher::data_path(key))
    }

    fn meta_path(&self, key: &str) -> PathBuf {
        self.config.root.join(hasher::meta_path(key))
    }

    /// Evict entries if over capacity.
    fn evict_if_needed(&self) {
        while self.total_size.load(Ordering::SeqCst) > self.config.max_size {
            let mut evicted = false;

            for shard in &self.shards {
                let _guard = shard.lock_exclusive();

                let freed = eviction::evict_expired(shard);
                if freed > 0 {
                    self.total_size.fetch_sub(freed, Ordering::SeqCst);
                    evicted = true;
                    continue;
                }

                if let Some(freed) = eviction::evict_lru(shard) {
                    self.total_size.fetch_sub(freed, Ordering::SeqCst);
                    evicted = true;
                    break;
                }
            }

            if !evicted {
                break;
            }
        }
    }

    /// Rebuild the in-memory index from existing files on disk.
    fn rebuild_index(&self) -> std::io::Result<()> {
        for entry in std::fs::read_dir(&self.config.root)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                self.rebuild_shard_index(&path)?;
            }
        }
        Ok(())
    }

    fn rebuild_shard_index(&self, dir: &std::path::Path) -> std::io::Result<()> {
        for entry in std::fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                self.rebuild_shard_index(&path)?;
            } else if let Some(name) = path.file_name() {
                if let Some(name_str) = name.to_str() {
                    if name_str.ends_with(".dat.meta") {
                        if let Ok(meta) = store::read_meta(&path) {
                            let data_path = path.with_extension("");
                            let idx = shard::shard_index(&meta.key, self.config.shards);
                            let shard = &self.shards[idx];
                            shard.insert(meta.key, data_path);
                            self.total_size.fetch_add(meta.size, Ordering::SeqCst);
                        }
                    }
                }
            }
        }
        Ok(())
    }
}