cooklang-sync-client 0.5.0

A client library for cooklang-sync
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
use log::trace;
use quick_cache::{sync::Cache, Weighter};
use sha2::{Digest, Sha256};
use std::path::{Path, PathBuf};
use tokio::fs::{self, create_dir_all, File};
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader, BufWriter};

use crate::errors::SyncError;

const BINARY_CHUNK_SIZE: usize = 1_024 * 1_024; // 1 MB
const BINARY_HASH_SIZE: usize = 32;
const TEXT_HASH_SIZE: usize = 10;

pub struct Chunker {
    cache: InMemoryCache,
    base_path: PathBuf,
}

type Result<T, E = SyncError> = std::result::Result<T, E>;

impl Chunker {
    pub fn new(cache: InMemoryCache, base_path: PathBuf) -> Chunker {
        Chunker { cache, base_path }
    }

    fn full_path(&self, path: &str) -> PathBuf {
        let mut base = self.base_path.clone();
        base.push(path);
        base
    }

    pub async fn hashify(&mut self, path: &str) -> Result<Vec<String>> {
        let p = Path::new(path);

        // TODO probably there's a better way to check if file is binary
        if is_text(p) {
            self.hashify_text(path).await
        } else if is_binary(p) {
            self.hashify_binary(path).await
        } else {
            Err(SyncError::UnlistedFileFormat(path.to_string()))
        }
    }

    async fn hashify_binary(&mut self, path: &str) -> Result<Vec<String>> {
        let file = File::open(self.full_path(path))
            .await
            .map_err(|e| SyncError::from_io_error(path, e))?;
        let mut reader = BufReader::new(file);
        let mut hashes = Vec::new();
        let mut buffer = vec![0u8; BINARY_CHUNK_SIZE];

        loop {
            let bytes_read = reader
                .read(&mut buffer)
                .await
                .map_err(|e| SyncError::from_io_error(path, e))?;
            if bytes_read == 0 {
                break;
            }

            let data = &buffer[..bytes_read].to_vec();
            let hash = self.hash(data, BINARY_HASH_SIZE);
            self.save_chunk(&hash, data.to_vec())?;
            hashes.push(hash);
        }

        Ok(hashes)
    }

    async fn hashify_text(&mut self, path: &str) -> Result<Vec<String>> {
        let file = File::open(self.full_path(path))
            .await
            .map_err(|e| SyncError::from_io_error(path, e))?;
        let mut reader = BufReader::new(file);
        let mut buffer = Vec::new();
        let mut hashes = Vec::new();

        while reader
            .read_until(b'\n', &mut buffer)
            .await
            .map_err(|e| SyncError::from_io_error(path, e))?
            > 0
        {
            let data: Vec<u8> = buffer.clone();
            let hash = self.hash(&data, TEXT_HASH_SIZE);
            self.save_chunk(&hash, data)?;
            hashes.push(hash);

            // Clear the buffer for the next line
            buffer.clear();
        }

        Ok(hashes)
    }

    pub fn hash(&self, data: &Vec<u8>, size: usize) -> String {
        let mut hasher = Sha256::new();

        hasher.update(data);

        let result = hasher.finalize();
        let hex_string = format!("{:x}", result);

        hex_string[0..size].to_string()
    }

    pub fn exists(&mut self, path: &str) -> bool {
        let full_path = self.full_path(path);

        full_path.exists()
    }

    // TODO can be a problem as it expects cache to contain all chunks
    pub async fn save(&mut self, path: &str, hashes: Vec<&str>) -> Result<()> {
        trace!("saving {:?}", path);
        let full_path = self.full_path(path);

        if let Some(parent) = full_path.parent() {
            create_dir_all(parent)
                .await
                .map_err(|e| SyncError::from_io_error(path, e))?;
        }

        let file = File::create(full_path)
            .await
            .map_err(|e| SyncError::from_io_error(path, e))?;
        let mut writer = BufWriter::new(file);

        for hash in hashes {
            let chunk = self.cache.get(hash)?;

            writer
                .write_all(&chunk)
                .await
                .map_err(|e| SyncError::from_io_error(path, e))?;
        }

        writer
            .flush()
            .await
            .map_err(|e| SyncError::from_io_error(path, e))?;

        Ok(())
    }

