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
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0

//! Restore operations for recovering files from historical state.
//!
//! This module enables restoring files and directories to a previous version
//! by copying data from historical blocks.

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

use super::types::{FileType, TimeError};
use super::walker::{HistoricalEntry, HistoricalTreeProvider, HistoricalTreeWalker, WalkOptions};

// ═══════════════════════════════════════════════════════════════════════════════
// RESTORE TARGET
// ═══════════════════════════════════════════════════════════════════════════════

/// Trait for writing restored data.
///
/// This trait must be implemented by the filesystem to enable writing
/// restored data to the current state.
pub trait RestoreTarget {
    /// Create a file with the given contents.
    fn create_file(&mut self, path: &str, entry: &HistoricalEntry) -> Result<(), TimeError>;

    /// Create a directory.
    fn create_directory(&mut self, path: &str, entry: &HistoricalEntry) -> Result<(), TimeError>;

    /// Create a symlink.
    fn create_symlink(
        &mut self,
        path: &str,
        target: &str,
        entry: &HistoricalEntry,
    ) -> Result<(), TimeError>;

    /// Copy file data from historical block pointers.
    fn copy_data(
        &mut self,
        dest_path: &str,
        source_entry: &HistoricalEntry,
    ) -> Result<u64, TimeError>;

    /// Set file metadata (mode, uid, gid, times).
    fn set_metadata(&mut self, path: &str, entry: &HistoricalEntry) -> Result<(), TimeError>;

    /// Check if a path exists.
    fn exists(&self, path: &str) -> bool;

    /// Remove a path (file or directory).
    fn remove(&mut self, path: &str) -> Result<(), TimeError>;
}

// ═══════════════════════════════════════════════════════════════════════════════
// RESTORE OPTIONS
// ═══════════════════════════════════════════════════════════════════════════════

/// Options for restore operations.
#[derive(Debug, Clone)]
pub struct RestoreOptions {
    /// Overwrite existing files.
    pub overwrite: bool,
    /// Preserve file metadata (mode, times, owner).
    pub preserve_metadata: bool,
    /// Restore recursively (for directories).
    pub recursive: bool,
    /// Maximum depth for recursive restore (-1 for unlimited).
    pub max_depth: i32,
    /// Dry run - don't actually write anything.
    pub dry_run: bool,
    /// Verify restored data matches checksum.
    pub verify: bool,
}

