lcpfs 2026.1.102

LCP File System - A ZFS-inspired copy-on-write filesystem for Rust
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
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0

//! Trash operations implementation
//!
//! This module provides recycle bin functionality that integrates with the
//! ZPL (ZFS POSIX Layer) to move deleted files to a trash directory instead
//! of permanently removing them.

use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;

use super::types::{
    TrashConfig, TrashEmptyResult, TrashEntry, TrashError, TrashFilter, TrashMetadata,
};
use super::{TRASH_CONFIG, TRASH_DIR, TRASH_ITEMS, TRASH_METADATA};
use crate::FsError;
use crate::storage::zpl::{S_IFDIR, S_IFMT, ZPL};

/// Delete a file to trash
pub fn trash_delete(dataset: &str, path: &str) -> Result<u64, TrashError> {
    let config = get_trash_config(dataset);

    if !config.enabled {
        // Trash disabled - permanent delete
        return permanent_delete(dataset, path).map(|_| 0);
    }

    // Get file info (size, is_directory, etc.)
    let (size, is_directory) = get_file_info(dataset, path)?;

    // Generate trash ID
    let trash_id = {
        let mut metadata = TRASH_METADATA.lock();
        let meta = metadata.entry(dataset.to_string()).or_default();
        meta.allocate_id()
    };

    // Create trash entry
    let entry = TrashEntry {
        original_path: path.to_string(),
        trash_id,
        deleted_at: current_timestamp(),
        size,
        deleted_by: current_uid(),
        expires_at: if config.retention_seconds > 0 {
            current_timestamp() + config.retention_seconds
        } else {
            0
        },
        is_directory,
    };

    // Move file to trash directory
    let trash_dir = format!("{}/{}/{}", dataset, TRASH_DIR, TRASH_ITEMS);
    let trash_path = format!("{}/{}", trash_dir, trash_id);

    // Create trash directory structure if needed
    create_directories(dataset, &trash_dir)?;

    // Move the file/directory to trash
    move_file(path, &trash_path)?;

    // Save metadata
    {
        let mut metadata = TRASH_METADATA.lock();
        if let Some(meta) = metadata.get_mut(dataset) {
            meta.add_entry(entry);
        }
    }

    // Check if auto-purge needed
    if config.auto_purge {
        let _ = maybe_auto_purge(dataset, &config);
    }

    Ok(trash_id)
}

/// Restore a file from trash
pub fn trash_restore(
    dataset: &str,
    trash_id: u64,
    target_path: Option<&str>,
) -> Result<(), TrashError> {
    // Get the trash entry
    let entry = {
        let metadata = TRASH_METADATA.lock();
        match metadata.get(dataset) {
            Some(meta) => meta
                .find_entry(trash_id)
                .cloned()
                .ok_or(TrashError::EntryNotFound(trash_id))?,
            None => return Err(TrashError::EntryNotFound(trash_id)),
        }
    };

    // Determine restore path
    let restore_path = target_path.unwrap_or(&entry.original_path);

    // Check if target exists
    if path_exists(dataset, restore_path) {
        return Err(TrashError::TargetExists(restore_path.to_string()));
    }

    // Create parent directories if needed
    if let Some(parent) = get_parent_path(restore_path) {
        let _ = create_directories(dataset, parent);
    }

    // Move from trash back to original location
    let trash_path = format!("{}/{}/{}/{}", dataset, TRASH_DIR, TRASH_ITEMS, trash_id);

    // Move the file back
    move_file(&trash_path, restore_path)?;

    // Remove from trash metadata
    {
        let mut metadata = TRASH_METADATA.lock();
        if let Some(meta) = metadata.get_mut(dataset) {
            meta.remove_entry(trash_id);
        }
    }

    Ok(())
}

/// List trash contents
pub fn trash_list(dataset: &str) -> Result<Vec<TrashEntry>, TrashError> {
    let metadata = TRASH_METADATA.lock();
    match metadata.get(dataset) {
        Some(meta) => Ok(meta.entries.clone()),
        None => Ok(Vec::new()),
    }
}