    pub async fn delete(&mut self, path: &str) -> Result<()> {
        trace!("deleting {:?}", path);
        let full_path = self.full_path(path);

        fs::remove_file(&full_path)
            .await
            .map_err(|e| SyncError::from_io_error(path, e))?;

        // Walk parents upward and remove empty directories. `remove_dir`
        // only succeeds on empty directories, which gives us strict-empty
        // semantics without manually counting entries. Stop at the storage
        // root (never remove it) and on any error (most commonly ENOTEMPTY
        // when a sibling file is present — that's the normal terminating
        // condition, not a failure to propagate).
        //
        // SAFETY: `dir == self.base_path` is a lexical comparison. It is
        // sound here because `full_path` is built by `base_path.clone()`
        // + `push(path)` with no canonicalization on either side, and the
        // server-provided `path` is trusted to not contain `..` segments
        // (the indexer produces forward-slash relative paths via WalkDir,
        // which never emits parent components). If that contract ever
        // weakens, harden this guard with `starts_with` or a depth check.
        let mut parent = full_path.parent();
        while let Some(dir) = parent {
            if dir == self.base_path {
                break;
            }
            if let Err(e) = fs::remove_dir(dir).await {
                trace!("stopping empty-dir cleanup at {:?}: {}", dir, e);
                break;
            }
            parent = dir.parent();
        }

        Ok(())
    }

    pub fn read_chunk(&self, chunk_hash: &str) -> Result<Vec<u8>> {
        self.cache.get(chunk_hash)
    }

    pub fn save_chunk(&mut self, chunk_hash: &str, content: Vec<u8>) -> Result<()> {
        self.cache.set(chunk_hash, content)
    }

    pub fn check_chunk(&self, chunk_hash: &str) -> bool {
        if chunk_hash.is_empty() {
            true
        } else {
            self.cache.contains(chunk_hash)
        }
    }
}

#[derive(Clone)]
pub struct BytesWeighter;

impl Weighter<String, Vec<u8>> for BytesWeighter {
    fn weight(&self, _key: &String, val: &Vec<u8>) -> u64 {
        // Be cautions out about zero weights!
        val.len().clamp(1, u64::MAX as usize) as u64
    }
}

pub struct InMemoryCache {
    cache: Cache<String, Vec<u8>, BytesWeighter>,
}

impl InMemoryCache {
    pub fn new(total_keys: usize, total_weight: u64) -> InMemoryCache {
        InMemoryCache {
            cache: Cache::with_weighter(total_keys, total_weight, BytesWeighter),
        }
    }

    fn get(&self, chunk_hash: &str) -> Result<Vec<u8>> {
        if chunk_hash.is_empty() {
            return Ok(vec![]);
        }

        match self.cache.get(chunk_hash) {
            Some(content) => Ok(content.clone()),
            None => Err(SyncError::GetFromCacheError),
        }
    }

    fn set(&mut self, chunk_hash: &str, content: Vec<u8>) -> Result<()> {
        // trace!("setting hash {:?} data  {:?}", chunk_hash, content.len());
        self.cache.insert(chunk_hash.to_string(), content);
        Ok(())
    }

    fn contains(&self, chunk_hash: &str) -> bool {
        match self.cache.get(chunk_hash) {
            Some(_content) => true,
            None => false,
        }
    }
}

pub fn is_binary(p: &Path) -> bool {
    if let Some(ext) = p.extension() {
        let ext = ext.to_ascii_lowercase();

        ext == "jpg" || ext == "jpeg" || ext == "png"
    } else {
        false
    }
}

