Skip to main content

capsule_library/library/
space.rs

1//! Free-space probe + streaming-import recommendation — the storage-constrained-import
2//! seam (SSoT:
3//! [Import — Pipeline](https://docs/design/import/pipeline/)).
4//!
5//! The probe is I/O and runs *outside* the pure planner: it is attached at plan
6//! confirmation, so the planner stays deterministic. The recommendation predicate below
7//! is pure and is the contract the executor's streaming drive mode keys off. The
8//! `total_size` accounting and the plan-level `streaming_recommended` attachment live on
9//! [`ImportActionPlan`](crate::import::ImportActionPlan); this module owns the
10//! probe and the two pure verdicts (`streaming_recommended`, `largest_asset_fits`) they
11//! feed.
12
13use std::path::Path;
14
15use super::error::LibraryError;
16
17/// The library volume's available bytes — a thin `statvfs` / `GetDiskFreeSpaceEx`
18/// wrapper over the filesystem holding `library_root`.
19///
20/// Reports the space available **to an unprivileged process** (POSIX `f_bavail`, not the
21/// root-reserved `f_bfree`), so the number matches what an import can actually write. On
22/// Unix it is `f_bavail × f_frsize`; on Windows it is `GetDiskFreeSpaceExW`'s
23/// free-bytes-available-to-caller. Any other target is a compile-time error rather than a
24/// silent wrong answer.
25#[tracing::instrument(level = "debug", skip_all, fields(root = %library_root.display()))]
26pub fn available_bytes(library_root: &Path) -> Result<u64, LibraryError> {
27    let bytes = platform::available_bytes(library_root)?;
28    tracing::debug!(available_bytes = bytes, "library free-space probe");
29    Ok(bytes)
30}
31
32#[cfg(unix)]
33mod platform {
34    use std::path::Path;
35
36    use super::LibraryError;
37
38    /// `statvfs(2)`: blocks available to an unprivileged caller × the fragment size.
39    pub(super) fn available_bytes(library_root: &Path) -> Result<u64, LibraryError> {
40        let stat = rustix::fs::statvfs(library_root).map_err(std::io::Error::from)?;
41        Ok(stat.f_bavail.saturating_mul(stat.f_frsize))
42    }
43}
44
45#[cfg(windows)]
46mod platform {
47    use std::os::windows::ffi::OsStrExt;
48    use std::path::Path;
49
50    use windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW;
51
52    use super::LibraryError;
53
54    /// `GetDiskFreeSpaceExW`: bytes available to the calling user on the volume holding
55    /// `library_root`.
56    pub(super) fn available_bytes(library_root: &Path) -> Result<u64, LibraryError> {
57        // A NUL-terminated wide string for the Win32 boundary.
58        let mut wide: Vec<u16> = library_root.as_os_str().encode_wide().collect();
59        wide.push(0);
60        let mut free_to_caller: u64 = 0;
61        // SAFETY: `wide` is a valid NUL-terminated UTF-16 buffer; `free_to_caller` is a live
62        // local out-pointer; the other two out-params are optional and passed null.
63        let ok = unsafe {
64            GetDiskFreeSpaceExW(
65                wide.as_ptr(),
66                &mut free_to_caller,
67                std::ptr::null_mut(),
68                std::ptr::null_mut(),
69            )
70        };
71        if ok == 0 {
72            return Err(LibraryError::Io(std::io::Error::last_os_error()));
73        }
74        Ok(free_to_caller)
75    }
76}
77
78#[cfg(not(any(unix, windows)))]
79mod platform {
80    use std::path::Path;
81
82    use super::LibraryError;
83
84    pub(super) fn available_bytes(_library_root: &Path) -> Result<u64, LibraryError> {
85        compile_error!("available_bytes: no free-space probe for this target");
86    }
87}
88
89/// The pure streaming-recommendation predicate: streaming mode is recommended when the
90/// plan's total size, plus a configurable headroom margin, meets or exceeds the volume's
91/// available bytes. Attached to the plan at confirmation (never computed inside the pure
92/// planner).
93pub fn streaming_recommended(total_size: u64, available: u64, headroom_margin: u64) -> bool {
94    total_size.saturating_add(headroom_margin) >= available
95}
96
97/// The pure minimum-headroom verdict for a *streaming* import: streaming bounds peak disk to
98/// the in-flight window, but a single asset must still fully materialize locally (original +
99/// derivatives + metadata) before its upload and release, so the **largest single asset** in
100/// the plan must fit within available space minus the headroom margin. When even one asset
101/// cannot fit, streaming cannot proceed and the plan surfaces a hard error rather than stall
102/// mid-stream — streaming cannot make a single file smaller than the disk.
103pub fn largest_asset_fits(largest_asset: u64, available: u64, headroom_margin: u64) -> bool {
104    largest_asset.saturating_add(headroom_margin) <= available
105}
106
107#[cfg(test)]
108mod tests;