Skip to main content

git2db/storage/
reflink.rs

1//! Reflink driver (cross-platform CoW)
2//!
3//! Implements the reflink storage driver using filesystem reflinks,
4//! providing space-efficient worktrees through copy-on-write semantics.
5//!
6//! Supports:
7//! - Linux: XFS, Btrfs, bcachefs
8//! - macOS: APFS
9//! - Windows: ReFS, Dev Drive
10
11use super::driver::{Driver, DriverFactory, DriverOpts, WorktreeHandle};
12use crate::errors::{Git2DBError, Git2DBResult};
13use async_trait::async_trait;
14use std::path::Path;
15use tracing::{debug, info};
16
17#[cfg(feature = "reflink")]
18use reflink_copy::reflink;
19
20#[cfg(feature = "reflink")]
21inventory::submit!(DriverFactory::new("reflink", || Box::new(
22    ReflinkDriver::new()
23)));
24
25/// Reflink storage driver with cross-platform CoW support
26///
27/// This driver creates git worktrees and then replaces working files
28/// with reflinks from the base repository, providing space savings
29/// through copy-on-write semantics.
30///
31/// Unlike overlay2, this driver has no special cleanup requirements -
32/// worktrees can be removed with a simple `rm -rf`.
33pub struct ReflinkDriver {
34    /// Cached availability check result
35    available: bool,
36}
37
38impl ReflinkDriver {
39    fn new() -> Self {
40        Self {
41            available: Self::check_availability(),
42        }
43    }
44
45    /// Check if reflinks are supported on the system
46    ///
47    /// Performs an actual reflink test in the temp directory to verify support.
48    fn check_availability() -> bool {
49        #[cfg(feature = "reflink")]
50        {
51            let temp_dir = std::env::temp_dir();
52
53            // Use predictable names for temp files (no sensitive data)
54            let test_src = temp_dir.join(".git2db_reflink_test_src");
55            let test_dst = temp_dir.join(".git2db_reflink_test_dst");
56
57            // Clean up any leftover test files
58            let _ = std::fs::remove_file(&test_src);
59            let _ = std::fs::remove_file(&test_dst);
60
61            // Create simple test file (no sensitive data)
62            if std::fs::write(&test_src, "reflink_test").is_err() {
63                return false;
64            }
65
66            // Try strict reflink (not reflink_or_copy)
67            let result = reflink(&test_src, &test_dst).is_ok();
68
69            // Cleanup
70            let _ = std::fs::remove_file(&test_src);
71            let _ = std::fs::remove_file(&test_dst);
72
73            if result {
74                info!("Reflink support detected in temp directory");
75            } else {
76                debug!("Reflink not available on temp filesystem");
77            }
78
79            result
80        }
81
82        #[cfg(not(feature = "reflink"))]
83        false
84    }
85}
86
87impl Default for ReflinkDriver {
88    fn default() -> Self {
89        Self::new()
90    }
91}
92
93#[async_trait]
94impl Driver for ReflinkDriver {
95    fn name(&self) -> &'static str {
96        "reflink"
97    }
98
99    fn is_available(&self) -> bool {
100        #[cfg(feature = "reflink")]
101        {
102            self.available
103        }
104
105        #[cfg(not(feature = "reflink"))]
106        false
107    }
108
109    #[cfg(feature = "reflink")]
110    async fn create_worktree(&self, opts: &DriverOpts) -> Git2DBResult<WorktreeHandle> {
111        // Strict: worktree path must not exist
112        if opts.worktree_path.exists() {
113            return Err(Git2DBError::worktree_exists(&opts.worktree_path));
114        }
115
116        // Validate inputs
117        if !opts.base_repo.exists() {
118            return Err(Git2DBError::invalid_path(
119                opts.base_repo.clone(),
120                "Base repository does not exist",
121            ));
122        }
123
124        info!(
125            "Creating reflink worktree: base={}, path={}, ref={}",
126            opts.base_repo.display(),
127            opts.worktree_path.display(),
128            opts.ref_spec
129        );
130
131        let worktree_path = opts.worktree_path.clone();
132
133        // Step 1: Create git worktree with rollback
134        match self
135            .create_git_worktree(&opts.base_repo, &worktree_path, &opts.ref_spec)
136            .await
137        {
138            Ok(_) => {
139                // Step 2: Replace working files with reflinks from base
140                match self
141                    .reflink_working_files(&opts.base_repo, &worktree_path)
142                    .await
143                {
144                    Ok(_) => {
145                        info!(
146                            "Successfully created reflink worktree at {}",
147                            worktree_path.display()
148                        );
149
150                        // Return handle (no special cleanup needed - just rm like vfs)
151                        Ok(WorktreeHandle::new(worktree_path, "reflink".to_owned()))
152                    }
153                    Err(e) => {
154                        // SECURITY: Clean up partially created worktree on reflink failure
155                        let _ = tokio::fs::remove_dir_all(&worktree_path).await;
156                        info!("Cleaned up partially created worktree due to reflink failure");
157                        Err(e)
158                    }
159                }
160            }
161            Err(e) => {
162                // Worktree creation failed, no cleanup needed as directory was never created
163                Err(e)
164            }
165        }
166    }
167
168    #[cfg(not(feature = "reflink"))]
169    async fn create_worktree(&self, _opts: &DriverOpts) -> Git2DBResult<WorktreeHandle> {
170        Err(Git2DBError::internal(
171            "reflink driver requires 'reflink' feature to be enabled",
172        ))
173    }
174
175    async fn get_worktrees(&self, base_repo: &Path) -> Git2DBResult<Vec<WorktreeHandle>> {
176        let worktrees_dir = base_repo
177            .parent()
178            .ok_or_else(|| {
179                Git2DBError::invalid_path(base_repo.to_path_buf(), "Invalid base repository path")
180            })?
181            .join("worktrees");
182
183        let mut worktrees = Vec::new();
184
185        if !worktrees_dir.exists() {
186            return Ok(worktrees);
187        }
188
189        // Read worktrees directory
190        for entry in std::fs::read_dir(&worktrees_dir)? {
191            let entry = entry?;
192            let worktree_path = entry.path();
193
194            // Skip non-directories and git's internal directories
195            if !worktree_path.is_dir()
196                || worktree_path
197                    .file_name()
198                    .is_some_and(|name| name.to_string_lossy().starts_with(".git"))
199            {
200                continue;
201            }
202
203            // For Reflink driver, any directory with a .git inside is a valid worktree
204            if worktree_path.join(".git").exists() {
205                worktrees.push(WorktreeHandle::new(worktree_path, "reflink".to_owned()));
206            }
207        }
208
209        Ok(worktrees)
210    }
211
212    async fn get_worktree(
213        &self,
214        base_repo: &Path,
215        branch: &str,
216    ) -> Git2DBResult<Option<WorktreeHandle>> {
217        let worktrees_dir = base_repo
218            .parent()
219            .ok_or_else(|| {
220                Git2DBError::invalid_path(base_repo.to_path_buf(), "Invalid base repository path")
221            })?
222            .join("worktrees");
223        let worktree_path = hyprstream_containedfs::contained_join(&worktrees_dir, branch)
224            .map_err(|e| {
225                Git2DBError::invalid_path(worktrees_dir, format!("Path containment: {e}"))
226            })?;
227
228        if worktree_path.exists() && worktree_path.join(".git").exists() {
229            Ok(Some(WorktreeHandle::new(
230                worktree_path,
231                "reflink".to_owned(),
232            )))
233        } else {
234            Ok(None)
235        }
236    }
237}
238
239#[cfg(feature = "reflink")]
240impl ReflinkDriver {
241    /// Create git worktree using libgit2
242    async fn create_git_worktree(
243        &self,
244        base_repo: &Path,
245        worktree_path: &Path,
246        ref_spec: &str,
247    ) -> Git2DBResult<()> {
248        // Ensure parent directory exists
249        if let Some(parent) = worktree_path.parent() {
250            tokio::fs::create_dir_all(parent).await.map_err(|e| {
251                Git2DBError::internal(format!("Failed to create parent directory: {e}"))
252            })?;
253        }
254
255        // Open the base repository
256        let repo = git2::Repository::open(base_repo)
257            .map_err(|e| Git2DBError::internal(format!("Failed to open repository: {e}")))?;
258
259        // Resolve ref_spec to a commit
260        let object = repo.revparse_single(ref_spec).map_err(|e| {
261            Git2DBError::internal(format!("Failed to resolve ref '{ref_spec}': {e}"))
262        })?;
263
264        let commit = object.peel_to_commit().map_err(|e| {
265            Git2DBError::internal(format!("Ref '{ref_spec}' does not point to a commit: {e}"))
266        })?;
267
268        // Check if this is a branch
269        let branch_ref_name = format!("refs/heads/{ref_spec}");
270        let is_branch = repo.find_reference(&branch_ref_name).is_ok();
271
272        // Create worktree name
273        let worktree_name = worktree_path
274            .file_name()
275            .and_then(|n| n.to_str())
276            .ok_or_else(|| {
277                Git2DBError::invalid_path(worktree_path.to_path_buf(), "Invalid worktree path")
278            })?;
279
280        // Create worktree
281        if is_branch {
282            let reference = repo.find_reference(&branch_ref_name)?;
283            repo.worktree(
284                worktree_name,
285                worktree_path,
286                Some(git2::WorktreeAddOptions::new().reference(Some(&reference))),
287            )
288            .map_err(|e| Git2DBError::internal(format!("Failed to create worktree: {e}")))?;
289
290            info!(
291                "Created git worktree at {} for branch '{}' (commit: {})",
292                worktree_path.display(),
293                ref_spec,
294                commit.id()
295            );
296        } else {
297            repo.worktree(worktree_name, worktree_path, None)
298                .map_err(|e| Git2DBError::internal(format!("Failed to create worktree: {e}")))?;
299
300            let wt_repo = git2::Repository::open(worktree_path)?;
301            wt_repo
302                .set_head_detached(commit.id())
303                .map_err(|e| Git2DBError::internal(format!("Failed to set detached HEAD: {e}")))?;
304
305            wt_repo
306                .checkout_head(Some(git2::build::CheckoutBuilder::default().force()))
307                .map_err(|e| Git2DBError::internal(format!("Failed to checkout HEAD: {e}")))?;
308
309            info!(
310                "Created git worktree at {} for ref '{}' (detached HEAD at {})",
311                worktree_path.display(),
312                ref_spec,
313                commit.id()
314            );
315        }
316
317        Ok(())
318    }
319
320    /// Replace working files with reflinks from base repository
321    ///
322    /// This walks the worktree and replaces each file with a reflink
323    /// from the corresponding file in the base repository.
324    async fn reflink_working_files(
325        &self,
326        base_repo: &Path,
327        worktree_path: &Path,
328    ) -> Git2DBResult<()> {
329        use tokio::task::spawn_blocking;
330
331        // SECURITY: Check if tokio runtime is available before spawning blocking task
332        if tokio::runtime::Handle::try_current().is_err() {
333            return Err(Git2DBError::internal(
334                "Cannot spawn blocking task - tokio runtime not available (possibly shutting down)",
335            ));
336        }
337
338        let base = base_repo.to_path_buf();
339        let worktree = worktree_path.to_path_buf();
340
341        spawn_blocking(move || Self::reflink_directory(&base, &worktree))
342            .await
343            .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))?
344    }
345
346    /// Recursively reflink files in directory
347    fn reflink_directory(base: &Path, target: &Path) -> Git2DBResult<()> {
348        let mut reflinked_count = 0u64;
349        let mut reflinked_bytes = 0u64;
350        let mut skipped_count = 0u64;
351
352        for entry in walkdir::WalkDir::new(target)
353            .into_iter()
354            .filter_entry(|e| e.file_name() != ".git")
355        {
356            let entry = entry
357                .map_err(|e| Git2DBError::internal(format!("Failed to walk directory: {e}")))?;
358
359            if !entry.file_type().is_file() {
360                continue;
361            }
362
363            let rel_path = entry
364                .path()
365                .strip_prefix(target)
366                .map_err(|e| Git2DBError::internal(format!("Failed to get relative path: {e}")))?;
367
368            // Prevent path traversal
369            if rel_path.components().any(|c| c.as_os_str() == "..") {
370                return Err(Git2DBError::invalid_path(
371                    entry.path().to_path_buf(),
372                    "Path traversal attempt detected",
373                ));
374            }
375
376            let base_file = base.join(rel_path);
377            let target_file = entry.path();
378
379            if !base_file.exists() {
380                skipped_count += 1;
381                continue;
382            }
383
384            let file_size = std::fs::metadata(&base_file).map(|m| m.len()).unwrap_or(0);
385
386            std::fs::remove_file(target_file).map_err(|e| {
387                Git2DBError::internal(format!("Failed to remove {}: {}", target_file.display(), e))
388            })?;
389
390            reflink(&base_file, target_file).map_err(|e| {
391                Git2DBError::internal(format!(
392                    "Reflink failed {} -> {}: {}",
393                    base_file.display(),
394                    target_file.display(),
395                    e
396                ))
397            })?;
398
399            reflinked_count += 1;
400            reflinked_bytes += file_size;
401        }
402
403        info!(
404            "Reflink complete: {} files ({} bytes), {} skipped",
405            reflinked_count, reflinked_bytes, skipped_count
406        );
407
408        Ok(())
409    }
410}
411
412#[cfg(test)]
413mod tests {
414    use super::*;
415
416    #[test]
417    fn test_driver_name() {
418        let driver = ReflinkDriver::new();
419        assert_eq!(driver.name(), "reflink");
420    }
421}