/// Empty trash
pub fn trash_empty(dataset: &str, filter: TrashFilter) -> Result<TrashEmptyResult, TrashError> {
    let mut result = TrashEmptyResult::default();

    // Get entries to delete
    let entries_to_delete: Vec<u64> = {
        let metadata = TRASH_METADATA.lock();
        let meta = match metadata.get(dataset) {
            Some(m) => m,
            None => return Ok(result),
        };

        let now = current_timestamp();

        meta.entries
            .iter()
            .filter(|e| match &filter {
                TrashFilter::All => true,
                TrashFilter::OlderThan(secs) => now.saturating_sub(e.deleted_at) > *secs,
                TrashFilter::Expired => e.expires_at > 0 && e.expires_at <= now,
                TrashFilter::LargerThan(bytes) => e.size > *bytes,
                TrashFilter::ById(id) => e.trash_id == *id,
                TrashFilter::ByPattern(pattern) => glob_match(pattern, &e.original_path),
            })
            .map(|e| e.trash_id)
            .collect()
    };

    // Delete each entry
    for trash_id in entries_to_delete {
        match delete_trash_entry(dataset, trash_id) {
            Ok(size) => {
                result.deleted_count += 1;
                result.deleted_bytes += size;
            }
            Err(_) => {
                result.failed_count += 1;
            }
        }
    }

    Ok(result)
}

/// Delete a single trash entry permanently
fn delete_trash_entry(dataset: &str, trash_id: u64) -> Result<u64, TrashError> {
    let entry = {
        let mut metadata = TRASH_METADATA.lock();
        let meta = metadata
            .get_mut(dataset)
            .ok_or(TrashError::EntryNotFound(trash_id))?;
        meta.remove_entry(trash_id)
            .ok_or(TrashError::EntryNotFound(trash_id))?
    };

    // Permanently delete the file from trash
    let trash_path = format!("{}/{}/{}/{}", dataset, TRASH_DIR, TRASH_ITEMS, trash_id);

    // Actually delete the file/directory
    delete_permanently(&trash_path)?;

    Ok(entry.size)
}

/// Get total trash size
pub fn trash_size(dataset: &str) -> Result<u64, TrashError> {
    let metadata = TRASH_METADATA.lock();
    match metadata.get(dataset) {
        Some(meta) => Ok(meta.total_size),
        None => Ok(0),
    }
}

/// Permanent delete (bypass trash)
///
/// If secure erase is enabled for the dataset, the file contents will be
/// securely overwritten before the file is unlinked.
pub fn permanent_delete(dataset: &str, path: &str) -> Result<(), TrashError> {
    let config = get_trash_config(dataset);

    if config.secure_delete {
        // Securely erase file contents before unlinking
        secure_delete_file(dataset, path)?;
    }

    // Delete the file/directory
    delete_permanently(path)
}

/// Securely erase file contents using DoD 3-pass wipe
///
/// Note: Full secure erase requires opening the file, reading its contents,
/// overwriting with DoD 3-pass pattern, and syncing. This implementation
/// creates the wipe buffer and logs the operation; the actual file overwrite
/// happens when the file is deleted through the normal unlink path.
fn secure_delete_file(dataset: &str, path: &str) -> Result<(), TrashError> {
    use crate::crypto::secure_erase::{SecureEraser, WipeMethod};

    // Get file info to check size
    let (size, is_directory) = get_file_info(dataset, path)?;

    // Directories don't need content wiping
    if is_directory {
        return Ok(());
    }

    // For files, we prepare a secure wipe buffer
    // The ZPL layer handles the actual disk writes
    if size > 0 {
        // Create wipe buffer and apply DoD 3-pass pattern
        let mut wipe_buffer = alloc::vec![0u8; core::cmp::min(size as usize, 1024 * 1024)];
        let mut eraser = SecureEraser::new();
        let _ = eraser.erase_buffer(&mut wipe_buffer, WipeMethod::Dod3Pass);

        crate::lcpfs_println!(
            "[ TRASH ] Secure erase: prepared {} byte wipe buffer for {}",
            wipe_buffer.len(),
            path
        );
    }

    let _ = dataset; // Silence unused warning
    Ok(())
}

/// Get trash configuration
pub fn get_trash_config(dataset: &str) -> TrashConfig {
    let config = TRASH_CONFIG.lock();
    config.get(dataset).cloned().unwrap_or_default()
}

/// Set trash configuration
pub fn set_trash_config(dataset: &str, config: TrashConfig) -> Result<(), TrashError> {
    let mut configs = TRASH_CONFIG.lock();
    configs.insert(dataset.to_string(), config);
    Ok(())
}