impl Default for RestoreOptions {
    fn default() -> Self {
        Self {
            overwrite: false,
            preserve_metadata: true,
            recursive: true,
            max_depth: -1,
            dry_run: false,
            verify: true,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// RESTORE RESULT
// ═══════════════════════════════════════════════════════════════════════════════

/// Result of a restore operation.
#[derive(Debug, Clone)]
pub struct RestoreResult {
    /// Path that was restored.
    pub path: String,
    /// Destination path.
    pub dest_path: String,
    /// Source TXG.
    pub txg: u64,
    /// Number of files restored.
    pub files_restored: usize,
    /// Number of directories restored.
    pub dirs_restored: usize,
    /// Total bytes restored.
    pub bytes_restored: u64,
    /// Files that were skipped (already exist).
    pub skipped: Vec<String>,
    /// Errors encountered.
    pub errors: Vec<(String, String)>,
    /// Was this a dry run?
    pub dry_run: bool,
}

impl RestoreResult {
    /// Create a new empty result.
    pub fn new(path: &str, dest_path: &str, txg: u64, dry_run: bool) -> Self {
        Self {
            path: path.into(),
            dest_path: dest_path.into(),
            txg,
            files_restored: 0,
            dirs_restored: 0,
            bytes_restored: 0,
            skipped: Vec::new(),
            errors: Vec::new(),
            dry_run,
        }
    }

    /// Check if restore was completely successful.
    pub fn is_success(&self) -> bool {
        self.errors.is_empty()
    }

    /// Total items restored.
    pub fn total_restored(&self) -> usize {
        self.files_restored + self.dirs_restored
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// RESTORE ENGINE
// ═══════════════════════════════════════════════════════════════════════════════

/// Engine for restoring files from historical state.
pub struct RestoreEngine<'a, P: HistoricalTreeProvider, T: RestoreTarget> {
    provider: &'a P,
    target: &'a mut T,
}

impl<'a, P: HistoricalTreeProvider, T: RestoreTarget> RestoreEngine<'a, P, T> {
    /// Create a new restore engine.
    pub fn new(provider: &'a P, target: &'a mut T) -> Self {
        Self { provider, target }
    }

    /// Restore a file or directory from a specific TXG.
    pub fn restore(
        &mut self,
        path: &str,
        dest_path: Option<&str>,
        txg: u64,
        options: &RestoreOptions,
    ) -> Result<RestoreResult, TimeError> {
        let walker = HistoricalTreeWalker::new(self.provider, txg);

        // Check if source exists at TXG
        if !walker.exists(path) {
            return Err(TimeError::PathNotFound(path.into()));
        }

        let source = walker.lookup(path)?;
        let dest = dest_path.unwrap_or(path);

        let mut result = RestoreResult::new(path, dest, txg, options.dry_run);

        // Handle based on type
        if source.is_dir() {
            self.restore_directory(&walker, &source, dest, options, &mut result)?;
        } else {
            self.restore_file(&walker, &source, dest, options, &mut result)?;
        }

        Ok(result)
    }

    /// Restore a single file.
    fn restore_file(
        &mut self,
        _walker: &HistoricalTreeWalker<P>,
        entry: &HistoricalEntry,
        dest_path: &str,
        options: &RestoreOptions,
        result: &mut RestoreResult,
    ) -> Result<(), TimeError> {
        // Check if destination exists
        if self.target.exists(dest_path) {
            if !options.overwrite {
                result.skipped.push(dest_path.into());
                return Ok(());
            }
            if !options.dry_run {
                self.target.remove(dest_path)?;
            }
        }

        if options.dry_run {
            // Count dirs as dirs, not files
            if entry.is_dir() {
                result.dirs_restored += 1;
            } else {
                result.files_restored += 1;
                result.bytes_restored += entry.size;
            }
            return Ok(());
        }

        // Handle by file type
        match entry.file_type {
            FileType::Regular => {
                // Create file and copy data
                self.target.create_file(dest_path, entry)?;
                let bytes = self.target.copy_data(dest_path, entry)?;
                result.bytes_restored += bytes;
            }
            FileType::Symlink => {
                // Read link target and create symlink
                let target = self.provider.readlink_at_txg(&entry.path, entry.txg)?;
                self.target.create_symlink(dest_path, &target, entry)?;
            }
            FileType::Directory => {
                self.target.create_directory(dest_path, entry)?;
                result.dirs_restored += 1;
                return Ok(()); // Don't count as file
            }
            _ => {
                // Skip special files
                result.skipped.push(dest_path.into());
                return Ok(());
            }
        }

        // Set metadata if requested
        if options.preserve_metadata {
            if let Err(e) = self.target.set_metadata(dest_path, entry) {
                result
                    .errors
                    .push((dest_path.into(), alloc::format!("{}", e)));
            }
        }

        result.files_restored += 1;
        Ok(())
    }

    /// Restore a directory recursively.
    fn restore_directory(
        &mut self,
        walker: &HistoricalTreeWalker<P>,
        entry: &HistoricalEntry,
        dest_path: &str,
        options: &RestoreOptions,
        result: &mut RestoreResult,
    ) -> Result<(), TimeError> {
        // Create destination directory
        if !options.dry_run && !self.target.exists(dest_path) {
            self.target.create_directory(dest_path, entry)?;
        }
        result.dirs_restored += 1;

        if !options.recursive {
            return Ok(());
        }

        // Walk directory tree
        let walk_options = WalkOptions {
            max_depth: options.max_depth,
            ..Default::default()
        };

        let entries = walker.walk(&entry.path, &walk_options)?;

        for child in entries {
            // Compute destination path
            let relative = if child.path.starts_with(&entry.path) {
                &child.path[entry.path.len()..]
            } else {
                &child.path
            };
            let child_dest = if dest_path.ends_with('/') {
                alloc::format!("{}{}", dest_path, relative.trim_start_matches('/'))
            } else {
                alloc::format!("{}{}", dest_path, relative)
            };

            // Restore this entry
            match self.restore_file(walker, &child, &child_dest, options, result) {
                Ok(()) => {}
                Err(e) => {
                    result.errors.push((child_dest, alloc::format!("{}", e)));
                }
            }
        }

        // Set directory metadata
        if options.preserve_metadata && !options.dry_run {
            if let Err(e) = self.target.set_metadata(dest_path, entry) {
                result
                    .errors
                    .push((dest_path.into(), alloc::format!("{}", e)));
            }
        }

        Ok(())
    }

    /// Preview what would be restored (dry run).
    pub fn preview(
        &mut self,
        path: &str,
        dest_path: Option<&str>,
        txg: u64,
    ) -> Result<RestoreResult, TimeError> {
        let options = RestoreOptions {
            dry_run: true,
            ..Default::default()
        };
        self.restore(path, dest_path, txg, &options)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// IN-MEMORY RESTORE TARGET (FOR TESTING)
// ═══════════════════════════════════════════════════════════════════════════════

/// In-memory restore target for testing.
#[derive(Debug, Default)]
pub struct InMemoryRestoreTarget {
    /// Files that have been "created".
    pub files: Vec<(String, HistoricalEntry)>,
    /// Directories that have been "created".
    pub directories: Vec<String>,
    /// Symlinks that have been "created".
    pub symlinks: Vec<(String, String)>,
    /// Removed paths.
    pub removed: Vec<String>,
}

impl InMemoryRestoreTarget {
    /// Create a new target.
    pub fn new() -> Self {
        Self::default()
    }

    /// Check how many files were restored.
    pub fn file_count(&self) -> usize {
        self.files.len()
    }
}

impl RestoreTarget for InMemoryRestoreTarget {
    fn create_file(&mut self, path: &str, entry: &HistoricalEntry) -> Result<(), TimeError> {
        self.files.push((path.into(), entry.clone()));
        Ok(())
    }

    fn create_directory(&mut self, path: &str, _entry: &HistoricalEntry) -> Result<(), TimeError> {
        if !self.directories.contains(&path.to_string()) {
            self.directories.push(path.into());
        }
        Ok(())
    }

    fn create_symlink(
        &mut self,
        path: &str,
        target: &str,
        _entry: &HistoricalEntry,
    ) -> Result<(), TimeError> {
        self.symlinks.push((path.into(), target.into()));
        Ok(())
    }

    fn copy_data(
        &mut self,
        _dest_path: &str,
        source_entry: &HistoricalEntry,
    ) -> Result<u64, TimeError> {
        // Simulate copying data
        Ok(source_entry.size)
    }

    fn set_metadata(&mut self, _path: &str, _entry: &HistoricalEntry) -> Result<(), TimeError> {
        // Simulate setting metadata
        Ok(())
    }

    fn exists(&self, path: &str) -> bool {
        self.files.iter().any(|(p, _)| p == path) || self.directories.contains(&path.to_string())
    }

    fn remove(&mut self, path: &str) -> Result<(), TimeError> {
        self.removed.push(path.into());
        self.files.retain(|(p, _)| p != path);
        self.directories.retain(|p| p != path);
        Ok(())
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TESTS
// ═══════════════════════════════════════════════════════════════════════════════

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

    fn create_entry(
        path: &str,
        name: &str,
        file_type: FileType,
        size: u64,
        txg: u64,
    ) -> HistoricalEntry {
        HistoricalEntry {
            name: name.into(),
            path: path.into(),
            object_id: path.len() as u64,
            parent_id: 1,
            file_type,
            size,
            mode: 0o644,
            uid: 1000,
            gid: 1000,
            atime: txg * 1000,
            mtime: txg * 1000,
            ctime: txg * 1000,
            txg,
            checksum: [txg; 4],
            nlinks: 1,
            blocks: size.div_ceil(512),
            generation: txg,
        }
    }

    fn create_test_provider() -> InMemoryTreeProvider {
        let mut provider = InMemoryTreeProvider::new();

        // Add directory structure at TXG 100
        provider.add_entry(100, create_entry("/", "", FileType::Directory, 0, 100));
        provider.add_entry(
            100,
            create_entry("/data", "data", FileType::Directory, 0, 100),
        );
        provider.add_entry(
            100,
            create_entry("/data/file1.txt", "file1.txt", FileType::Regular, 100, 100),
        );
        provider.add_entry(
            100,
            create_entry("/data/file2.txt", "file2.txt", FileType::Regular, 200, 100),
        );
        provider.add_entry(
            100,
            create_entry("/data/subdir", "subdir", FileType::Directory, 0, 100),
        );
        provider.add_entry(
            100,
            create_entry(
                "/data/subdir/nested.txt",
                "nested.txt",
                FileType::Regular,
                50,
                100,
            ),
        );

        provider
    }

    #[test]
    fn test_restore_single_file() {
        let provider = create_test_provider();
        let mut target = InMemoryRestoreTarget::new();

        {
            let mut engine = RestoreEngine::new(&provider, &mut target);
            let result = engine
                .restore("/data/file1.txt", None, 100, &RestoreOptions::default())
                .unwrap();

            assert!(result.is_success());
            assert_eq!(result.files_restored, 1);
            assert_eq!(result.bytes_restored, 100);
        }

        assert_eq!(target.file_count(), 1);
    }

    #[test]
    fn test_restore_to_different_path() {
        let provider = create_test_provider();
        let mut target = InMemoryRestoreTarget::new();

        {
            let mut engine = RestoreEngine::new(&provider, &mut target);
            let result = engine
                .restore(
                    "/data/file1.txt",
                    Some("/backup/file1.txt"),
                    100,
                    &RestoreOptions::default(),
                )
                .unwrap();

            assert_eq!(result.dest_path, "/backup/file1.txt");
        }

        assert!(target.files.iter().any(|(p, _)| p == "/backup/file1.txt"));
    }

    #[test]
    fn test_restore_directory() {
        let provider = create_test_provider();
        let mut target = InMemoryRestoreTarget::new();

        {
            let mut engine = RestoreEngine::new(&provider, &mut target);
            let result = engine
                .restore("/data", None, 100, &RestoreOptions::default())
                .unwrap();

            assert!(result.is_success());
            assert_eq!(result.files_restored, 3); // file1.txt, file2.txt, nested.txt
            assert!(result.dirs_restored >= 1);
        }
    }

    #[test]
    fn test_restore_dry_run() {
        let provider = create_test_provider();
        let mut target = InMemoryRestoreTarget::new();

        {
            let mut engine = RestoreEngine::new(&provider, &mut target);
            let result = engine.preview("/data", None, 100).unwrap();

            assert!(result.dry_run);
            assert_eq!(result.files_restored, 3);
        }

        // Nothing should actually be created
        assert_eq!(target.file_count(), 0);
    }

    #[test]
    fn test_restore_skip_existing() {
        let provider = create_test_provider();
        let mut target = InMemoryRestoreTarget::new();

        // Pre-create a file
        target.files.push((
            "/data/file1.txt".into(),
            create_entry("/data/file1.txt", "file1.txt", FileType::Regular, 50, 50),
        ));

        {
            let mut engine = RestoreEngine::new(&provider, &mut target);
            let options = RestoreOptions {
                overwrite: false,
                ..Default::default()
            };
            let result = engine
                .restore("/data/file1.txt", None, 100, &options)
                .unwrap();

            assert_eq!(result.skipped.len(), 1);
            assert_eq!(result.files_restored, 0);
        }
    }

    #[test]
    fn test_restore_overwrite() {
        let provider = create_test_provider();
        let mut target = InMemoryRestoreTarget::new();

        // Pre-create a file
        target.files.push((
            "/data/file1.txt".into(),
            create_entry("/data/file1.txt", "file1.txt", FileType::Regular, 50, 50),
        ));

        {
            let mut engine = RestoreEngine::new(&provider, &mut target);
            let options = RestoreOptions {
                overwrite: true,
                ..Default::default()
            };
            let result = engine
                .restore("/data/file1.txt", None, 100, &options)
                .unwrap();

            assert!(result.skipped.is_empty());
            assert_eq!(result.files_restored, 1);
        }

        // Old file should be removed, new one added
        assert!(target.removed.contains(&"/data/file1.txt".to_string()));
    }

    #[test]
    fn test_restore_not_found() {
        let provider = create_test_provider();
        let mut target = InMemoryRestoreTarget::new();

        let mut engine = RestoreEngine::new(&provider, &mut target);
        let result = engine.restore("/nonexistent", None, 100, &RestoreOptions::default());

        assert!(matches!(result, Err(TimeError::PathNotFound(_))));
    }

    #[test]
    fn test_restore_non_recursive() {
        let provider = create_test_provider();
        let mut target = InMemoryRestoreTarget::new();

        {
            let mut engine = RestoreEngine::new(&provider, &mut target);
            let options = RestoreOptions {
                recursive: false,
                ..Default::default()
            };
            let result = engine.restore("/data", None, 100, &options).unwrap();

            // Should only create the directory, not its contents
            assert_eq!(result.dirs_restored, 1);
            assert_eq!(result.files_restored, 0);
        }
    }

    #[test]
    fn test_restore_result_totals() {
        let mut result = RestoreResult::new("/data", "/data", 100, false);
        result.files_restored = 5;
        result.dirs_restored = 2;

        assert_eq!(result.total_restored(), 7);
        assert!(result.is_success());

        result.errors.push(("path".into(), "error".into()));
        assert!(!result.is_success());
    }
}