pub fn is_text(p: &Path) -> bool {
    // Check for specific filenames without extensions
    if let Some(file_name) = p.file_name() {
        let file_name_str = file_name.to_string_lossy();
        if file_name_str == ".shopping-list"
            || file_name_str == ".shopping-checked"
            || file_name_str == ".bookmarks"
        {
            return true;
        }
    }

    // Check for file extensions
    if let Some(ext) = p.extension() {
        let ext = ext.to_ascii_lowercase();

        ext == "cook"
            || ext == "conf"
            || ext == "yaml"
            || ext == "yml"
            || ext == "md"
            || ext == "menu"
            || ext == "jinja"
            || ext == "j2"
    } else {
        false
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::Path;
    use tempfile::TempDir;
    use tokio::fs::File;
    use tokio::io::AsyncWriteExt;

    #[test]
    fn test_is_binary_with_jpg() {
        let path = Path::new("image.jpg");
        assert!(is_binary(path));
    }

    #[test]
    fn test_is_binary_with_jpeg() {
        let path = Path::new("image.JPEG");
        assert!(is_binary(path));
    }

    #[test]
    fn test_is_binary_with_png() {
        let path = Path::new("image.png");
        assert!(is_binary(path));
    }

    #[test]
    fn test_is_binary_returns_false_for_text() {
        let path = Path::new("recipe.cook");
        assert!(!is_binary(path));
    }

    #[test]
    fn test_is_text_with_cook_extension() {
        let path = Path::new("recipe.cook");
        assert!(is_text(path));
    }

    #[test]
    fn test_is_text_with_md_extension() {
        let path = Path::new("README.md");
        assert!(is_text(path));
    }

    #[test]
    fn test_is_text_with_yaml_extension() {
        let path = Path::new("config.yaml");
        assert!(is_text(path));
    }

    #[test]
    fn test_is_text_with_yml_extension() {
        let path = Path::new("config.yml");
        assert!(is_text(path));
    }

    #[test]
    fn test_is_text_with_special_filenames() {
        assert!(is_text(Path::new(".shopping-list")));
        assert!(is_text(Path::new(".shopping-checked")));
        assert!(is_text(Path::new(".bookmarks")));
    }

    #[test]
    fn test_is_text_returns_false_for_unknown() {
        let path = Path::new("file.unknown");
        assert!(!is_text(path));
    }

    #[test]
    fn test_hash_consistency() {
        let cache = InMemoryCache::new(100, 1000);
        let chunker = Chunker::new(cache, PathBuf::from("/tmp"));

        let data = b"Hello, World!".to_vec();
        let hash1 = chunker.hash(&data, 10);
        let hash2 = chunker.hash(&data, 10);

        // Same input should produce same hash
        assert_eq!(hash1, hash2);
    }

    #[test]
    fn test_hash_different_data_produces_different_hash() {
        let cache = InMemoryCache::new(100, 1000);
        let chunker = Chunker::new(cache, PathBuf::from("/tmp"));

        let data1 = b"Hello, World!".to_vec();
        let data2 = b"Goodbye, World!".to_vec();

        let hash1 = chunker.hash(&data1, 10);
        let hash2 = chunker.hash(&data2, 10);

        // Different input should produce different hash
        assert_ne!(hash1, hash2);
    }

    #[test]
    fn test_hash_respects_size_parameter() {
        let cache = InMemoryCache::new(100, 1000);
        let chunker = Chunker::new(cache, PathBuf::from("/tmp"));

        let data = b"Hello, World!".to_vec();
        let hash_short = chunker.hash(&data, 5);
        let hash_long = chunker.hash(&data, 10);

        assert_eq!(hash_short.len(), 5);
        assert_eq!(hash_long.len(), 10);
        // Shorter hash should be prefix of longer hash
        assert!(hash_long.starts_with(&hash_short));
    }

    #[test]
    fn test_inmemory_cache_set_and_get() {
        let mut cache = InMemoryCache::new(100, 1000);

        let hash = "testhash123";
        let data = vec![1, 2, 3, 4, 5];

        cache.set(hash, data.clone()).unwrap();
        let retrieved = cache.get(hash).unwrap();

        assert_eq!(data, retrieved);
    }

    #[test]
    fn test_inmemory_cache_get_nonexistent() {
        let cache = InMemoryCache::new(100, 1000);

        let result = cache.get("nonexistent");
        assert!(result.is_err());
    }

    #[test]
    fn test_inmemory_cache_contains() {
        let mut cache = InMemoryCache::new(100, 1000);

        let hash = "testhash456";
        let data = vec![1, 2, 3];

        assert!(!cache.contains(hash));
        cache.set(hash, data).unwrap();
        assert!(cache.contains(hash));
    }

    #[test]
    fn test_inmemory_cache_empty_hash() {
        let cache = InMemoryCache::new(100, 1000);

        // Empty hash should return empty vector
        let result = cache.get("").unwrap();
        assert_eq!(result, Vec::<u8>::new());
    }

    #[test]
    fn test_chunker_check_chunk_empty_hash() {
        let cache = InMemoryCache::new(100, 1000);
        let chunker = Chunker::new(cache, PathBuf::from("/tmp"));

        // Empty hash should return true
        assert!(chunker.check_chunk(""));
    }

    #[test]
    fn test_chunker_check_chunk_existing() {
        let mut cache = InMemoryCache::new(100, 1000);
        cache.set("existinghash", vec![1, 2, 3]).unwrap();
        let chunker = Chunker::new(cache, PathBuf::from("/tmp"));

        assert!(chunker.check_chunk("existinghash"));
    }

    #[test]
    fn test_chunker_check_chunk_nonexistent() {
        let cache = InMemoryCache::new(100, 1000);
        let chunker = Chunker::new(cache, PathBuf::from("/tmp"));

        assert!(!chunker.check_chunk("nonexistent"));
    }

    #[tokio::test]
    async fn test_chunker_hashify_text_round_trip() {
        let temp_dir = TempDir::new().unwrap();
        let cache = InMemoryCache::new(1000, 100000);
        let mut chunker = Chunker::new(cache, temp_dir.path().to_path_buf());

        // Create a test file
        let test_file = "test.cook";
        let content = "Line 1\nLine 2\nLine 3\n";
        let mut file = File::create(temp_dir.path().join(test_file)).await.unwrap();
        file.write_all(content.as_bytes()).await.unwrap();
        file.flush().await.unwrap();

        // Hashify the file
        let hashes = chunker.hashify(test_file).await.unwrap();

        // Should have 3 hashes (one per line)
        assert_eq!(hashes.len(), 3);

        // Verify all chunks are in cache
        for hash in &hashes {
            assert!(chunker.check_chunk(hash));
        }
    }

    #[tokio::test]
    async fn test_chunker_save_and_read() {
        let temp_dir = TempDir::new().unwrap();
        let cache = InMemoryCache::new(1000, 100000);
        let mut chunker = Chunker::new(cache, temp_dir.path().to_path_buf());

        // Save some chunks to cache
        let chunk1 = b"Hello ".to_vec();
        let chunk2 = b"World!".to_vec();
        let hash1 = chunker.hash(&chunk1, 10);
        let hash2 = chunker.hash(&chunk2, 10);

        chunker.save_chunk(&hash1, chunk1).unwrap();
        chunker.save_chunk(&hash2, chunk2).unwrap();

        // Save to file
        let test_file = "output.txt";
        chunker.save(test_file, vec![&hash1, &hash2]).await.unwrap();

        // Verify file exists
        assert!(chunker.exists(test_file));

        // Read file content
        let content = tokio::fs::read(temp_dir.path().join(test_file))
            .await
            .unwrap();
        assert_eq!(content, b"Hello World!");
    }

    #[tokio::test]
    async fn test_chunker_delete() {
        let temp_dir = TempDir::new().unwrap();
        let cache = InMemoryCache::new(1000, 100000);
        let mut chunker = Chunker::new(cache, temp_dir.path().to_path_buf());

        // Create a test file
        let test_file = "to_delete.txt";
        let mut file = File::create(temp_dir.path().join(test_file)).await.unwrap();
        file.write_all(b"test content").await.unwrap();
        file.flush().await.unwrap();

        assert!(chunker.exists(test_file));

        // Delete the file
        chunker.delete(test_file).await.unwrap();

        // Verify file doesn't exist
        assert!(!chunker.exists(test_file));
    }

    #[test]
    fn test_bytes_weighter() {
        let weighter = BytesWeighter;

        let key = "test".to_string();
        let small_val = vec![1, 2, 3];
        let large_val = vec![0u8; 1000];

        assert_eq!(weighter.weight(&key, &small_val), 3);
        assert_eq!(weighter.weight(&key, &large_val), 1000);
    }

    #[test]
    fn test_bytes_weighter_empty_vec() {
        let weighter = BytesWeighter;

        let key = "test".to_string();
        let empty_val = vec![];

        // Should clamp to minimum of 1
        assert_eq!(weighter.weight(&key, &empty_val), 1);
    }

    #[tokio::test]
    async fn hashify_errors_on_missing_file() {
        let temp = tempfile::TempDir::new().unwrap();
        let cache = InMemoryCache::new(100, 10_000);
        let mut chunker = Chunker::new(cache, temp.path().to_path_buf());

        let err = chunker
            .hashify("does_not_exist.cook")
            .await
            .expect_err("hashify on missing file should error");
        // `.cook` hits the text branch; File::open failure is wrapped via
        // SyncError::from_io_error into SyncError::IoError { .. }.
        assert!(
            matches!(err, SyncError::IoError { .. }),
            "expected SyncError::IoError for missing file, got {err:?}"
        );
    }

    #[tokio::test]
    async fn save_errors_when_referenced_chunk_is_missing() {
        let temp = tempfile::TempDir::new().unwrap();
        let cache = InMemoryCache::new(100, 10_000);
        let mut chunker = Chunker::new(cache, temp.path().to_path_buf());

        // Reference a hash that was never stored.
        let phantom = "deadbeefdeadbeefdeadbeefdeadbeef";
        let err = chunker
            .save("out.cook", vec![phantom])
            .await
            .expect_err("save should fail when chunk is not available");
        // The missing-chunk branch returns GetFromCacheError from read_chunk().
        assert!(
            matches!(err, SyncError::GetFromCacheError),
            "expected SyncError::GetFromCacheError for unknown chunk, got {err:?}"
        );
    }

    #[tokio::test]
    async fn delete_removes_file_from_storage_dir() {
        let temp = tempfile::TempDir::new().unwrap();
        let cache = InMemoryCache::new(100, 10_000);
        let mut chunker = Chunker::new(cache, temp.path().to_path_buf());

        // Write a file into the storage dir, then delete via Chunker::delete.
        let path = "recipe.cook";
        tokio::fs::write(temp.path().join(path), b"eggs\n")
            .await
            .unwrap();
        assert!(temp.path().join(path).exists(), "precondition: file written");

        chunker
            .delete(path)
            .await
            .expect("Chunker::delete should succeed on existing file");

        assert!(
            !temp.path().join(path).exists(),
            "file should be gone after Chunker::delete"
        );
    }

    #[tokio::test]
    async fn hashify_then_read_chunk_round_trip_via_cache() {
        // Exercises the save_chunk → read_chunk → check_chunk paths together.
        // hashify_text splits a file into line chunks and stores each chunk
        // bytes-for-bytes in the cache keyed by its hash; read_chunk must
        // return those bytes verbatim for any hash hashify produced.
        let temp = tempfile::TempDir::new().unwrap();
        let cache = InMemoryCache::new(100, 10_000);
        let mut chunker = Chunker::new(cache, temp.path().to_path_buf());

        let path = "round.cook";
        let body = b"alpha\nbeta\n"; // two newline-terminated chunks
        tokio::fs::write(temp.path().join(path), body).await.unwrap();

        let hashes = chunker.hashify(path).await.expect("hashify");
        assert_eq!(hashes.len(), 2, "two-line file produces two chunks");

        // Every hash hashify yielded must be resolvable via check_chunk and
        // read_chunk. Concatenating the chunk bytes reconstructs the file.
        let mut recovered = Vec::new();
        for h in &hashes {
            assert!(
                chunker.check_chunk(h),
                "hashify must populate the cache for every hash it returns"
            );
            let bytes = chunker.read_chunk(h).expect("read_chunk on known hash");
            recovered.extend_from_slice(&bytes);
        }
        assert_eq!(recovered, body, "chunks concatenate back to the original bytes");
    }

    #[tokio::test]
    async fn hashify_text_file_with_multiple_lines_produces_multiple_chunks() {
        let temp = tempfile::TempDir::new().unwrap();
        let cache = InMemoryCache::new(1000, 100_000);
        let mut chunker = Chunker::new(cache, temp.path().to_path_buf());

        let content = "line-a\nline-b\nline-c\n";
        tokio::fs::write(temp.path().join("multi.cook"), content.as_bytes())
            .await
            .unwrap();

        let hashes = chunker.hashify("multi.cook").await.unwrap();
        assert_eq!(
            hashes.len(),
            3,
            "three newline-terminated lines should yield three text chunks; got {hashes:?}"
        );
    }

    #[tokio::test]
    async fn delete_removes_empty_parent_directories() {
        // Issue #21: when the syncer deletes the only file inside a
        // nested directory, those now-empty parents must also be removed.
        // Otherwise users see ghost folders accumulate on receiving devices.
        let temp = tempfile::TempDir::new().unwrap();
        let cache = InMemoryCache::new(100, 10_000);
        let mut chunker = Chunker::new(cache, temp.path().to_path_buf());

        let nested_dir = temp.path().join("a").join("b");
        tokio::fs::create_dir_all(&nested_dir).await.unwrap();
        tokio::fs::write(nested_dir.join("c.cook"), b"eggs\n")
            .await
            .unwrap();

        chunker
            .delete("a/b/c.cook")
            .await
            .expect("delete should succeed");

        assert!(
            !temp.path().join("a/b/c.cook").exists(),
            "file should be removed"
        );
        assert!(
            !temp.path().join("a/b").exists(),
            "empty intermediate directory should be removed"
        );
        assert!(
            !temp.path().join("a").exists(),
            "empty grandparent directory should be removed"
        );
        assert!(
            temp.path().exists(),
            "storage root must never be removed"
        );
    }

    #[tokio::test]
    async fn delete_stops_at_first_non_empty_ancestor() {
        // If `a/` still has a sibling file after we delete `a/b/c.cook`,
        // we must remove `a/b/` (now empty) but leave `a/` alone.
        // remove_dir naturally enforces this via ENOTEMPTY; this test
        // pins that behavior so a future refactor can't accidentally
        // implement recursive deletion.
        let temp = tempfile::TempDir::new().unwrap();
        let cache = InMemoryCache::new(100, 10_000);
        let mut chunker = Chunker::new(cache, temp.path().to_path_buf());

        let nested_dir = temp.path().join("a").join("b");
        tokio::fs::create_dir_all(&nested_dir).await.unwrap();
        tokio::fs::write(nested_dir.join("c.cook"), b"eggs\n")
            .await
            .unwrap();
        tokio::fs::write(temp.path().join("a").join("sibling.cook"), b"flour\n")
            .await
            .unwrap();

        chunker
            .delete("a/b/c.cook")
            .await
            .expect("delete should succeed");

        assert!(
            !temp.path().join("a/b/c.cook").exists(),
            "target file should be removed"
        );
        assert!(
            !temp.path().join("a/b").exists(),
            "empty intermediate directory should be removed"
        );
        assert!(
            temp.path().join("a").exists(),
            "non-empty ancestor must be preserved"
        );
        assert!(
            temp.path().join("a/sibling.cook").exists(),
            "sibling file must be preserved"
        );
    }

    #[tokio::test]
    async fn delete_does_not_remove_storage_root() {
        // Even when the very last file in the storage root is deleted,
        // the root itself must survive — otherwise the next download
        // cycle has nowhere to write to, and the indexer would crash
        // walking a missing directory.
        let temp = tempfile::TempDir::new().unwrap();
        let cache = InMemoryCache::new(100, 10_000);
        let mut chunker = Chunker::new(cache, temp.path().to_path_buf());

        tokio::fs::write(temp.path().join("only.cook"), b"sugar\n")
            .await
            .unwrap();

        chunker
            .delete("only.cook")
            .await
            .expect("delete should succeed");

        assert!(
            !temp.path().join("only.cook").exists(),
            "file should be removed"
        );
        assert!(
            temp.path().exists(),
            "storage root must never be removed"
        );
        assert!(
            temp.path().is_dir(),
            "storage root must still be a directory"
        );
    }

    #[tokio::test]
    async fn delete_leaves_sibling_files_in_same_directory() {
        // Deleting `a/x.cook` when `a/y.cook` also exists must leave
        // both `a/` and `a/y.cook` intact. This is the "obvious" case
        // but worth pinning — a naive implementation that always
        // removes the immediate parent would break it.
        let temp = tempfile::TempDir::new().unwrap();
        let cache = InMemoryCache::new(100, 10_000);
        let mut chunker = Chunker::new(cache, temp.path().to_path_buf());

        let dir = temp.path().join("a");
        tokio::fs::create_dir_all(&dir).await.unwrap();
        tokio::fs::write(dir.join("x.cook"), b"salt\n").await.unwrap();
        tokio::fs::write(dir.join("y.cook"), b"pepper\n").await.unwrap();

        chunker
            .delete("a/x.cook")
            .await
            .expect("delete should succeed");

        assert!(
            !temp.path().join("a/x.cook").exists(),
            "target file should be removed"
        );
        assert!(
            temp.path().join("a").exists(),
            "directory with remaining files must be preserved"
        );
        assert!(
            temp.path().join("a/y.cook").exists(),
            "sibling file must be preserved"
        );
    }
}