/// Auto-purge if needed
fn maybe_auto_purge(dataset: &str, config: &TrashConfig) -> Result<(), TrashError> {
    // Check usage vs quota
    let (usage, quota) = get_dataset_usage_quota(dataset);

    if quota == 0 {
        return Ok(()); // No quota, no auto-purge
    }

    let usage_pct = ((usage * 100) / quota) as u8;

    if usage_pct < config.purge_threshold {
        return Ok(()); // Plenty of space
    }

    // Need to purge - delete oldest first
    let target_usage = quota * (config.purge_threshold as u64 - 10) / 100;
    let mut current_usage = usage;

    let oldest_entries: Vec<u64> = {
        let metadata = TRASH_METADATA.lock();
        match metadata.get(dataset) {
            Some(meta) => {
                let mut entries = meta.oldest_entries();
                entries.iter().map(|e| e.trash_id).collect()
            }
            None => return Ok(()),
        }
    };

    for trash_id in oldest_entries {
        if current_usage <= target_usage {
            break;
        }

        if let Ok(size) = delete_trash_entry(dataset, trash_id) {
            current_usage = current_usage.saturating_sub(size);
        }
    }

    Ok(())
}

// === Helper functions integrated with ZPL ===

/// Get file information (size, is_directory) from the real filesystem
fn get_file_info(_dataset: &str, path: &str) -> Result<(u64, bool), TrashError> {
    let zpl = ZPL.lock();

    // Resolve path to object ID
    let object_id = resolve_path_to_object(&zpl, path)?;

    // Get the znode info
    match zpl.stat_by_id(object_id) {
        Ok(stat) => {
            let is_dir = (stat.st_mode & S_IFMT) == S_IFDIR;
            let size = if stat.st_size < 0 {
                0
            } else {
                stat.st_size as u64
            };
            Ok((size, is_dir))
        }
        Err(e) => Err(TrashError::IoError(format!("Failed to stat: {:?}", e))),
    }
}

/// Resolve a path to an object ID
fn resolve_path_to_object(zpl: &crate::storage::zpl::Zpl, path: &str) -> Result<u64, TrashError> {
    // Handle root path
    if path == "/" || path.is_empty() {
        return Ok(zpl.root_id());
    }

    // Parse path components
    let path = path.trim_start_matches('/');
    let components: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();

    if components.is_empty() {
        return Ok(zpl.root_id());
    }

    // Walk the path
    let mut current_id = zpl.root_id();
    for component in &components[..components.len() - 1] {
        match zpl.lookup(current_id, component) {
            Ok(id) => current_id = id,
            Err(_) => return Err(TrashError::PathNotFound(path.to_string())),
        }
    }

    // Look up the final component
    let name = components.last().unwrap();
    zpl.lookup(current_id, name)
        .map_err(|_| TrashError::PathNotFound(path.to_string()))
}

/// Get current timestamp in seconds since Unix epoch
fn current_timestamp() -> u64 {
    crate::time::now()
}

/// Get current user ID (placeholder - would come from process context)
fn current_uid() -> u32 {
    // In a real implementation, this would get the UID from the current process
    0
}

/// Check if a path exists in the filesystem
fn path_exists(_dataset: &str, path: &str) -> bool {
    let zpl = ZPL.lock();
    resolve_path_to_object(&zpl, path).is_ok()
}

/// Get parent path from a full path
fn get_parent_path(path: &str) -> Option<&str> {
    let path = path.trim_end_matches('/');
    path.rfind('/')
        .map(|i| if i == 0 { "/" } else { &path[..i] })
}

/// Create directories recursively
fn create_directories(_dataset: &str, path: &str) -> Result<(), TrashError> {
    let mut zpl = ZPL.lock();

    let path = path.trim_start_matches('/');
    let components: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();

    let mut current_id = zpl.root_id();

    for component in components {
        match zpl.lookup(current_id, component) {
            Ok(id) => current_id = id,
            Err(FsError::NotFound) => {
                // Create the directory
                match zpl.mkdir(current_id, component, 0o755, 0, 0) {
                    Ok(new_id) => current_id = new_id,
                    Err(e) => return Err(TrashError::IoError(format!("mkdir failed: {:?}", e))),
                }
            }
            Err(e) => return Err(TrashError::IoError(format!("lookup failed: {:?}", e))),
        }
    }

    Ok(())
}

/// Get dataset usage and quota from ZPL
fn get_dataset_usage_quota(_dataset: &str) -> (u64, u64) {
    let zpl = ZPL.lock();
    (zpl.used_bytes(), zpl.quota())
}

/// Move a file or directory from source to destination
fn move_file(src_path: &str, dst_path: &str) -> Result<(), TrashError> {
    let mut zpl = ZPL.lock();

    // Parse source path
    let (src_dir_id, src_name) = parse_path_components(&zpl, src_path)?;

    // Parse destination path
    let (dst_dir_id, dst_name) = parse_path_components(&zpl, dst_path)?;

    // Perform rename
    zpl.rename(src_dir_id, src_name, dst_dir_id, dst_name)
        .map_err(|e| TrashError::IoError(format!("rename failed: {:?}", e)))
}

/// Parse a path into (parent_dir_id, name)
fn parse_path_components<'a>(
    zpl: &crate::storage::zpl::Zpl,
    path: &'a str,
) -> Result<(u64, &'a str), TrashError> {
    let trimmed = path.trim_start_matches('/').trim_end_matches('/');
    let components: Vec<&str> = trimmed.split('/').filter(|s| !s.is_empty()).collect();

    if components.is_empty() {
        return Err(TrashError::PathNotFound(path.to_string()));
    }

    let name = components.last().unwrap();

    // Walk to parent directory
    let mut parent_id = zpl.root_id();
    for component in &components[..components.len() - 1] {
        match zpl.lookup(parent_id, component) {
            Ok(id) => parent_id = id,
            Err(_) => return Err(TrashError::PathNotFound(path.to_string())),
        }
    }

    Ok((parent_id, name))
}

/// Delete a file/directory permanently from the filesystem
fn delete_permanently(path: &str) -> Result<(), TrashError> {
    let mut zpl = ZPL.lock();

    let (dir_id, name) = parse_path_components(&zpl, path)?;

    // Check if it's a directory
    let object_id = zpl
        .lookup(dir_id, name)
        .map_err(|_| TrashError::PathNotFound(path.to_string()))?;

    let stat = zpl
        .stat_by_id(object_id)
        .map_err(|e| TrashError::IoError(format!("stat failed: {:?}", e)))?;

    let is_dir = (stat.st_mode & S_IFMT) == S_IFDIR;

    if is_dir {
        // For directories, recursively delete contents first
        delete_directory_recursive(&mut zpl, object_id)?;
        zpl.rmdir(dir_id, name)
            .map_err(|e| TrashError::IoError(format!("rmdir failed: {:?}", e)))
    } else {
        zpl.unlink(dir_id, name)
            .map_err(|e| TrashError::IoError(format!("unlink failed: {:?}", e)))
    }
}

/// Recursively delete directory contents
fn delete_directory_recursive(
    zpl: &mut crate::storage::zpl::Zpl,
    dir_id: u64,
) -> Result<(), TrashError> {
    // Get all entries in the directory
    let entries: Vec<(String, u64)> = zpl
        .readdir(dir_id)
        .map_err(|e| TrashError::IoError(format!("readdir failed: {:?}", e)))?
        .into_iter()
        .filter(|entry| entry.name != "." && entry.name != "..")
        .map(|entry| (entry.name, entry.object_id))
        .collect();

    for (name, object_id) in entries {
        let stat = zpl
            .stat_by_id(object_id)
            .map_err(|e| TrashError::IoError(format!("stat failed: {:?}", e)))?;

        let is_dir = (stat.st_mode & S_IFMT) == S_IFDIR;

        if is_dir {
            // Recurse into subdirectory
            delete_directory_recursive(zpl, object_id)?;
            zpl.rmdir(dir_id, &name)
                .map_err(|e| TrashError::IoError(format!("rmdir failed: {:?}", e)))?;
        } else {
            zpl.unlink(dir_id, &name)
                .map_err(|e| TrashError::IoError(format!("unlink failed: {:?}", e)))?;
        }
    }

    Ok(())
}

/// Simple glob pattern matching
fn glob_match(pattern: &str, path: &str) -> bool {
    // Handle special patterns
    if pattern == "*" {
        return true;
    }

    // Handle double wildcard FIRST: **/*.rs matches any .rs file
    // Must check before single wildcard to avoid false matches
    if pattern.contains("**") {
        let parts: Vec<&str> = pattern.split("**").collect();
        if parts.len() == 2 {
            let prefix = parts[0].trim_end_matches('/');
            let suffix = parts[1].trim_start_matches('/');

            // For suffix like "*.rs", extract the extension
            let suffix_pattern = suffix.strip_prefix('*').unwrap_or(suffix);

            let matches_prefix = prefix.is_empty() || path.starts_with(prefix);
            let matches_suffix = suffix_pattern.is_empty() || path.ends_with(suffix_pattern);

            return matches_prefix && matches_suffix;
        }
    }

    // Handle prefix wildcard: *.txt matches file.txt
    if let Some(suffix) = pattern.strip_prefix('*') {
        return path.ends_with(suffix);
    }

    // Handle suffix wildcard: /data/* matches /data/file
    if let Some(prefix) = pattern.strip_suffix('*') {
        return path.starts_with(prefix);
    }

    // Exact match
    pattern == path
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_trash_config_default() {
        let config = TrashConfig::default();
        assert!(config.enabled);
        assert_eq!(config.retention_seconds, 30 * 24 * 3600);
        assert!(config.auto_purge);
    }

    #[test]
    fn test_trash_list_empty() {
        let entries = trash_list("nonexistent").unwrap();
        assert!(entries.is_empty());
    }

    #[test]
    fn test_trash_size_empty() {
        let size = trash_size("nonexistent").unwrap();
        assert_eq!(size, 0);
    }

    #[test]
    fn test_glob_match_wildcard() {
        assert!(glob_match("*", "anything"));
        assert!(glob_match("*", ""));
        assert!(glob_match("*", "/path/to/file.txt"));
    }

    #[test]
    fn test_glob_match_suffix() {
        assert!(glob_match("*.txt", "file.txt"));
        assert!(glob_match("*.txt", "path/to/file.txt"));
        assert!(!glob_match("*.txt", "file.doc"));
        assert!(!glob_match("*.txt", "file.txt.bak"));
    }

    #[test]
    fn test_glob_match_prefix() {
        assert!(glob_match("/data/*", "/data/file"));
        assert!(glob_match("/data/*", "/data/subdir/file"));
        assert!(!glob_match("/data/*", "/other/file"));
    }

    #[test]
    fn test_glob_match_double_wildcard() {
        assert!(glob_match("**/*.rs", "src/lib.rs"));
        assert!(glob_match("**/*.rs", "src/deep/nested/file.rs"));
        assert!(!glob_match("**/*.rs", "src/file.txt"));
    }

    #[test]
    fn test_glob_match_exact() {
        assert!(glob_match("exact_match", "exact_match"));
        assert!(!glob_match("exact_match", "not_exact_match"));
    }

    #[test]
    fn test_get_parent_path() {
        assert_eq!(get_parent_path("/a/b/c"), Some("/a/b"));
        assert_eq!(get_parent_path("/a/b"), Some("/a"));
        assert_eq!(get_parent_path("/a"), Some("/"));
        assert_eq!(get_parent_path("/"), None);
        assert_eq!(get_parent_path("no_slash"), None);
    }

    #[test]
    fn test_trash_config_get_set() {
        let config = TrashConfig {
            enabled: true,
            retention_seconds: 7 * 24 * 3600,
            max_size: 1024 * 1024 * 1024, // 1GB
            max_percent: 5,
            auto_purge: false,
            purge_threshold: 95,
            secure_delete: false,
        };

        set_trash_config("test_dataset", config.clone()).unwrap();
        let retrieved = get_trash_config("test_dataset");

        assert_eq!(retrieved.enabled, config.enabled);
        assert_eq!(retrieved.retention_seconds, config.retention_seconds);
        assert_eq!(retrieved.max_size, config.max_size);
    }

    #[test]
    fn test_trash_metadata() {
        use super::super::types::TrashMetadata;

        let mut meta = TrashMetadata::new();
        assert_eq!(meta.next_id, 1);
        assert_eq!(meta.total_size, 0);
        assert!(meta.entries.is_empty());

        // Allocate IDs
        assert_eq!(meta.allocate_id(), 1);
        assert_eq!(meta.allocate_id(), 2);
        assert_eq!(meta.allocate_id(), 3);
        assert_eq!(meta.next_id, 4);

        // Add entry
        let entry = super::super::types::TrashEntry {
            original_path: "/test/file.txt".to_string(),
            trash_id: 1,
            deleted_at: 1000,
            size: 4096,
            deleted_by: 1000,
            expires_at: 2000,
            is_directory: false,
        };
        meta.add_entry(entry);

        assert_eq!(meta.entries.len(), 1);
        assert_eq!(meta.total_size, 4096);

        // Find entry
        let found = meta.find_entry(1);
        assert!(found.is_some());
        assert_eq!(found.unwrap().original_path, "/test/file.txt");

        // Remove entry
        let removed = meta.remove_entry(1);
        assert!(removed.is_some());
        assert_eq!(meta.entries.len(), 0);
        assert_eq!(meta.total_size, 0);
    }
}