diff --git a/AGENTS.md b/AGENTS.md index 4b6ae25..aa00795 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -119,9 +119,11 @@ and `cargo build --release` directly; CI runs the gate on both systems. 10. **Discovery is not a scan.** Local launch scans `$HOME` directly, while bare `disktree ssh HOST` and the location dialog list mounts in the - selected machine's namespace without probing them; scans stop at nested - mounts, including bind mounts and same-device subvolumes. Switching - machines clears marks and identity. The Unix SSH helper streams records + selected machine's namespace without probing them. Local scans include + distinct same-filesystem Btrfs subvolumes, but exclude overlapping mount + views, snapshots, other disks and network mounts; remote scans stop at + every nested mount. Switching machines clears marks and identity. The Unix + SSH helper streams records and never retains the tree. SSH hosts are Unix, so remote paths are POSIX on every client: join, split and compare them through `PathStyle`, never `std::path`, which uses `\` on Windows. @@ -135,17 +137,19 @@ and `cargo build --release` directly; CI runs the gate on both systems. | change | where | | --- | --- | -| bounded Unix SSH traversal | `crates/disktree-core/src/remote_walk.rs` | +| parallel scan, arena, Protobuf cache DB, SWR | `crates/disktree-scanner/src/` (`walk.rs`, `tree.rs`, `db.rs`, `session.rs`) | +| bounded-memory streaming walk | `crates/disktree-scanner/src/stream.rs` (wired into `disktree-core/src/remote_walk.rs`) | +| terminal TUI and `--json` / `--ndjson` CLI | `crates/disktree-cli/src/` | | SSH protocol, discovery and transport | `crates/disktree-core/src/remote.rs` | | joining, splitting or comparing a scanned path | `crates/disktree-core/src/path_style.rs` | -| measurement, filtering, parallelism | `crates/disktree-core/src/scan.rs` | +| arena-to-treemap projection and `ScanHandle` | `crates/disktree-core/src/scan.rs` | | what a node is, or a derived total | `crates/disktree-core/src/tree.rs` | | tile geometry, nesting, the merged tail | `crates/disktree-core/src/treemap.rs` | | anything that deletes, or refuses to | `crates/disktree-core/src/removal.rs` | | free space and projections | `crates/disktree-core/src/space.rs` | -| what macOS lists and measures in bulk | `crates/disktree-core/src/macos.rs` — `unsafe` for `getattrlistbulk` | -| what Windows lists, measures and compares differently | `crates/disktree-core/src/windows.rs` — `unsafe` for Win32 | -| reading a whole NTFS drive from its file table | `crates/disktree-core/src/mft.rs` | +| what macOS lists and measures in bulk | `crates/disktree-scanner/src/macos.rs` — `unsafe` for `getattrlistbulk` | +| what Windows lists, measures and compares differently | `crates/disktree-scanner/src/windows.rs` — `unsafe` for Win32 | +| reading a whole NTFS drive from its file table | `crates/disktree-scanner/src/mft.rs` | | a key, a screen transition, a mark | `crates/disktree-app/src/state.rs` | | spacing, type and size | `crates/disktree-app/src/ui.rs` — tokens only, no `px` in layout | | the mosaic's painting or labels | `crates/disktree-app/src/treemap_view.rs` | diff --git a/Cargo.lock b/Cargo.lock index 5074dea..7d426b0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -164,6 +164,56 @@ dependencies = [ "libc", ] +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + [[package]] name = "anyhow" version = "1.0.104" @@ -324,7 +374,7 @@ dependencies = [ "futures-lite", "parking", "polling", - "rustix", + "rustix 1.1.4", "slab", "windows-sys 0.61.2", ] @@ -366,7 +416,7 @@ dependencies = [ "cfg-if", "event-listener", "futures-lite", - "rustix", + "rustix 1.1.4", ] [[package]] @@ -392,7 +442,7 @@ dependencies = [ "cfg-if", "futures-core", "futures-io", - "rustix", + "rustix 1.1.4", "signal-hook-registry", "slab", "windows-sys 0.61.2", @@ -768,7 +818,7 @@ checksum = "4dbf9978365bac10f54d1d4b04f7ce4427e51f71d61f2fe15e3fed5166474df7" dependencies = [ "bitflags 2.13.2", "polling", - "rustix", + "rustix 1.1.4", "slab", "tracing", ] @@ -780,11 +830,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "138efcf0940a02ebf0cc8d1eff41a1682a46b431630f4c52450d6265876021fa" dependencies = [ "calloop", - "rustix", + "rustix 1.1.4", "wayland-backend", "wayland-client", ] +[[package]] +name = "cassowary" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53" + +[[package]] +name = "castaway" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" +dependencies = [ + "rustversion", +] + [[package]] name = "cbc" version = "0.1.2" @@ -901,6 +966,46 @@ dependencies = [ "libloading", ] +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + [[package]] name = "cocoa" version = "0.25.0" @@ -968,7 +1073,7 @@ checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" dependencies = [ "serde", "termcolor", - "unicode-width", + "unicode-width 0.2.0", ] [[package]] @@ -977,6 +1082,26 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "compact_str" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fd622ebbb56a5b2ccb651b32b911cdeb2a9b4b11776b2473bf26a26a286244e" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "rustversion", + "ryu", + "static_assertions", +] + [[package]] name = "compression-codecs" version = "0.4.42" @@ -1284,6 +1409,31 @@ version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" +[[package]] +name = "crossterm" +version = "0.28.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6" +dependencies = [ + "bitflags 2.13.2", + "crossterm_winapi", + "mio", + "parking_lot", + "rustix 0.38.44", + "signal-hook", + "signal-hook-mio", + "winapi", +] + +[[package]] +name = "crossterm_winapi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" +dependencies = [ + "winapi", +] + [[package]] name = "crunchy" version = "0.2.4" @@ -1319,6 +1469,40 @@ dependencies = [ "linktime-proc-macro", ] +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.5", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.5", +] + [[package]] name = "data-url" version = "0.3.2" @@ -1425,6 +1609,7 @@ dependencies = [ "anyhow", "async-channel", "disktree-core", + "disktree-scanner", "dunce", "gpui-kit", "gpui-omarchy", @@ -1434,21 +1619,35 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "disktree-cli" +version = "0.11.0" +dependencies = [ + "anyhow", + "clap", + "crossterm", + "disktree-scanner", + "ratatui", + "rustc-hash 2.1.3", + "serde", + "serde_json", + "tempfile", +] + [[package]] name = "disktree-core" version = "0.11.0" dependencies = [ "chrono", + "disktree-scanner", "rayon", "rustc-hash 2.1.3", - "rustix", + "rustix 1.1.4", "serde", "serde_json", "sha2 0.10.9", - "sysinfo", "tempfile", "trash", - "winapi-util", "windows-sys 0.61.2", ] @@ -1457,11 +1656,27 @@ name = "disktree-scan" version = "0.11.0" dependencies = [ "disktree-core", - "rustix", + "rustix 1.1.4", "serde_json", "tempfile", ] +[[package]] +name = "disktree-scanner" +version = "0.11.0" +dependencies = [ + "lz4_flex", + "prost", + "rayon", + "redb", + "rustc-hash 2.1.3", + "rustix 1.1.4", + "serde", + "tempfile", + "winapi-util", + "windows-sys 0.61.2", +] + [[package]] name = "dispatch" version = "0.2.0" @@ -2097,7 +2312,7 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" dependencies = [ - "rustix", + "rustix 1.1.4", "windows-link 0.2.1", ] @@ -2458,7 +2673,7 @@ dependencies = [ "slotmap", "smallvec", "spin 0.10.1", - "strum", + "strum 0.28.0", "taffy", "thiserror 2.0.20", "ttf-parser", @@ -2570,7 +2785,7 @@ dependencies = [ "raw-window-handle", "smallvec", "smol", - "strum", + "strum 0.28.0", "url", "uuid", "wayland-backend", @@ -2628,7 +2843,7 @@ dependencies = [ "raw-window-handle", "semver", "smallvec", - "strum", + "strum 0.28.0", "uuid", "zed-font-kit", ] @@ -2973,6 +3188,8 @@ version = "0.15.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" dependencies = [ + "allocator-api2", + "equivalent", "foldhash 0.1.5", ] @@ -3277,6 +3494,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + [[package]] name = "idna" version = "1.1.0" @@ -3377,6 +3600,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "indoc" +version = "2.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a37b2691796cffeb8a8cd305ac66e65841559f147f4e63231d0eafa4db5384d1" +dependencies = [ + "rustversion", +] + [[package]] name = "inotify" version = "0.10.2" @@ -3407,6 +3639,19 @@ dependencies = [ "generic-array", ] +[[package]] +name = "instability" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c3b5acc1e2fd9375041a388da33d1eb8aed5f7a8c0dd3543e3ea2805adfbe20" +dependencies = [ + "darling", + "indoc", + "proc-macro2", + "quote", + "syn 3.0.5", +] + [[package]] name = "instant" version = "0.1.13" @@ -3476,6 +3721,12 @@ dependencies = [ "once_cell", ] +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itertools" version = "0.11.0" @@ -3710,6 +3961,12 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7e57c38c1e860fd37c604281cdfb1dd2216977fd76a50f85ba2f388ef3219616" +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -3756,6 +4013,15 @@ dependencies = [ "imgref", ] +[[package]] +name = "lru" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38" +dependencies = [ + "hashbrown 0.15.5", +] + [[package]] name = "lru-slab" version = "0.1.3" @@ -3827,6 +4093,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "lz4_flex" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13591d77a9b6d941f7e6fcade7f9dfd9e801308752bde50c0a9bb5852778c22c" + [[package]] name = "mac" version = "0.1.1" @@ -4700,6 +4972,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "oo7" version = "0.6.0" @@ -5018,7 +5296,7 @@ dependencies = [ "concurrent-queue", "hermit-abi", "pin-project-lite", - "rustix", + "rustix 1.1.4", "windows-sys 0.61.2", ] @@ -5190,6 +5468,29 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "prost" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2796faa41db3ec313a31f7624d9286acf277b52de526150b7e69f3debf891ee5" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-derive" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d" +dependencies = [ + "anyhow", + "itertools 0.14.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "pulp" version = "0.22.3" @@ -5432,6 +5733,27 @@ version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d" +[[package]] +name = "ratatui" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eabd94c2f37801c20583fc49dd5cd6b0ba68c716787c2dd6ed18571e1e63117b" +dependencies = [ + "bitflags 2.13.2", + "cassowary", + "compact_str", + "crossterm", + "indoc", + "instability", + "itertools 0.13.0", + "lru", + "paste", + "strum 0.26.3", + "unicode-segmentation", + "unicode-truncate", + "unicode-width 0.2.0", +] + [[package]] name = "rav1e" version = "0.8.1" @@ -5557,6 +5879,15 @@ version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "03251193000f4bd3b042892be858ee50e8b3719f2b08e5833ac4353724632430" +[[package]] +name = "redb" +version = "2.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d64e07496d293ad8ed401c4d193d5b9f0f97671fbd5bf21d691a0c7d2c53dc8" +dependencies = [ + "libc", +] + [[package]] name = "redox_syscall" version = "0.5.18" @@ -5836,6 +6167,19 @@ dependencies = [ "semver", ] +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + [[package]] name = "rustix" version = "1.1.4" @@ -5845,7 +6189,7 @@ dependencies = [ "bitflags 2.13.2", "errno", "libc", - "linux-raw-sys", + "linux-raw-sys 0.12.1", "windows-sys 0.61.2", ] @@ -6257,6 +6601,27 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "signal-hook" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-mio" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc" +dependencies = [ + "libc", + "mio", + "signal-hook", +] + [[package]] name = "signal-hook-registry" version = "1.4.8" @@ -6460,13 +6825,41 @@ dependencies = [ "quote", ] +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" +dependencies = [ + "strum_macros 0.26.4", +] + [[package]] name = "strum" version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" dependencies = [ - "strum_macros", + "strum_macros 0.28.0", +] + +[[package]] +name = "strum_macros" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.119", ] [[package]] @@ -6733,7 +7126,7 @@ dependencies = [ "fastrand", "getrandom 0.4.3", "once_cell", - "rustix", + "rustix 1.1.4", "windows-sys 0.61.2", ] @@ -7249,6 +7642,17 @@ version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" +[[package]] +name = "unicode-truncate" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3644627a5af5fa321c95b9b235a72fd24cd29c648c2c379431e6628655627bf" +dependencies = [ + "itertools 0.13.0", + "unicode-segmentation", + "unicode-width 0.1.14", +] + [[package]] name = "unicode-vo" version = "0.1.0" @@ -7257,9 +7661,15 @@ checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94" [[package]] name = "unicode-width" -version = "0.2.2" +version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + +[[package]] +name = "unicode-width" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd" [[package]] name = "unicode-xid" @@ -7363,6 +7773,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "uuid" version = "1.26.1" @@ -7593,7 +8009,7 @@ dependencies = [ "cc", "downcast-rs", "log", - "rustix", + "rustix 1.1.4", "scoped-tls", "smallvec", "wayland-sys", @@ -7606,7 +8022,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" dependencies = [ "bitflags 2.13.2", - "rustix", + "rustix 1.1.4", "wayland-backend", "wayland-scanner", ] @@ -7617,7 +8033,7 @@ version = "0.31.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" dependencies = [ - "rustix", + "rustix 1.1.4", "wayland-client", "xcursor", ] @@ -8596,7 +9012,7 @@ dependencies = [ "as-raw-xcb-connection", "gethostname", "libc", - "rustix", + "rustix 1.1.4", "x11rb-protocol", "xcursor", ] @@ -8759,7 +9175,7 @@ dependencies = [ "hex", "libc", "ordered-stream", - "rustix", + "rustix 1.1.4", "serde", "serde_repr", "tracing", diff --git a/Cargo.toml b/Cargo.toml index 19d0d6e..fd3b875 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,13 @@ [workspace] resolver = "3" -members = ["crates/disktree-app", "crates/disktree-core", "crates/disktree-scan", "xtask"] +members = [ + "crates/disktree-app", + "crates/disktree-cli", + "crates/disktree-core", + "crates/disktree-scan", + "crates/disktree-scanner", + "xtask", +] [workspace.package] version = "0.11.0" @@ -11,6 +18,7 @@ repository = "https://github.com/tobi/disktree" [workspace.dependencies] disktree-core = { path = "crates/disktree-core" } +disktree-scanner = { path = "crates/disktree-scanner" } anyhow = "1" rayon = "1" rustc-hash = "2" diff --git a/README.md b/README.md index 98747c2..aa6321f 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,9 @@ Find what is filling a disk, mark what should go, and remove it — with the volume's free space in view the whole time. -disktree is a treemap for Omarchy. Choose a local or SSH source, then a -mounted volume or directory; no scan starts until you explicitly accept. -It draws every directory as a nested mosaic sized by its real disk cost, +disktree is a treemap for Omarchy. It starts by scanning your home directory; +the location picker switches to another folder, volume or SSH source. +It draws every directory as a nested mosaic sized by its disk usage, and lets you walk into it with the keyboard or the mouse. Mark as much as you like; nothing happens until you review the list and commit, and the permanent path always asks first. @@ -300,7 +300,9 @@ tool-owned data. The remote helper itself has no delete operation. their share and size, to jump sideways (arrows and Enter work too). Above the scanned root a crumb is dimmer, and clicking it widens the scan to there (see below). -- **Under it:** the scan totals, the filter when one is typed, and the legend. +- **Under it:** the scan totals, **Refresh**, the filter when one is typed, + and the legend. Refresh rescans the whole scanned root in the background, + keeps the previous view visible, and updates marks when the scan lands. - **Mosaic:** colour is the *kind* of data — code, agent scratch, toolchains, synced files, git, media, documents, caches — at one muted level, lighter with depth. A diagonal hatch is space that can be had back @@ -381,7 +383,7 @@ and shows how much free space was actually gained. | `t` | size, files or age: what areas and colours say | | `d` | disk usage or apparent size | | `i` | include or skip hidden entries | -| `r` | scan again | +| `r` | refresh the scanned root in the background | | `esc` while scanning | stop the scan | | `v` | choose a local/SSH source and root | | `ctrl o` (`⌘O` on macOS) | choose another directory to scan | @@ -409,9 +411,10 @@ escaped in the prompt, so it cannot pass for another path. ## What it measures -- **Disk usage** by default: `st_blocks × 512`, the number `du` reports and the - space that actually comes back when a file is deleted. Apparent size (what - `ls -l` shows) is one toggle away. +- **Disk usage** by default: `st_blocks × 512`, the number `du` reports. + Apparent size (what `ls -l` shows) is one toggle away. On Btrfs, compression, + reflinks and snapshots mean these totals and the removal projection can + differ from actual physical usage and the space freed by a deletion. - **Hardlinks once.** Two names for one inode cost one file. - **Hidden entries included**, because `~/.cache` is often the biggest thing in a home directory. Symlinks are not followed. @@ -470,11 +473,12 @@ outside `~` (on this machine, seconds instead of a full rescan). The current view stays on screen until the wider tree lands, which then opens with the directory you came from selected. Going back down is just navigation. -By default a scan stops at **every nested mount point**, including bind -mounts and same-device btrfs subvolumes. Boundaries are checked by path, -before metadata or directory reads, so an automounted NAS is not activated -just to measure its parent. Choose `/home`, `/var/log`, or another mount as -its own root rather than implicitly traversing it from `/`. +Local Linux scans include distinct Btrfs subvolumes on the same filesystem, +so a `/` scan includes Omarchy's `/home`. Overlapping mount views, known +snapshot mounts, other disks and network filesystems remain excluded. Mount +boundaries are checked by path before reading a directory, so an automounted +NAS is not activated just to measure its parent. Remote scans still stop at +every nested mount; select another mount as its own root. Local `-X` explicitly crosses mounts; remote streaming scans reject it. A local mark on another volume is still removed, but is not added to the diff --git a/crates/disktree-app/Cargo.toml b/crates/disktree-app/Cargo.toml index 952349a..31b7c6c 100644 --- a/crates/disktree-app/Cargo.toml +++ b/crates/disktree-app/Cargo.toml @@ -17,6 +17,7 @@ workspace = true gpui-kit = { version = "=0.6.6", default-features = false, features = ["assets"] } gpui-omarchy = "0.1.3" disktree-core = { workspace = true } +disktree-scanner = { workspace = true } anyhow = { workspace = true } async-channel = "2" dunce = "1.0.5" diff --git a/crates/disktree-app/src/main.rs b/crates/disktree-app/src/main.rs index 1831469..47b00f1 100644 --- a/crates/disktree-app/src/main.rs +++ b/crates/disktree-app/src/main.rs @@ -86,13 +86,6 @@ options: --power-efficiency PRESET miser, balanced (default), aggressive, drain-my-battery --scan-threads N fixed scan workers, capped by available CPU count - --adaptive-threads - experimental adaptive admission (opt-in) - --fixed-threads disable adaptive admission and CPU governor - --thread-throughput-percent N - retain this percent of sampled initial throughput (80) - --thread-system-cpu-percent N - best-effort host CPU budget; 0 disables it (80) --metric files rank by file count instead of bytes -h, --help show this help "; @@ -192,7 +185,7 @@ fn run() -> Result<()> { if native_look { appearance::apply(cx.window_appearance(), cx); } - let options = args.options.clone(); + let options = args.options; let root_for_app = root.clone(); let window = cx .open_window( @@ -235,7 +228,7 @@ fn run() -> Result<()> { cx.new(|cx| { let mut app = if args.choose_root { Disktree::choose( - options.clone(), + options, depth, args.remote.clone(), cx, @@ -243,7 +236,7 @@ fn run() -> Result<()> { } else { Disktree::open( root_for_app.clone(), - options.clone(), + options, depth, args.remote.clone(), args.remote_disk, @@ -311,7 +304,7 @@ fn parse_args_with_power( ) -> Result { let mut root: Option = None; let mut options = ScanOptions { - threads: preset.policy(power::cpu_threads()), + threads: Some(preset.threads(power::cpu_threads())), ..ScanOptions::default() }; let mut power = Some(preset); @@ -365,54 +358,17 @@ fn parse_args_with_power( text(args.next(), "--power-efficiency needs a preset")?; let preset = power::PowerEfficiency::parse(&value) .context("unknown Power Efficiency preset")?; - options.threads = preset.policy(power::cpu_threads()); + options.threads = Some(preset.threads(power::cpu_threads())); power = Some(preset); } "--scan-threads" => { power = None; let value = text(args.next(), "--scan-threads needs a number")?; - options.threads.max_threads = value + let threads: usize = value .parse() .context("--scan-threads needs a positive integer")?; - anyhow::ensure!( - options.threads.max_threads > 0, - "--scan-threads must be positive" - ); - } - "--fixed-threads" => { - options.threads.adaptive = false; - power = None; - } - "--adaptive-threads" => { - options.threads.adaptive = true; - options.threads.system_cpu_limit = Some(0.80); - power = None; - } - "--thread-throughput-percent" => { - let value = text( - args.next(), - "--thread-throughput-percent needs a number", - )?; - let percent: u8 = value - .parse() - .context("throughput percent must be 1 to 100")?; - anyhow::ensure!( - (1..=100).contains(&percent), - "throughput percent must be 1 to 100" - ); - options.threads.retained_throughput = - f64::from(percent) / 100.0; - } - "--thread-system-cpu-percent" => { - let value = text( - args.next(), - "--thread-system-cpu-percent needs a number", - )?; - let percent: u8 = - value.parse().context("CPU percent must be 0 to 100")?; - anyhow::ensure!(percent <= 100, "CPU percent must be 0 to 100"); - options.threads.system_cpu_limit = - (percent > 0).then(|| f64::from(percent) / 100.0); + anyhow::ensure!(threads > 0, "--scan-threads must be positive"); + options.threads = Some(threads); } "--metric" => { let value = text(args.next(), "--metric needs a value")?; @@ -547,30 +503,13 @@ mod argument_tests { } #[test] - fn adaptive_budget_and_fixed_override_are_explicit() { + fn worker_budget_defaults_and_override_are_explicit() { let args = parse_args(arguments(&[])).expect("defaults"); - assert_eq!( - args.options.threads.max_threads, - 4.min(power::cpu_threads()) - ); - assert!(!args.options.threads.adaptive); - let args = parse_args(arguments(&[ - "--scan-threads", - "4", - "--fixed-threads", - "--thread-throughput-percent", - "85", - "--thread-system-cpu-percent", - "0", - ])) - .expect("custom"); - assert_eq!(args.options.threads.max_threads, 4); - assert!(!args.options.threads.adaptive); - assert!( - (args.options.threads.retained_throughput - 0.85).abs() - < f64::EPSILON - ); - assert_eq!(args.options.threads.system_cpu_limit, None); + assert_eq!(args.options.threads, Some(4.min(power::cpu_threads()))); + let args = + parse_args(arguments(&["--scan-threads", "4"])).expect("custom"); + assert_eq!(args.options.threads, Some(4)); + assert!(args.power.is_none()); } #[test] @@ -603,7 +542,7 @@ mod argument_tests { .expect("remote arguments"); assert_eq!(args.remote.as_deref(), Some("dev")); assert!(args.check); - assert_eq!(args.options.threads.max_threads, 4); + assert_eq!(args.options.threads, Some(4)); assert_eq!(args.root, PathBuf::from("/only-on-the-remote-machine")); assert!(args.power.is_none()); for root in ["relative", r"C:\Users", r"\srv"] { @@ -638,25 +577,19 @@ mod argument_tests { let saved = power::load(&path).expect("load"); let args = parse_args_with_power(arguments(&[]), saved).expect("saved"); assert_eq!(args.power, Some(Power::Miser)); - assert_eq!( - args.options.threads.max_threads, - 2.min(power::cpu_threads()) - ); + assert_eq!(args.options.threads, Some(2.min(power::cpu_threads()))); let args = parse_args_with_power( arguments(&["--power-efficiency", "drain-my-battery"]), saved, ) .expect("override"); assert_eq!(args.power, Some(Power::DrainMyBattery)); - assert_eq!(args.options.threads.max_threads, power::cpu_threads()); - let args = parse_args_with_power( - arguments(&["--scan-threads", "8", "--adaptive-threads"]), - saved, - ) - .expect("experiment"); + assert_eq!(args.options.threads, Some(power::cpu_threads())); + let args = + parse_args_with_power(arguments(&["--scan-threads", "8"]), saved) + .expect("override"); assert!(args.power.is_none()); - assert!(args.options.threads.adaptive); - assert_eq!(args.options.threads.max_threads, 8); + assert_eq!(args.options.threads, Some(8)); assert_eq!(power::load(&path).expect("unchanged"), saved); assert!( parse_args(arguments(&["--power-efficiency", "invalid"])).is_err() @@ -684,18 +617,13 @@ mod argument_tests { ) .expect("native path"); assert_eq!(args.root, dunce::canonicalize(root).expect("root")); - assert_eq!(args.options.threads.max_threads, 4); + assert_eq!(args.options.threads, Some(4)); } #[test] fn invalid_worker_budgets_are_rejected() { - for extra in [ - vec!["--scan-threads", "0"], - vec!["--scan-threads", "-1"], - vec!["--thread-throughput-percent", "0"], - vec!["--thread-throughput-percent", "101"], - vec!["--thread-system-cpu-percent", "101"], - ] { + for extra in [vec!["--scan-threads", "0"], vec!["--scan-threads", "-1"]] + { assert!(parse_args(arguments(&extra)).is_err()); } } diff --git a/crates/disktree-app/src/power.rs b/crates/disktree-app/src/power.rs index c4a05bd..e3cc7f0 100644 --- a/crates/disktree-app/src/power.rs +++ b/crates/disktree-app/src/power.rs @@ -3,8 +3,6 @@ use std::io::{self, Write as _}; use std::path::{Path, PathBuf}; -use disktree_core::scan_threads::ScanThreads; - #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum PowerEfficiency { Miser, @@ -78,15 +76,6 @@ impl PowerEfficiency { .count() .max(1) } - - pub fn policy(self, cpus: usize) -> ScanThreads { - ScanThreads { - max_threads: self.threads(cpus), - adaptive: false, - system_cpu_limit: None, - ..ScanThreads::default() - } - } } pub fn workers(count: usize) -> String { @@ -149,10 +138,7 @@ mod tests { for (preset, expected) in PowerEfficiency::ALL.into_iter().zip([2, 4, 8, 18]) { - let policy = preset.policy(18); - assert_eq!(policy.max_threads, expected); - assert!(!policy.adaptive); - assert_eq!(policy.system_cpu_limit, None); + assert_eq!(preset.threads(18), expected); assert_eq!(preset.threads(1), 1); } assert_eq!(PowerEfficiency::Balanced.threads(3), 3); diff --git a/crates/disktree-app/src/state.rs b/crates/disktree-app/src/state.rs index 8690da5..df29690 100644 --- a/crates/disktree-app/src/state.rs +++ b/crates/disktree-app/src/state.rs @@ -18,7 +18,10 @@ use disktree_core::removal::{ Plan, RemovalEvent, RemovalHandle, RemovalMode, Target, TrashBackend, detect_trash_backend, plan, }; -use disktree_core::scan::{Known, ScanHandle, ScanOptions, ScanSnapshot}; +use disktree_core::scan::{ + Known, ScanHandle, ScanOptions, ScanSnapshot, ScanUpdate, arena_to_node, + node_to_arena, +}; use disktree_core::space::{ SpaceInfo, device_for, space_info, volume_root_for, }; @@ -26,6 +29,9 @@ use disktree_core::tree::{Metric, Node, path_of}; use disktree_core::treemap::{ LayoutOptions, Rect, Tile, TileKind, hit, layout_filtered, }; +use disktree_scanner::{ + CachePolicy, Freshness, Scanner, StorageMode, TreeArena, +}; use gpui_kit::base::input::{InputEvent, InputState}; use gpui_kit::{ AppContext as _, Context, Entity, FocusHandle, Focusable as _, @@ -359,9 +365,14 @@ pub struct Disktree { /// to toggle, not a press outside the menu that closes it first. pub power_hover: bool, pub cpu_threads: usize, + scanner: Scanner, + pub arena: Option>, + pub freshness: Option, pub tree: Option>, pub scan: Option, pub scan_epoch: u64, + /// Metric of a background refresh, or `None` for a normal scan. + pub refresh_metric: Option, pub progress: ScanSnapshot, pub scan_error: Option, @@ -538,6 +549,15 @@ impl Disktree { None }; let trash_backend = detect_trash_backend(); + let scanner = if cfg!(test) { + Scanner::new(StorageMode::InMemory, CachePolicy::default()) + .expect("in-memory scanner") + } else { + Scanner::open_default().unwrap_or_else(|_| { + Scanner::new(StorageMode::InMemory, CachePolicy::default()) + .expect("in-memory fallback scanner") + }) + }; let mut tree = Self { root_path, remote, @@ -556,9 +576,13 @@ impl Disktree { power_menu: None, power_hover: false, cpu_threads: crate::power::cpu_threads(), + scanner, + arena: None, + freshness: None, tree: None, scan: None, scan_epoch: 0, + refresh_metric: None, progress: ScanSnapshot::default(), scan_error: None, screen: Screen::Explore, @@ -687,6 +711,7 @@ impl Disktree { app.options.metric, app.path_style(), ); + app.arena = Some(Arc::new(node_to_arena(app.root_path.clone(), &tree))); app.tree = Some(Arc::new(tree)); app.cache = None; app.refresh_insights(); @@ -736,6 +761,7 @@ impl Disktree { scan.cancel(); } self.scan_epoch += 1; + self.refresh_metric = None; let epoch = self.scan_epoch; self.progress = ScanSnapshot::default(); self.scan_error = None; @@ -743,15 +769,19 @@ impl Disktree { self.scan_elapsed = None; self.scan_root.clone_from(&above); self.remember(); + let known_path = self + .root_path + .canonicalize() + .unwrap_or_else(|_| self.root_path.clone()); + let arena = self.arena.clone().unwrap_or_else(|| { + Arc::new(node_to_arena(known_path.clone(), &tree)) + }); let known = Known { - path: self.root_path.clone(), - tree, + path: known_path, + arena, }; - self.scan = Some(ScanHandle::spawn_with( - above, - self.options.clone(), - Some(known), - )); + self.scan = + Some(ScanHandle::spawn_with(above, self.options, Some(known))); Self::poll_scan(epoch, cx); cx.notify(); } @@ -1209,6 +1239,7 @@ impl Disktree { /// and a widening scan leaves the tree it started from on screen. pub fn cancel_scan(&mut self, cx: &mut Context<'_, Self>) { self.scan_preview = None; + self.refresh_metric = None; if self.remote_scan.take().is_some() { self.scan_epoch += 1; self.progress.cancelled = true; @@ -1243,7 +1274,7 @@ impl Disktree { cx.notify(); return; } - self.options.threads = preset.policy(self.cpu_threads); + self.options.threads = Some(preset.threads(self.cpu_threads)); self.power_choice = Some(preset); let label = preset.label(self.cpu_threads); self.notice = Some(match self.power_settings_path.as_deref() { @@ -1331,8 +1362,86 @@ impl Disktree { true } - /// Start a fresh scan, abandoning any walk still in progress. + /// Refresh the whole scanned root in the background. Keeping its old tree + /// visible also preserves hardlink accounting across the current view and + /// the rest of the root; a subtree-only scan could charge a link twice. + pub fn refresh_scan(&mut self, cx: &mut Context<'_, Self>) { + if self.tree.is_none() { + self.start_scan_with_policy( + CachePolicy { + force_refresh: true, + ..CachePolicy::default() + }, + cx, + ); + return; + } + if self.is_indexing() { + return; + } + self.scan_epoch += 1; + let epoch = self.scan_epoch; + self.refresh_metric = Some(self.options.metric); + self.progress = ScanSnapshot::default(); + self.remote_progress = + disktree_core::remote_progress::Progress::default(); + self.scan_error = None; + self.scan_preview = None; + self.preview_updated = None; + self.scan_started = Some(Instant::now()); + self.scan_elapsed = None; + self.scan_root.clone_from(&self.root_path); + if let Some(host) = &self.remote { + let request = disktree_core::remote::Request { + root: Some(self.root_path.clone()), + disk: self.remote_disk, + options: self.options, + }; + match disktree_core::remote::RemoteScan::spawn(host, &request) { + Ok(scan) => self.remote_scan = Some(scan), + Err(error) => { + self.refresh_metric = None; + self.scan_error = Some(error.to_string()); + cx.notify(); + return; + } + } + } else { + let policy = CachePolicy { + force_refresh: true, + ..CachePolicy::default() + }; + match ScanHandle::spawn_session( + &self.scanner, + self.root_path.clone(), + self.options, + policy, + ) { + Ok(scan) => self.scan = Some(scan), + Err(error) => { + self.refresh_metric = None; + self.scan_error = Some(error.to_string()); + cx.notify(); + return; + } + } + } + Self::poll_scan(epoch, cx); + cx.notify(); + } + + /// Start a scan, serving fresh/stale cache immediately via SWR when + /// available and abandoning any walk still in progress. pub fn start_scan(&mut self, cx: &mut Context<'_, Self>) { + self.start_scan_with_policy(CachePolicy::default(), cx); + } + + fn start_scan_with_policy( + &mut self, + policy: CachePolicy, + cx: &mut Context<'_, Self>, + ) { + self.refresh_metric = None; if self.awaiting_root { self.open_volumes(cx); return; @@ -1353,6 +1462,8 @@ impl Disktree { self.remember(); } discard(self.tree.take()); + self.arena = None; + self.freshness = None; self.crumbs.clear(); self.selected = None; self.hovered = None; @@ -1371,7 +1482,7 @@ impl Disktree { root: (!self.root_path.as_os_str().is_empty()) .then(|| self.root_path.clone()), disk: self.remote_disk, - options: self.options.clone(), + options: self.options, }; match disktree_core::remote::RemoteScan::spawn(host, &request) { Ok(scan) => { @@ -1383,12 +1494,24 @@ impl Disktree { cx.notify(); return; } - self.scan = Some(ScanHandle::spawn( + match ScanHandle::spawn_session( + &self.scanner, self.root_path.clone(), - self.options.clone(), - )); - Self::poll_scan(epoch, cx); - cx.notify(); + self.options, + policy, + ) { + Ok(scan) => { + self.scan = Some(scan); + // Drain any instant cache hit so warm launches paint on frame 1. + if self.poll_scan_once(epoch, cx) { + Self::poll_scan(epoch, cx); + } + } + Err(error) => { + self.scan_error = Some(error.to_string()); + cx.notify(); + } + } } fn poll_scan(epoch: u64, cx: &Context<'_, Self>) { @@ -1449,6 +1572,14 @@ impl Disktree { }; match outcome { Ok(snapshot) => { + let refresh_paths = self.refresh_metric.map(|_| { + ( + self.current_path(), + self.selected + .as_deref() + .and_then(|c| self.path_at(c)), + ) + }); self.root_path = snapshot.header.root; self.home = snapshot.header.home; self.disk_root = snapshot.header.disk_root; @@ -1459,15 +1590,19 @@ impl Disktree { format!("{host} · read-only · space at scan") }); let node = snapshot.tree; - self.marks.refresh( - &self.root_path, - &node, - self.options.metric, - self.path_style(), - ); - self.tree = Some(Arc::new(node)); - self.refresh_insights(); - self.select_largest(cx); + if let Some((directory, selected)) = refresh_paths { + self.install_refresh(node, &directory, selected, cx); + } else { + self.marks.refresh( + &self.root_path, + &node, + self.options.metric, + self.path_style(), + ); + self.tree = Some(Arc::new(node)); + self.refresh_insights(); + self.select_largest(cx); + } self.scan_elapsed = self.scan_started.map(|t| t.elapsed()); } Err(error) => { @@ -1475,6 +1610,7 @@ impl Disktree { } } self.remote_scan = None; + self.refresh_metric = None; self.scan_preview = None; self.progress.finished = true; cx.notify(); @@ -1494,58 +1630,186 @@ impl Disktree { self.preview_updated = Some(Instant::now()); } } - let Some(outcome) = scan.poll() else { + let Some(update) = scan.poll_update() else { cx.notify(); return true; }; - match outcome { - Ok(node) => { - // A widening scan lands on a new root: move the view up to it, - // with the directory it came from selected. - let came_from = (self.scan_root != self.root_path) - .then(|| self.root_path.clone()); - if came_from.is_some() { - self.clear_filter(); - self.root_path.clone_from(&self.scan_root); - self.space = space_info(&self.root_path).ok(); - self.device = device_for(&self.root_path); - self.file_table = file_table_readable(&self.root_path); + match update { + ScanUpdate::Cached { + arena, + node, + freshness, + } => { + let is_fresh = matches!(freshness, Freshness::Fresh { .. }); + self.arena = Some(arena); + self.freshness = Some(freshness); + self.install_tree(node, false, cx); + if is_fresh { + self.scan = None; + self.refresh_metric = None; + self.scan_preview = None; + self.progress.finished = true; + cx.notify(); + return false; } - let metric = self.options.metric; - self.marks.refresh( - &self.root_path, - &node, - metric, - self.path_style(), - ); - discard(self.tree.replace(Arc::new(node))); - self.cache = None; - self.refresh_insights(); + // Stale/partial SWR hit: paint immediately and keep polling + // for the live background revalidation. + self.refresh_metric = Some(self.options.metric); + cx.notify(); + return true; + } + ScanUpdate::Live { arena, node } + if self.refresh_metric.is_some() => + { + let directory = self.current_path(); + let selected = + self.selected.as_deref().and_then(|c| self.path_at(c)); + self.arena = Some(arena); + self.freshness = Some(Freshness::Live { + scanned_at: disktree_scanner::unix_now(), + }); + self.install_refresh(node, &directory, selected, cx); self.scan_elapsed = self.scan_started.map(|started| started.elapsed()); - if let Some(from) = came_from { - let crumbs = self.crumbs_for_path(&from); - self.crumbs.clear(); - self.view = View::default(); - self.transition = None; - self.forget_hover(); - self.selected = crumbs.and_then(|crumbs| { - crumbs.first().map(|&top| vec![top]) - }); - } - self.keep_selection_valid(); - self.prune_history(); - self.select_largest(cx); } - Err(error) => self.scan_error = Some(error.to_string()), + ScanUpdate::Live { arena, node } => { + let came_from = self.scan_root != self.root_path; + self.arena = Some(arena); + self.freshness = Some(Freshness::Live { + scanned_at: disktree_scanner::unix_now(), + }); + self.install_tree(node, came_from, cx); + } + ScanUpdate::Error(error) => { + self.scan_error = Some(error.to_string()); + } + ScanUpdate::Finished => {} } self.scan = None; + self.refresh_metric = None; self.scan_preview = None; self.progress.finished = true; cx.notify(); false } + fn install_tree( + &mut self, + node: Node, + widening: bool, + cx: &mut Context<'_, Self>, + ) { + let came_from = widening.then(|| self.root_path.clone()); + if came_from.is_some() { + self.clear_filter(); + self.root_path.clone_from(&self.scan_root); + self.space = space_info(&self.root_path).ok(); + self.device = device_for(&self.root_path); + self.file_table = file_table_readable(&self.root_path); + } + let metric = self.options.metric; + self.marks + .refresh(&self.root_path, &node, metric, self.path_style()); + discard(self.tree.replace(Arc::new(node))); + self.cache = None; + self.refresh_insights(); + self.scan_elapsed = self.scan_started.map(|started| started.elapsed()); + if let Some(from) = came_from { + let crumbs = self.crumbs_for_path(&from); + self.crumbs.clear(); + self.view = View::default(); + self.transition = None; + self.forget_hover(); + self.selected = + crumbs.and_then(|crumbs| crumbs.first().map(|&top| vec![top])); + } + self.keep_selection_valid(); + self.prune_history(); + self.select_largest(cx); + } + + /// Re-project the current `TreeArena` after toggling `apparent_size` or + /// `include_hidden` without rescanning disk. + pub fn toggle_hidden(&mut self, cx: &mut Context<'_, Self>) { + self.options.include_hidden = !self.options.include_hidden; + if self.remote.is_none() + && let Some(arena) = self.arena.clone() + { + self.reproject_arena(&arena, cx); + } else { + self.start_scan(cx); + } + } + + /// Toggle allocated vs apparent sizes with zero rescan when backed by a + /// local `TreeArena`. + pub fn toggle_apparent_size(&mut self, cx: &mut Context<'_, Self>) { + self.options.apparent_size = !self.options.apparent_size; + if self.remote.is_none() + && let Some(arena) = self.arena.clone() + { + self.reproject_arena(&arena, cx); + } else { + self.start_scan(cx); + } + } + + fn reproject_arena( + &mut self, + arena: &TreeArena, + cx: &mut Context<'_, Self>, + ) { + let directory = self.current_path(); + let selected = self.selected.as_deref().and_then(|c| self.path_at(c)); + let node = arena_to_node( + arena, + self.options.apparent_size, + self.options.include_hidden, + self.options.dedup_hardlinks, + self.options.metric, + ); + self.install_refresh(node, &directory, selected, cx); + self.select_largest(cx); + } + + /// Reattach the view and selection by absolute path: sorting may have + /// changed every crumb while the old tree remained interactive. + fn install_refresh( + &mut self, + mut node: Node, + directory: &Path, + selected: Option, + cx: &mut Context<'_, Self>, + ) { + if self.refresh_metric != Some(self.options.metric) { + disktree_core::tree::aggregate(&mut node, self.options.metric); + } + self.marks.refresh( + &self.root_path, + &node, + self.options.metric, + self.path_style(), + ); + discard(self.tree.replace(Arc::new(node))); + self.clear_filter(); + self.cache = None; + self.transition = None; + self.forget_hover(); + self.git.clear(); + self.git_pending.clear(); + self.refresh_insights(); + let style = self.path_style(); + self.crumbs = style + .ancestors(directory) + .find_map(|path| self.crumbs_for_path(path)) + .unwrap_or_default(); + self.selected = selected + .and_then(|path| self.crumbs_for_path(&path)) + .filter(|crumbs| crumbs.starts_with(&self.crumbs)); + self.prune_history(); + cx.notify(); + } + fn keep_selection_valid(&mut self) { let Some(tree) = &self.tree else { return; @@ -1976,6 +2240,12 @@ impl Disktree { self.view = View::IDENTITY; self.transition = None; self.cache = None; + // Entering a directory while a background SWR refresh is running + // prioritizes that subtree first. + if let Some(scan) = &self.scan { + let target = self.current_path(); + scan.prioritize(&target); + } cx.notify(); } @@ -2935,6 +3205,20 @@ impl Disktree { self.run = None; self.marks.clear(); self.screen = Screen::Done; + // Invalidate every removed path in the cache DB so the follow-up + // scan refreshes them immediately while keeping untouched siblings + // fast. + let removed: Vec = self + .run_log + .iter() + .filter(|(_, outcome)| outcome.is_ok()) + .map(|(path, _)| path.clone()) + .collect(); + if !removed.is_empty() { + let _ = self + .scanner + .invalidate(&disktree_scanner::HostKey::Local, &removed); + } // The tree on screen is now wrong; start over rather than leaving // numbers that include what was just removed. self.start_scan(cx); @@ -3461,17 +3745,11 @@ impl Disktree { "t" if !control => { self.set_mode((self.mode_index() + 1) % 3, cx); } - "r" if !control => self.start_scan(cx), + "r" if !control => self.refresh_scan(cx), "g" if !control => self.go_to_disk(cx), "v" if !control && !shift => self.open_volumes(cx), - "i" if !control => { - self.options.include_hidden = !self.options.include_hidden; - self.start_scan(cx); - } - "d" if !control => { - self.options.apparent_size = !self.options.apparent_size; - self.start_scan(cx); - } + "i" if !control => self.toggle_hidden(cx), + "d" if !control => self.toggle_apparent_size(cx), "p" if !control => { self.show_selection = !self.show_selection; cx.notify(); @@ -3871,25 +4149,10 @@ pub fn restart_args( if options.metric == Metric::Files { args.push("files".into()); } - args.push("--scan-threads".into()); - args.push(options.threads.max_threads.to_string().into()); - args.push(if options.threads.adaptive { - "--adaptive-threads".into() - } else { - "--fixed-threads".into() - }); - args.push("--thread-throughput-percent".into()); - args.push( - format!("{:.0}", options.threads.retained_throughput * 100.0).into(), - ); - args.push("--thread-system-cpu-percent".into()); - args.push( - format!( - "{:.0}", - options.threads.system_cpu_limit.unwrap_or(0.0) * 100.0 - ) - .into(), - ); + if let Some(threads) = options.threads { + args.push("--scan-threads".into()); + args.push(threads.to_string().into()); + } args.push("--depth".into()); args.push(depth.to_string().into()); args.push(root.as_os_str().to_owned()); diff --git a/crates/disktree-app/src/tests.rs b/crates/disktree-app/src/tests.rs index cea6796..0161aa1 100644 --- a/crates/disktree-app/src/tests.rs +++ b/crates/disktree-app/src/tests.rs @@ -1777,6 +1777,111 @@ fn after_descending_every_tile_is_inside_the_directory_drawn( assert_eq!(hatched, 1, "exactly the marked tile is hatched"); } +#[gpui_kit::test] +fn refresh_button_rescans_and_keeps_the_view_and_marks_by_path( + cx: &mut TestAppContext, +) { + use gpui_kit::Modifiers; + + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + let junk = temp.path().join("junk"); + let blob = junk.join("blob.bin"); + update(&view, cx, |app, cx| { + let directory = app.crumbs_for_path(&junk).unwrap(); + app.go_to(directory, cx); + let selected = app.crumbs_for_path(&blob).unwrap(); + app.select(Some(selected), cx); + app.toggle_mark_selected(cx); + }); + std::fs::write(&blob, vec![b'x'; 400_000]).unwrap(); + std::fs::write(junk.join("new.bin"), vec![b'x'; 500_000]).unwrap(); + std::fs::write(temp.path().join("keep/new.bin"), b"outside view").unwrap(); + draw(cx); + let button = cx.debug_bounds("refresh-scan").expect("refresh button"); + cx.simulate_click(button.center(), Modifiers::none()); + read(&view, cx, |app| { + assert!(app.scan.is_some()); + assert!(app.refresh_metric.is_some()); + assert!(app.tree().is_some(), "the previous tree stays visible"); + assert_eq!(app.current_path(), junk); + }); + finish_scan(&view, cx); + read(&view, cx, |app| { + assert_eq!(app.current_path(), junk); + let selected = app.selected.as_deref().and_then(|c| app.path_at(c)); + assert_eq!(selected.as_deref(), Some(blob.as_path())); + assert_eq!(app.marks.items()[0].path, blob); + assert_eq!(app.marks.items()[0].bytes, 400_000); + assert!(app.crumbs_for_path(&junk.join("new.bin")).is_some()); + assert!( + app.crumbs_for_path(&temp.path().join("keep/new.bin")) + .is_some(), + "refresh rescans the whole root, not just the visible directory" + ); + assert!(app.refresh_metric.is_none()); + }); +} + +#[gpui_kit::test] +fn toggling_hidden_and_apparent_reprojects_arena_without_rescanning( + cx: &mut TestAppContext, +) { + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + let epoch = read(&view, cx, |app| app.scan_epoch); + assert!(read(&view, cx, |app| app + .tree() + .unwrap() + .child_named(".cache") + .is_some())); + + update(&view, cx, Disktree::toggle_hidden); + read(&view, cx, |app| { + assert!(!app.options.include_hidden); + assert_eq!(app.scan_epoch, epoch, "no rescan triggered"); + assert!(app.scan.is_none()); + assert!(app.tree().unwrap().child_named(".cache").is_none()); + }); + + update(&view, cx, Disktree::toggle_hidden); + read(&view, cx, |app| { + assert!(app.options.include_hidden); + assert_eq!(app.scan_epoch, epoch, "still no rescan"); + assert!(app.tree().unwrap().child_named(".cache").is_some()); + }); + + update(&view, cx, Disktree::toggle_apparent_size); + read(&view, cx, |app| { + assert!(!app.options.apparent_size); + assert_eq!(app.scan_epoch, epoch, "apparent toggle needs no rescan"); + assert!(app.scan.is_none()); + }); +} + +#[gpui_kit::test] +fn cancelling_a_refresh_keeps_the_previous_complete_tree( + cx: &mut TestAppContext, +) { + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + let before = read(&view, cx, |app| app.tree().unwrap().bytes); + std::fs::write(temp.path().join("new.bin"), b"new").unwrap(); + update(&view, cx, |app, cx| { + app.refresh_scan(cx); + assert!(app.scan.is_some()); + app.cancel_scan(cx); + assert!(app.refresh_metric.is_none()); + }); + read(&view, cx, |app| { + assert_eq!(app.tree().unwrap().bytes, before); + assert!(app.crumbs_for_path(&temp.path().join("new.bin")).is_none()); + }); +} + /// Drive the scan the view started until its outcome has been applied. /// /// The scan is what is waited on, not the tree: widening keeps the old tree @@ -2363,32 +2468,20 @@ fn restart_arguments_parse_back_to_the_same_scan() { include_hidden: false, one_filesystem: false, metric: Metric::Files, - threads: disktree_core::scan_threads::ScanThreads { - max_threads: 8, - adaptive: true, - retained_throughput: 0.85, - system_cpu_limit: Some(0.70), - }, + threads: Some(8), ..ScanOptions::default() }; - for (options, depth) in [(changed, 5), (ScanOptions::default(), 1)] { + let default_with_threads = ScanOptions { + threads: Some(4.min(crate::power::cpu_threads())), + ..ScanOptions::default() + }; + for (options, depth) in [(changed, 5), (default_with_threads, 1)] { let args = crate::state::restart_args(&options, depth, &root); let parsed = crate::parse_args(args.into_iter()).expect("parses"); assert_eq!(parsed.root, root); assert_eq!(parsed.depth, depth); let got = &parsed.options; - assert_eq!(got.threads.max_threads, options.threads.max_threads); - assert_eq!(got.threads.adaptive, options.threads.adaptive); - assert!( - (got.threads.retained_throughput - - options.threads.retained_throughput) - .abs() - < f64::EPSILON - ); - assert_eq!( - got.threads.system_cpu_limit, - options.threads.system_cpu_limit - ); + assert_eq!(got.threads, options.threads); assert_eq!( ( got.apparent_size, @@ -2439,10 +2532,9 @@ fn power_efficiency_menu_saves_without_discarding_the_tree( read(&view, cx, |app| { assert_eq!(app.power_choice, Some(preset)); assert_eq!( - app.options.threads.max_threads, - preset.threads(app.cpu_threads) + app.options.threads, + Some(preset.threads(app.cpu_threads)) ); - assert!(!app.options.threads.adaptive); assert!(app.power_menu.is_none()); assert_eq!(app.scan_epoch, epoch); assert!(app.tree.is_some()); @@ -2515,7 +2607,7 @@ fn the_power_menu_offers_only_what_the_cpus_can_tell_apart( press(cx, "enter"); read(&view, cx, |app| { assert_eq!(app.power_choice, Some(Power::Miser)); - assert_eq!(app.options.threads.max_threads, 2); + assert_eq!(app.options.threads, Some(2)); assert!(app.power_menu.is_none()); }); diff --git a/crates/disktree-app/src/views.rs b/crates/disktree-app/src/views.rs index 5f1dccc..8fcfb7a 100644 --- a/crates/disktree-app/src/views.rs +++ b/crates/disktree-app/src/views.rs @@ -66,7 +66,7 @@ pub fn root( // Where `r` would: not behind the confirmation, and not under // the review list or a removal that is still running. if this.can_start_over() { - this.start_scan(cx); + this.refresh_scan(cx); } })) .on_action(cx.listener( @@ -1329,8 +1329,7 @@ fn view_settings( .tab_stop(false) .on_change(move |_, _, window, cx| { let _ = entity.update(cx, |this, cx| { - this.options.include_hidden = !this.options.include_hidden; - this.start_scan(cx); + this.toggle_hidden(cx); }); window.focus(&focus, cx); }) @@ -1345,8 +1344,7 @@ fn view_settings( .tab_stop(false) .on_change(move |_, _, window, cx| { let _ = entity.update(cx, |this, cx| { - this.options.apparent_size = !this.options.apparent_size; - this.start_scan(cx); + this.toggle_apparent_size(cx); }); window.focus(&focus, cx); }) @@ -1501,7 +1499,7 @@ fn power_efficiency(app: &Disktree, cx: &Context<'_, Disktree>) -> Div { let theme = cx.omarchy().clone(); let cpus = app.cpu_threads; - let threads = app.options.threads.max_threads.min(cpus); + let threads = app.options.threads.unwrap_or(cpus).min(cpus); let name = app.power_choice.map_or("Custom", PowerEfficiency::name); let open = app.power_menu.is_some(); let trigger = div() @@ -1693,7 +1691,20 @@ fn trail_and_legend( .gap(space::LG) .px(space::LG) .py(space::SM) - .child(scan_totals(app, theme)); + .child(scan_totals(app, theme)) + .child(with_tooltip( + button("refresh-scan", "Refresh", ButtonVariant::Outline, cx) + .debug_selector(|| "refresh-scan".into()) + .tab_stop(false) + .px(space::SM) + .py(space::XS) + .disabled(app.is_indexing()) + .on_click(cx.listener(|this, _, window, cx| { + this.refresh_scan(cx); + window.focus(&this.focus, cx); + })), + "Refresh the scanned root · r", + )); if app.find_open || !app.find.is_empty() { row = row.child(find_field(app, theme)); } @@ -1707,7 +1718,11 @@ fn scan_totals(app: &Disktree, theme: &Theme) -> Div { return div() .text_size(text::CAPTION) .text_color(theme.secondary) - .child("Live overview · incomplete · top-level contributions"); + .child(if app.refresh_metric.is_some() { + "Refreshing · showing the previous scan" + } else { + "Live overview · incomplete · top-level contributions" + }); } let tree = app.tree(); let bytes = tree.map_or(app.progress.bytes, |node| node.bytes); @@ -1734,6 +1749,13 @@ fn scan_totals(app: &Disktree, theme: &Theme) -> Div { widgets::human_count(errors) ))) }) + .when( + matches!( + app.freshness, + Some(disktree_scanner::Freshness::Fresh { .. }) + ), + |this| this.child("· cached"), + ) } /// The key to the colours: the categories, or the age ramp in age mode. @@ -2929,7 +2951,14 @@ fn indexing_progress( .gap(space::XS) .text_size(text::BODY) .text_color(theme.foreground) - .child(widgets::eyebrow("Indexing", cx)) + .child(widgets::eyebrow( + if app.refresh_metric.is_some() { + "Refreshing" + } else { + "Indexing" + }, + cx, + )) .child(div().h(size::PROGRESS_ROW).truncate().child( if app.remote.is_some() { app.remote_progress.stage.label() diff --git a/crates/disktree-cli/Cargo.toml b/crates/disktree-cli/Cargo.toml new file mode 100644 index 0000000..986eba5 --- /dev/null +++ b/crates/disktree-cli/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "disktree-cli" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "Fast terminal disk usage explorer (Ratatui TUI + JSON) backed by disktree-scanner" + +[[bin]] +name = "disktree-cli" +path = "src/main.rs" + +[lints] +workspace = true + +[dependencies] +anyhow = { workspace = true } +clap = { version = "4", features = ["derive"] } +crossterm = "0.28" +disktree-scanner = { workspace = true } +ratatui = "0.29" +rustc-hash = { workspace = true } +serde = { version = "1", features = ["derive"] } +serde_json = "1" + +[dev-dependencies] +tempfile = "3" diff --git a/crates/disktree-cli/src/cli.rs b/crates/disktree-cli/src/cli.rs new file mode 100644 index 0000000..a0e3b66 --- /dev/null +++ b/crates/disktree-cli/src/cli.rs @@ -0,0 +1,275 @@ +//! Command-line argument parsing and human duration parsing for +//! `disktree-cli`. + +use std::path::PathBuf; +use std::time::Duration; + +use clap::{Parser, Subcommand, ValueEnum}; +use disktree_scanner::{CachePolicy, Metric, ScanOptions, StorageMode}; + +/// Fast disk usage explorer with a 15-minute Protobuf cache, SWR, and JSON. +#[derive(Clone, Debug, Parser)] +#[command(name = "disktree-cli", version, about)] +pub struct Cli { + #[command(subcommand)] + pub command: Option, + + /// Directory to inspect (defaults to current working directory). + pub path: Option, + + /// Maximum cache age before revalidation (default: 15m). Examples: 0, 30s, + /// 15m, 1h, 2h30m. + #[arg(long, default_value = "15m", value_parser = parse_duration)] + pub max_age: Duration, + + /// Ignore cached freshness and force a live scan (still updates cache). + #[arg(long, alias = "no-cache")] + pub fresh: bool, + + /// Return stale cached data immediately without waiting for revalidation + /// (in `--json` / non-TTY mode). + #[arg(long)] + pub stale_ok: bool, + + /// Force revalidation of specific subtrees before/during the scan. + #[arg(long = "revalidate", value_name = "PATH")] + pub revalidate_paths: Vec, + + /// Storage backend mode (auto falls back to in-memory on full/RO disks). + #[arg(long, value_enum, default_value_t = ModeArg::Auto)] + pub mode: ModeArg, + + /// Override the cache DB directory (stores `scan-cache.redb` inside it). + #[arg(long, value_name = "DIR")] + pub cache_dir: Option, + + /// Output a single structured JSON document (`schema_version: 1`). + #[arg(long)] + pub json: bool, + + /// Output newline-delimited JSON (streaming records or SWR snapshots). + #[arg(long)] + pub ndjson: bool, + + /// Run in bounded-memory O(depth) streaming mode (implies `--ndjson`). + #[arg(long)] + pub stream: bool, + + /// With `--ndjson`, emit stale cached snapshot first then live snapshot. + #[arg(long)] + pub swr: bool, + + /// Maximum depth emitted in JSON/text output (unlimited if omitted). + #[arg(long)] + pub depth: Option, + + /// Maximum number of children emitted per directory in JSON/text output. + #[arg(long)] + pub top: Option, + + /// Measure and rank by apparent file length instead of allocated blocks. + #[arg(short = 'a', long)] + pub apparent_size: bool, + + /// Exclude hidden dotfiles/dot-directories from totals and display. + #[arg(short = 'H', long)] + pub no_hidden: bool, + + /// Follow symbolic links while walking. + #[arg(short = 'l', long)] + pub follow_links: bool, + + /// Cross filesystem mount boundaries while walking. + #[arg(short = 'X', long)] + pub cross_filesystems: bool, + + /// Ranking metric for children. + #[arg(long, value_enum, default_value_t = MetricArg::Bytes)] + pub metric: MetricArg, + + /// Fixed worker threads for scanning (defaults to CPU count). + #[arg(long)] + pub scan_threads: Option, +} + +#[derive(Clone, Debug, Subcommand)] +pub enum Command { + /// Mark one or more paths dirty in the cache DB (e.g. after deleting files) + /// so subsequent runs revalidate them immediately. + Invalidate { + /// Paths to invalidate (may already be deleted). + #[arg(required = true)] + paths: Vec, + + /// Emit JSON output. + #[arg(long)] + json: bool, + }, + /// Inspect or maintain the scan cache database. + Cache { + #[command(subcommand)] + action: CacheAction, + }, +} + +#[derive(Clone, Debug, Subcommand)] +pub enum CacheAction { + /// Print cache DB location, size, indexed directories, and chunk count. + Status { + #[arg(long)] + json: bool, + }, + /// Delete all cached entries. + Clear { + #[arg(long)] + json: bool, + }, + /// Remove cached chunks older than `--older-than` (default: 24h). + Prune { + #[arg(long, default_value = "24h", value_parser = parse_duration)] + older_than: Duration, + #[arg(long)] + json: bool, + }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)] +pub enum ModeArg { + Auto, + Memory, + Stream, + TempDb, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)] +pub enum MetricArg { + Bytes, + Apparent, + Files, +} + +impl Cli { + pub fn storage_mode(&self) -> StorageMode { + if self.stream || self.mode == ModeArg::Stream { + return StorageMode::Streaming; + } + if let Some(dir) = &self.cache_dir { + return StorageMode::Persistent { + path: dir.join("scan-cache.redb"), + strict: false, + }; + } + match self.mode { + ModeArg::Auto => StorageMode::Auto, + ModeArg::Memory => StorageMode::InMemory, + ModeArg::Stream => StorageMode::Streaming, + ModeArg::TempDb => StorageMode::TempDb, + } + } + + pub fn scan_options(&self) -> ScanOptions { + ScanOptions { + apparent_size: self.apparent_size + || self.metric == MetricArg::Apparent, + follow_links: self.follow_links, + include_hidden: !self.no_hidden, + one_filesystem: !self.cross_filesystems, + max_depth: None, + dedup_hardlinks: true, + threads: self.scan_threads, + } + } + + pub const fn metric(&self) -> Metric { + if self.apparent_size { + return Metric::ApparentBytes; + } + match self.metric { + MetricArg::Bytes => Metric::Bytes, + MetricArg::Apparent => Metric::ApparentBytes, + MetricArg::Files => Metric::Files, + } + } + + pub fn cache_policy(&self) -> CachePolicy { + CachePolicy { + ttl: self.max_age, + stale_while_revalidate: true, + force_refresh: self.fresh, + reuse_fresh_subtrees: !self.fresh, + ..CachePolicy::default() + } + } +} + +/// Parse a compact human duration such as `0`, `45s`, `15m`, `1h`, `1h30m`, +/// or `2d`. +pub fn parse_duration(input: &str) -> Result { + let trimmed = input.trim(); + if trimmed.is_empty() { + return Err("duration cannot be empty".to_owned()); + } + if trimmed == "0" { + return Ok(Duration::ZERO); + } + if let Ok(plain_secs) = trimmed.parse::() { + return Ok(Duration::from_secs(plain_secs)); + } + + let mut total_secs = 0u64; + let mut num_buf = String::new(); + let mut matched_unit = false; + + for ch in trimmed.chars() { + if ch.is_ascii_digit() { + num_buf.push(ch); + continue; + } + if num_buf.is_empty() { + return Err(format!( + "invalid duration '{input}': unexpected '{ch}'" + )); + } + let val: u64 = num_buf.parse().map_err(|e| { + format!("invalid number in duration '{input}': {e}") + })?; + num_buf.clear(); + + let mult = match ch { + 's' | 'S' => 1u64, + 'm' | 'M' => 60, + 'h' | 'H' => 3_600, + 'd' | 'D' => 86_400, + _ => { + return Err(format!( + "unknown unit '{ch}' in duration '{input}' (use s, m, h, d)" + )); + } + }; + total_secs = total_secs.saturating_add(val.saturating_mul(mult)); + matched_unit = true; + } + + if !num_buf.is_empty() || !matched_unit { + return Err(format!( + "invalid duration '{input}' (example: 15m, 1h30m)" + )); + } + + Ok(Duration::from_secs(total_secs)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_duration_handles_units_and_compounds() { + assert_eq!(parse_duration("0").unwrap(), Duration::ZERO); + assert_eq!(parse_duration("30s").unwrap(), Duration::from_secs(30)); + assert_eq!(parse_duration("15m").unwrap(), Duration::from_mins(15)); + assert_eq!(parse_duration("1h30m").unwrap(), Duration::from_mins(90)); + assert_eq!(parse_duration("2d").unwrap(), Duration::from_hours(48)); + assert!(parse_duration("abc").is_err()); + } +} diff --git a/crates/disktree-cli/src/format.rs b/crates/disktree-cli/src/format.rs new file mode 100644 index 0000000..9e26d67 --- /dev/null +++ b/crates/disktree-cli/src/format.rs @@ -0,0 +1,57 @@ +//! Human-readable size, age, and bar formatting helpers. + +/// Format a byte count with binary IEC prefixes (`B`, `KiB`, `MiB`, `GiB`, +/// `TiB`). +pub fn human_bytes(bytes: u64) -> String { + const UNITS: [&str; 6] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"]; + if bytes < 1024 { + return format!("{bytes} B"); + } + let mut value = bytes as f64; + let mut unit = 0usize; + while value >= 1024.0 && unit + 1 < UNITS.len() { + value /= 1024.0; + unit += 1; + } + if value >= 100.0 { + format!("{value:.0} {}", UNITS[unit]) + } else if value >= 10.0 { + format!("{value:.1} {}", UNITS[unit]) + } else { + format!("{value:.2} {}", UNITS[unit]) + } +} + +/// Format an elapsed duration in seconds as a compact relative age string. +pub fn human_age(age_secs: u64) -> String { + if age_secs < 5 { + "just now".to_owned() + } else if age_secs < 60 { + format!("{age_secs}s ago") + } else if age_secs < 3_600 { + format!("{}m ago", age_secs / 60) + } else if age_secs < 86_400 { + format!("{}h ago", age_secs / 3_600) + } else { + format!("{}d ago", age_secs / 86_400) + } +} + +/// Render an ASCII/Unicode usage bar of width `width` for `fraction` in +/// `0.0..=1.0`. +pub fn usage_bar(fraction: f64, width: usize) -> String { + if width == 0 { + return String::new(); + } + let clamped = fraction.clamp(0.0, 1.0); + let filled = (clamped * width as f64).round() as usize; + let filled = filled.min(width); + let mut out = String::with_capacity(width * 3); + for _ in 0..filled { + out.push('█'); + } + for _ in filled..width { + out.push('░'); + } + out +} diff --git a/crates/disktree-cli/src/json_out.rs b/crates/disktree-cli/src/json_out.rs new file mode 100644 index 0000000..f290068 --- /dev/null +++ b/crates/disktree-cli/src/json_out.rs @@ -0,0 +1,199 @@ +//! Versioned JSON (`--json`) and newline-delimited JSON (`--ndjson` / +//! `--stream`) output formatters. + +use std::io::{self, Write}; + +use disktree_scanner::{ + ActiveStorageMode, FallbackReason, Freshness, HostIdentity, Metric, NodeId, + NodeKind, ScanSnapshot, ScanStats, SpaceInfo, SubtreeStatus, TreeArena, + unix_now, +}; +use serde::Serialize; + +/// Schema version emitted in every `--json` / `--ndjson` snapshot document. +pub const SCHEMA_VERSION: u32 = 1; + +#[derive(Serialize)] +pub struct JsonDocument { + pub schema_version: u32, + pub host: Option, + pub root: String, + pub metric: Metric, + pub apparent_size: bool, + pub include_hidden: bool, + pub freshness: JsonFreshness, + pub storage: JsonStorage, + pub space: Option, + pub stats: ScanStats, + pub tree: JsonNode, +} + +#[derive(Serialize)] +pub struct JsonFreshness { + pub status: &'static str, + pub scanned_at: Option, + pub age_seconds: Option, + pub stale_dirs: Option, +} + +#[derive(Serialize)] +pub struct JsonStorage { + pub mode: ActiveStorageMode, + pub fallback_reason: Option, +} + +#[derive(Serialize)] +pub struct JsonNode { + pub name: String, + pub path: String, + pub kind: NodeKind, + pub bytes: u64, + pub apparent_bytes: u64, + pub files: u64, + pub dirs: u32, + pub modified: i64, + pub read_error: bool, + pub hidden: bool, + pub status: SubtreeStatus, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub children: Vec, +} + +/// Build a structured [`JsonDocument`] from a [`ScanSnapshot`]. +#[allow(clippy::too_many_arguments, reason = "top-level output builder")] +pub fn build_document( + snapshot: &ScanSnapshot, + metric: Metric, + apparent_size: bool, + include_hidden: bool, + max_depth: Option, + top_n: Option, + space: Option, +) -> JsonDocument { + let now = unix_now(); + let freshness = match &snapshot.freshness { + Freshness::Fresh { newest_at, .. } => JsonFreshness { + status: "fresh", + scanned_at: Some(*newest_at), + age_seconds: Some(now.saturating_sub(*newest_at)), + stale_dirs: Some(0), + }, + Freshness::Stale { + newest_at, + stale_dirs, + .. + } => JsonFreshness { + status: "stale", + scanned_at: Some(*newest_at), + age_seconds: Some(now.saturating_sub(*newest_at)), + stale_dirs: Some(*stale_dirs), + }, + Freshness::Partial { + newest_at, + missing_dirs, + .. + } => JsonFreshness { + status: "partial", + scanned_at: *newest_at, + age_seconds: newest_at.map(|ts| now.saturating_sub(ts)), + stale_dirs: Some(*missing_dirs), + }, + Freshness::Live { scanned_at } => JsonFreshness { + status: "live", + scanned_at: Some(*scanned_at), + age_seconds: Some(now.saturating_sub(*scanned_at)), + stale_dirs: Some(0), + }, + }; + + let tree = build_node( + &snapshot.arena, + snapshot.arena.root(), + 0, + max_depth, + top_n, + include_hidden, + ); + + JsonDocument { + schema_version: SCHEMA_VERSION, + host: HostIdentity::current(), + root: snapshot.arena.root_path().to_string_lossy().into_owned(), + metric, + apparent_size, + include_hidden, + freshness, + storage: JsonStorage { + mode: snapshot.storage_mode, + fallback_reason: snapshot.fallback_reason.clone(), + }, + space, + stats: snapshot.stats.clone(), + tree, + } +} + +fn build_node( + arena: &TreeArena, + id: NodeId, + depth: usize, + max_depth: Option, + top_n: Option, + include_hidden: bool, +) -> JsonNode { + let node = arena.node(id); + let mut children = Vec::new(); + if node.is_dir() && max_depth.is_none_or(|limit| depth < limit) { + let iter = arena + .children(id) + .filter(|&kid| include_hidden || !arena.node(kid).hidden()); + let limited: Vec = match top_n { + Some(n) => iter.take(n).collect(), + None => iter.collect(), + }; + children.reserve(limited.len()); + for kid in limited { + children.push(build_node( + arena, + kid, + depth + 1, + max_depth, + top_n, + include_hidden, + )); + } + } + + JsonNode { + name: arena.name(id).to_owned(), + path: arena.path_of(id).to_string_lossy().into_owned(), + kind: node.kind(), + bytes: node.effective_allocated_bytes(), + apparent_bytes: node.effective_apparent_bytes(), + files: node.files, + dirs: node.dirs, + modified: node.modified, + read_error: node.read_error(), + hidden: node.hidden(), + status: node.status(), + children, + } +} + +/// Write a pretty-printed JSON document. +pub fn write_pretty( + out: &mut W, + doc: &JsonDocument, +) -> io::Result<()> { + serde_json::to_writer_pretty(&mut *out, doc).map_err(io::Error::other)?; + writeln!(out) +} + +/// Write a single compact JSON line (`--ndjson`). +pub fn write_ndjson_line( + out: &mut W, + value: &T, +) -> io::Result<()> { + serde_json::to_writer(&mut *out, value).map_err(io::Error::other)?; + writeln!(out) +} diff --git a/crates/disktree-cli/src/main.rs b/crates/disktree-cli/src/main.rs new file mode 100644 index 0000000..becc711 --- /dev/null +++ b/crates/disktree-cli/src/main.rs @@ -0,0 +1,300 @@ +//! `disktree-cli`: fast terminal disk usage explorer (Ratatui TUI + JSON mode) +//! backed by `disktree-scanner`. + +mod cli; +mod format; +mod json_out; +mod tui; + +use std::io::{self, IsTerminal as _, Write as _}; +use std::path::PathBuf; + +use anyhow::Result; +use clap::Parser as _; +use disktree_scanner::{ + Freshness, HostKey, ScanEvent, Scanner, StorageMode, space_info, +}; +use serde::Serialize; + +use crate::cli::{CacheAction, Cli, Command}; +use crate::format::{human_age, human_bytes}; +use crate::json_out::{build_document, write_ndjson_line, write_pretty}; + +fn main() -> Result<()> { + let args = Cli::parse(); + let policy = args.cache_policy(); + let mode = args.storage_mode(); + + if let Some(command) = &args.command { + return run_subcommand(command, mode, policy); + } + + let root = match &args.path { + Some(path) => path.clone(), + None => std::env::current_dir()?, + }; + let canonical_root = root.canonicalize().unwrap_or(root); + let options = args.scan_options(); + let metric = args.metric(); + + let scanner = Scanner::new(mode, policy)?; + + // Targeted `--revalidate` paths invalidate before opening so they are + // refreshed while untouched fresh siblings stay cached. + if !args.revalidate_paths.is_empty() { + let _ = scanner.invalidate(&HostKey::Local, &args.revalidate_paths)?; + } + + // Bounded-memory streaming mode (`--stream` or `--mode stream`). + if args.stream || matches!(args.storage_mode(), StorageMode::Streaming) { + let mut stdout = io::BufWriter::new(io::stdout().lock()); + scanner.stream(&canonical_root, &options, None, |item| { + write_ndjson_line(&mut stdout, &item) + })?; + stdout.flush()?; + return Ok(()); + } + + let space = space_info(&canonical_root).ok(); + + // Structured JSON mode (`--json`). + if args.json { + let snapshot = scanner.scan_blocking( + &canonical_root, + options, + policy, + args.stale_ok, + )?; + let doc = build_document( + &snapshot, + metric, + options.apparent_size, + options.include_hidden, + args.depth, + args.top, + space, + ); + let mut stdout = io::BufWriter::new(io::stdout().lock()); + write_pretty(&mut stdout, &doc)?; + stdout.flush()?; + return Ok(()); + } + + // NDJSON mode (`--ndjson`, optionally emitting stale then live with `--swr`). + if args.ndjson { + let session = scanner.open_with( + HostKey::Local, + canonical_root, + options, + policy, + )?; + let mut stdout = io::BufWriter::new(io::stdout().lock()); + while let Ok(event) = session.recv() { + match event { + ScanEvent::Snapshot(snap) => { + let is_final = matches!( + snap.freshness, + Freshness::Fresh { .. } | Freshness::Live { .. } + ); + if args.swr || args.stale_ok || is_final { + let doc = build_document( + &snap, + metric, + options.apparent_size, + options.include_hidden, + args.depth, + args.top, + space, + ); + write_ndjson_line(&mut stdout, &doc)?; + stdout.flush()?; + } + if args.stale_ok || is_final { + session.cancel(); + break; + } + } + ScanEvent::Error { message } => { + eprintln!("disktree-cli: {message}"); + } + ScanEvent::Finished => break, + _ => {} + } + } + return Ok(()); + } + + // Non-TTY stdout without `--json`: print a concise ranked summary table. + if !io::stdout().is_terminal() { + let snapshot = scanner.scan_blocking( + &canonical_root, + options, + policy, + args.stale_ok, + )?; + print_plain_summary( + &snapshot, + options.apparent_size, + options.include_hidden, + args.top.unwrap_or(20), + )?; + return Ok(()); + } + + // Interactive Ratatui TUI. + let session = scanner.open_with( + HostKey::Local, + canonical_root.clone(), + options, + policy, + )?; + let exported = tui::run_tui( + &session, + &canonical_root, + options, + scanner.active_mode(), + scanner.fallback_reason(), + space, + )?; + + if !exported.is_empty() { + let mut stdout = io::BufWriter::new(io::stdout().lock()); + for path in exported { + writeln!(stdout, "{}", path.display())?; + } + stdout.flush()?; + } + + Ok(()) +} + +fn run_subcommand( + command: &Command, + mode: StorageMode, + policy: disktree_scanner::CachePolicy, +) -> Result<()> { + let scanner = Scanner::new(mode, policy)?; + match command { + Command::Invalidate { paths, json } => { + let report = scanner.invalidate(&HostKey::Local, paths)?; + if *json { + #[derive(Serialize)] + struct Out<'a> { + paths: &'a [PathBuf], + invalidated_dirs: u64, + touched_ancestors: u64, + } + let mut stdout = io::stdout().lock(); + serde_json::to_writer_pretty( + &mut stdout, + &Out { + paths, + invalidated_dirs: report.invalidated_dirs, + touched_ancestors: report.touched_ancestors, + }, + )?; + writeln!(stdout)?; + } else { + println!( + "Invalidated {} dir(s) ({} ancestor(s) marked stale).", + report.invalidated_dirs, report.touched_ancestors + ); + } + } + Command::Cache { action } => match action { + CacheAction::Status { json } => { + let stats = scanner.cache_stats()?; + if *json { + let mut stdout = io::stdout().lock(); + serde_json::to_writer_pretty(&mut stdout, &stats)?; + writeln!(stdout)?; + } else { + println!("mode: {:?}", scanner.active_mode()); + if let Some(path) = &stats.db_path { + println!("db_path: {}", path.display()); + } + println!("db_size: {}", human_bytes(stats.db_bytes)); + println!("hosts: {}", stats.hosts); + println!("indexed_dirs: {}", stats.indexed_dirs); + println!("chunks: {}", stats.chunks); + } + } + CacheAction::Clear { json } => { + scanner.clear_cache()?; + if *json { + println!(r#"{{"cleared":true}}"#); + } else { + println!("Cache cleared."); + } + } + CacheAction::Prune { older_than, json } => { + let pruned = scanner.prune_cache(*older_than)?; + if *json { + println!(r#"{{"pruned_chunks":{pruned}}}"#); + } else { + println!("Pruned {pruned} expired chunk(s)."); + } + } + }, + } + Ok(()) +} + +fn print_plain_summary( + snapshot: &disktree_scanner::ScanSnapshot, + apparent: bool, + include_hidden: bool, + top_n: usize, +) -> io::Result<()> { + let arena = &snapshot.arena; + let root = arena.node(arena.root()); + let total = if apparent { + root.apparent_bytes + } else { + root.allocated_bytes + }; + let now = disktree_scanner::unix_now(); + let freshness_label = match &snapshot.freshness { + Freshness::Fresh { newest_at, .. } => { + format!("cached {}", human_age(now.saturating_sub(*newest_at))) + } + Freshness::Stale { newest_at, .. } => { + format!("stale {}", human_age(now.saturating_sub(*newest_at))) + } + Freshness::Partial { .. } => "partial".to_owned(), + Freshness::Live { .. } => "live".to_owned(), + }; + + let mut stdout = io::BufWriter::new(io::stdout().lock()); + writeln!( + stdout, + "{} {} ({} files, {} dirs, {}, {} ms)", + human_bytes(total), + arena.root_path().display(), + root.files, + root.dirs, + freshness_label, + snapshot.stats.duration_ms, + )?; + + for id in arena + .children(arena.root()) + .filter(|&kid| include_hidden || !arena.node(kid).hidden()) + .take(top_n) + { + let node = arena.node(id); + let bytes = if apparent { + node.apparent_bytes + } else { + node.allocated_bytes + }; + let suffix = if node.is_dir() { "/" } else { "" }; + writeln!( + stdout, + " {:>10} {}{suffix}", + human_bytes(bytes), + arena.name(id), + )?; + } + stdout.flush() +} diff --git a/crates/disktree-cli/src/tui.rs b/crates/disktree-cli/src/tui.rs new file mode 100644 index 0000000..dfc48a6 --- /dev/null +++ b/crates/disktree-cli/src/tui.rs @@ -0,0 +1,1047 @@ +//! Interactive Ratatui terminal UI with instant SWR rendering, per-subtree +//! freshness badges (`fresh` / `stale` / `updating`), and click/enter +//! priority-interruptible revalidation. + +use std::io; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use crossterm::event::{ + self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, +}; +use crossterm::execute; +use crossterm::terminal::{ + EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, + enable_raw_mode, +}; +use disktree_scanner::{ + ActiveStorageMode, FallbackReason, Freshness, Metric, NodeId, ScanEvent, + ScanOptions, ScanSession, ScanSnapshot, ScanStats, SpaceInfo, + SubtreeStatus, TreeArena, unix_now, +}; +use ratatui::backend::CrosstermBackend; +use ratatui::layout::{Constraint, Direction, Layout, Rect}; +use ratatui::style::{Color, Modifier, Style}; +use ratatui::text::{Line, Span}; +use ratatui::widgets::{ + Block, Borders, Clear, Gauge, Paragraph, Row, Table, TableState, +}; +use ratatui::{Frame, Terminal}; +use rustc_hash::FxHashSet; + +use crate::format::{human_age, human_bytes, usage_bar}; + +/// Sort key for the directory table. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum SortBy { + #[default] + Size, + Files, + Modified, + Name, +} + +impl SortBy { + const fn next(self) -> Self { + match self { + Self::Size => Self::Files, + Self::Files => Self::Modified, + Self::Modified => Self::Name, + Self::Name => Self::Size, + } + } + + const fn label(self) -> &'static str { + match self { + Self::Size => "size", + Self::Files => "files", + Self::Modified => "mtime", + Self::Name => "name", + } + } +} + +/// Interactive application state (decoupled from terminal I/O for unit tests). +pub struct App { + pub root_path: PathBuf, + pub arena: Option, + /// Path of the currently viewed directory (tracked by path so live arena + /// refreshes keep the user in the exact same directory!). + pub current_path: PathBuf, + pub freshness: Option, + pub stats: ScanStats, + pub storage_mode: ActiveStorageMode, + pub fallback_reason: Option, + pub space: Option, + pub options: ScanOptions, + pub sort_by: SortBy, + pub revalidating: bool, + pub active_scan_path: Option, + pub updating_paths: FxHashSet, + pub marks: FxHashSet, + pub filter_mode: bool, + pub filter_text: String, + pub show_help: bool, + pub status_message: Option, + pub selected: usize, + pub export_on_exit: bool, + pub should_quit: bool, + pub tick: usize, +} + +impl App { + pub fn new( + root_path: PathBuf, + options: ScanOptions, + storage_mode: ActiveStorageMode, + fallback_reason: Option, + space: Option, + ) -> Self { + Self { + current_path: root_path.clone(), + root_path, + arena: None, + freshness: None, + stats: ScanStats::default(), + storage_mode, + fallback_reason, + space, + options, + sort_by: SortBy::Size, + revalidating: true, + active_scan_path: None, + updating_paths: FxHashSet::default(), + marks: FxHashSet::default(), + filter_mode: false, + filter_text: String::new(), + show_help: false, + status_message: None, + selected: 0, + export_on_exit: false, + should_quit: false, + tick: 0, + } + } + + /// Apply an incoming [`ScanEvent`] from `disktree-scanner`. + pub fn apply_event(&mut self, event: ScanEvent) { + match event { + ScanEvent::Snapshot(snap) => self.apply_snapshot(snap), + ScanEvent::SubtreeUpdating { path, .. } => { + self.updating_paths.insert(path.clone()); + self.revalidating = true; + self.active_scan_path = Some(path); + } + ScanEvent::SubtreeRefreshed { + path, + arena: sub, + scanned_at, + .. + } => { + self.updating_paths.remove(&path); + if let Some(main_arena) = &mut self.arena { + if path == main_arena.root_path() { + *main_arena = (*sub).clone(); + self.freshness = Some(Freshness::Live { scanned_at }); + } else if let Ok(rel) = + path.strip_prefix(main_arena.root_path()) + { + let parts: Vec = rel + .components() + .map(|c| { + c.as_os_str().to_string_lossy().into_owned() + }) + .collect(); + if let Some(target_id) = main_arena + .find_relative(parts.iter().map(String::as_str)) + { + main_arena.replace_node_contents(target_id, &sub); + main_arena.aggregate( + self.options.dedup_hardlinks, + self.options.include_hidden, + ); + main_arena + .sort_children(self.options.byte_metric()); + } + } + self.clamp_selection(); + } else { + self.arena = Some((*sub).clone()); + } + self.status_message = + Some(format!("Refreshed {}", path.display())); + } + ScanEvent::Progress { stats, active_path } => { + self.stats = stats; + self.active_scan_path = active_path; + } + ScanEvent::StorageFallback { to, reason, .. } => { + self.storage_mode = to; + self.fallback_reason = Some(reason); + } + ScanEvent::Error { message } => { + self.status_message = Some(format!("Error: {message}")); + } + ScanEvent::Finished => { + self.revalidating = false; + self.active_scan_path = None; + self.updating_paths.clear(); + } + } + } + + fn apply_snapshot(&mut self, snap: ScanSnapshot) { + let mut arena = (*snap.arena).clone(); + arena.aggregate( + self.options.dedup_hardlinks, + self.options.include_hidden, + ); + arena.sort_children(self.options.byte_metric()); + self.revalidating = !matches!( + snap.freshness, + Freshness::Fresh { .. } | Freshness::Live { .. } + ); + self.freshness = Some(snap.freshness); + self.stats = snap.stats; + self.storage_mode = snap.storage_mode; + self.fallback_reason = snap.fallback_reason; + self.arena = Some(arena); + self.clamp_selection(); + } + + /// Resolve `self.current_path` to its [`NodeId`] in the active arena. + pub fn current_node_id(&self) -> Option { + let arena = self.arena.as_ref()?; + if self.current_path == arena.root_path() { + return Some(arena.root()); + } + let rel = self.current_path.strip_prefix(arena.root_path()).ok()?; + let parts: Vec = rel + .components() + .map(|c| c.as_os_str().to_string_lossy().into_owned()) + .collect(); + arena + .find_relative(parts.iter().map(String::as_str)) + .or_else(|| Some(arena.root())) + } + + /// Visible, filtered, sorted child [`NodeId`]s for the current directory. + pub fn visible_children(&self) -> Vec { + let Some(arena) = &self.arena else { + return Vec::new(); + }; + let Some(cur) = self.current_node_id() else { + return Vec::new(); + }; + let needle = self.filter_text.trim().to_ascii_lowercase(); + let mut kids: Vec = arena + .children(cur) + .filter(|&id| { + let node = arena.node(id); + if !self.options.include_hidden && node.hidden() { + return false; + } + if !needle.is_empty() + && !arena.name(id).to_ascii_lowercase().contains(&needle) + { + return false; + } + true + }) + .collect(); + + let metric = self.active_metric(); + kids.sort_unstable_by(|&a, &b| { + let na = arena.node(a); + let nb = arena.node(b); + match self.sort_by { + SortBy::Size => nb + .value(metric) + .cmp(&na.value(metric)) + .then_with(|| arena.name(a).cmp(arena.name(b))), + SortBy::Files => nb + .files + .cmp(&na.files) + .then_with(|| arena.name(a).cmp(arena.name(b))), + SortBy::Modified => nb + .modified + .cmp(&na.modified) + .then_with(|| arena.name(a).cmp(arena.name(b))), + SortBy::Name => arena.name(a).cmp(arena.name(b)), + } + }); + kids + } + + const fn active_metric(&self) -> Metric { + if self.options.apparent_size { + Metric::ApparentBytes + } else { + Metric::Bytes + } + } + + fn clamp_selection(&mut self) { + let count = self.visible_children().len(); + if count == 0 { + self.selected = 0; + } else if self.selected >= count { + self.selected = count - 1; + } + } + + /// Handle a single keystroke, returning an optional path to immediately + /// prioritize in the scanner. + pub fn handle_key(&mut self, key: KeyEvent) -> Option { + if key.kind != KeyEventKind::Press { + return None; + } + + if key.modifiers.contains(KeyModifiers::CONTROL) + && key.code == KeyCode::Char('c') + { + self.should_quit = true; + return None; + } + + if self.show_help { + if matches!(key.code, KeyCode::Esc | KeyCode::Char('?' | 'q')) { + self.show_help = false; + } + return None; + } + + if self.filter_mode { + match key.code { + KeyCode::Esc => { + self.filter_mode = false; + self.filter_text.clear(); + self.clamp_selection(); + } + KeyCode::Enter => { + self.filter_mode = false; + self.clamp_selection(); + } + KeyCode::Backspace => { + self.filter_text.pop(); + self.clamp_selection(); + } + KeyCode::Char(c) => { + self.filter_text.push(c); + self.clamp_selection(); + } + _ => {} + } + return None; + } + + match key.code { + KeyCode::Char('q') => { + self.should_quit = true; + } + KeyCode::Char('?') => { + self.show_help = true; + } + KeyCode::Char('j') | KeyCode::Down => { + let len = self.visible_children().len(); + if len > 0 && self.selected + 1 < len { + self.selected += 1; + } + } + KeyCode::Char('k') | KeyCode::Up => { + self.selected = self.selected.saturating_sub(1); + } + KeyCode::Char('g') | KeyCode::Home => { + self.selected = 0; + } + KeyCode::Char('G') | KeyCode::End => { + let len = self.visible_children().len(); + self.selected = len.saturating_sub(1); + } + KeyCode::Enter | KeyCode::Char('l') | KeyCode::Right => { + let kids = self.visible_children(); + if let Some(&child_id) = kids.get(self.selected) + && let Some(arena) = &self.arena + && arena.node(child_id).is_dir() + { + let target = arena.path_of(child_id); + let status = arena.node(child_id).status(); + self.current_path.clone_from(&target); + self.filter_text.clear(); + self.selected = 0; + // Priority-interrupt background refresh when descending + // into a stale or unscanned directory! + if matches!( + status, + SubtreeStatus::Stale { .. } | SubtreeStatus::Unscanned + ) { + self.updating_paths.insert(target.clone()); + return Some(target); + } + } + } + KeyCode::Backspace | KeyCode::Char('h') | KeyCode::Left => { + if self.current_path != self.root_path + && let Some(parent) = self.current_path.parent() + { + let prev_path = self.current_path.clone(); + self.current_path = parent.to_path_buf(); + self.filter_text.clear(); + // Re-select the directory we just climbed out of. + let kids = self.visible_children(); + if let Some(arena) = &self.arena { + self.selected = kids + .iter() + .position(|&id| arena.path_of(id) == prev_path) + .unwrap_or(0); + } else { + self.selected = 0; + } + } + } + KeyCode::Char('a') => { + self.options.apparent_size = !self.options.apparent_size; + if let Some(arena) = &mut self.arena { + arena.sort_children(self.options.byte_metric()); + } + self.status_message = Some(if self.options.apparent_size { + "Showing apparent size (zero rescan)".to_owned() + } else { + "Showing allocated disk blocks (zero rescan)".to_owned() + }); + } + KeyCode::Char('H') => { + self.options.include_hidden = !self.options.include_hidden; + if let Some(arena) = &mut self.arena { + arena.aggregate( + self.options.dedup_hardlinks, + self.options.include_hidden, + ); + arena.sort_children(self.options.byte_metric()); + } + self.clamp_selection(); + self.status_message = Some(if self.options.include_hidden { + "Showing hidden entries".to_owned() + } else { + "Hiding dotfiles".to_owned() + }); + } + KeyCode::Char('s') => { + self.sort_by = self.sort_by.next(); + self.status_message = + Some(format!("Sorted by {}", self.sort_by.label())); + } + KeyCode::Char('/') => { + self.filter_mode = true; + } + KeyCode::Char(' ') => { + let kids = self.visible_children(); + if let Some(&child_id) = kids.get(self.selected) + && let Some(arena) = &self.arena + { + let path = arena.path_of(child_id); + if !self.marks.remove(&path) { + self.marks.insert(path); + } + } + } + KeyCode::Char('e') => { + if self.marks.is_empty() { + self.status_message = Some( + "No paths marked (press Space to mark)".to_owned(), + ); + } else { + self.export_on_exit = true; + self.should_quit = true; + } + } + KeyCode::Char('r') => { + let kids = self.visible_children(); + let target = if let Some(&child_id) = kids.get(self.selected) + && let Some(arena) = &self.arena + && arena.node(child_id).is_dir() + { + arena.path_of(child_id) + } else { + self.current_path.clone() + }; + self.updating_paths.insert(target.clone()); + self.status_message = + Some(format!("Prioritizing refresh: {}", target.display())); + return Some(target); + } + KeyCode::Char('R') => { + let target = self.root_path.clone(); + self.updating_paths.insert(target.clone()); + self.status_message = Some("Refreshing full root…".to_owned()); + return Some(target); + } + _ => {} + } + None + } + + /// Render the current state to a Ratatui [`Frame`]. + pub fn draw(&self, frame: &mut Frame<'_>) { + let chunks = Layout::default() + .direction(Direction::Vertical) + .constraints([ + Constraint::Length(3), + Constraint::Length(1), + Constraint::Min(5), + Constraint::Length(2), + ]) + .split(frame.area()); + + self.draw_header(frame, chunks[0]); + self.draw_space_bar(frame, chunks[1]); + self.draw_table(frame, chunks[2]); + self.draw_footer(frame, chunks[3]); + + if self.show_help { + draw_help_overlay(frame, frame.area()); + } + } + + fn draw_header(&self, frame: &mut Frame<'_>, area: Rect) { + let now = unix_now(); + let spinner = + ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"][self.tick % 10]; + + let (badge_text, badge_color) = if !self.updating_paths.is_empty() { + (format!("{spinner} UPDATING"), Color::Cyan) + } else if self.revalidating { + match &self.freshness { + Some(Freshness::Stale { newest_at, .. }) => ( + format!( + "{spinner} STALE ({}) · REVALIDATING", + human_age(now.saturating_sub(*newest_at)) + ), + Color::Yellow, + ), + Some(Freshness::Partial { .. }) => { + (format!("{spinner} PARTIAL · SCANNING"), Color::Yellow) + } + _ => (format!("{spinner} SCANNING"), Color::Cyan), + } + } else { + match &self.freshness { + Some(Freshness::Fresh { newest_at, .. }) => ( + format!( + "CACHED · {}", + human_age(now.saturating_sub(*newest_at)) + ), + Color::Green, + ), + Some(Freshness::Live { .. }) => { + ("LIVE".to_owned(), Color::Green) + } + Some(Freshness::Stale { newest_at, .. }) => ( + format!( + "STALE · {}", + human_age(now.saturating_sub(*newest_at)) + ), + Color::Yellow, + ), + _ => ("READY".to_owned(), Color::DarkGray), + } + }; + + let storage_label = match (&self.storage_mode, &self.fallback_reason) { + (ActiveStorageMode::Persistent, _) => "db".to_owned(), + (ActiveStorageMode::TempDb, _) => "temp-db".to_owned(), + (ActiveStorageMode::InMemory, Some(reason)) => { + format!("in-memory ({reason:?})") + } + (ActiveStorageMode::InMemory, None) => "in-memory".to_owned(), + (ActiveStorageMode::Streaming, _) => "stream".to_owned(), + }; + + let mode_label = if self.options.apparent_size { + "apparent" + } else { + "blocks" + }; + + let title = Line::from(vec![ + Span::styled( + " disktree-cli ", + Style::default() + .fg(Color::Black) + .bg(Color::Cyan) + .add_modifier(Modifier::BOLD), + ), + Span::raw(" "), + Span::styled( + self.current_path.display().to_string(), + Style::default().add_modifier(Modifier::BOLD), + ), + Span::raw(" "), + Span::styled( + format!("[{badge_text}]"), + Style::default() + .fg(badge_color) + .add_modifier(Modifier::BOLD), + ), + Span::raw(" "), + Span::styled( + format!( + "{mode_label} · sort:{} · {storage_label}", + self.sort_by.label() + ), + Style::default().fg(Color::DarkGray), + ), + ]); + + let current_summary = if let Some(arena) = &self.arena + && let Some(cur) = self.current_node_id() + { + let node = arena.node(cur); + let bytes = if self.options.apparent_size { + node.apparent_bytes + } else { + node.allocated_bytes + }; + format!( + " {} · {} files · {} dirs · {} marked", + human_bytes(bytes), + node.files, + node.dirs, + self.marks.len() + ) + } else { + " Scanning filesystem…".to_owned() + }; + + let header = Paragraph::new(current_summary) + .block(Block::default().borders(Borders::ALL).title(title)); + frame.render_widget(header, area); + } + + fn draw_space_bar(&self, frame: &mut Frame<'_>, area: Rect) { + if let Some(space) = self.space { + let ratio = f64::from(space.used_fraction()).clamp(0.0, 1.0); + let label = format!( + "Volume: {} used / {} total ({} available)", + human_bytes(space.used()), + human_bytes(space.total), + human_bytes(space.available), + ); + let color = if ratio > 0.90 { + Color::Red + } else if ratio > 0.75 { + Color::Yellow + } else { + Color::Blue + }; + let gauge = Gauge::default() + .ratio(ratio) + .label(label) + .gauge_style(Style::default().fg(color).bg(Color::DarkGray)); + frame.render_widget(gauge, area); + } + } + + fn draw_table(&self, frame: &mut Frame<'_>, area: Rect) { + let Some(arena) = &self.arena else { + let placeholder = Paragraph::new( + "Scanning… (subsequent runs within 15m load from cache in milliseconds)", + ) + .block(Block::default().borders(Borders::ALL).title("Entries")); + frame.render_widget(placeholder, area); + return; + }; + + let cur = self.current_node_id().unwrap_or_else(|| arena.root()); + let parent_total = arena.node(cur).value(self.active_metric()).max(1); + let kids = self.visible_children(); + let now = unix_now(); + + let rows: Vec> = kids + .iter() + .map(|&id| { + let node = arena.node(id); + let path = arena.path_of(id); + let marked = if self.marks.contains(&path) { "*" } else { " " }; + let bytes = if self.options.apparent_size { + node.effective_apparent_bytes() + } else { + node.effective_allocated_bytes() + }; + let frac = node.value(self.active_metric()) as f64 + / parent_total as f64; + let pct = format!("{:>5.1}%", frac * 100.0); + let bar = usage_bar(frac, 14); + + let (status_str, status_color) = if !node.is_dir() { + (String::new(), Color::DarkGray) + } else if self.updating_paths.contains(&path) { + ("updating…".to_owned(), Color::Cyan) + } else { + match node.status() { + SubtreeStatus::Fresh { scanned_at } => ( + format!( + "fresh {}", + human_age(now.saturating_sub(scanned_at)) + ), + Color::Green, + ), + SubtreeStatus::Stale { scanned_at } => ( + format!( + "stale {}", + human_age(now.saturating_sub(scanned_at)) + ), + Color::Yellow, + ), + SubtreeStatus::Updating { .. } => { + ("updating…".to_owned(), Color::Cyan) + } + SubtreeStatus::Unscanned => { + ("unscanned".to_owned(), Color::DarkGray) + } + } + }; + + let mut display_name = arena.name(id).to_owned(); + if node.is_dir() { + display_name.push('/'); + } + if node.read_error() { + display_name.push_str(" [unreadable]"); + } + + let name_style = if node.read_error() { + Style::default().fg(Color::Red) + } else if node.hidden() { + Style::default().fg(Color::DarkGray) + } else if node.is_dir() { + Style::default() + .fg(Color::Cyan) + .add_modifier(Modifier::BOLD) + } else { + Style::default() + }; + + Row::new(vec![ + Span::styled( + marked, + Style::default() + .fg(Color::Yellow) + .add_modifier(Modifier::BOLD), + ), + Span::raw(format!("{:>10}", human_bytes(bytes))), + Span::styled(pct, Style::default().fg(Color::DarkGray)), + Span::styled(bar, Style::default().fg(Color::Blue)), + Span::styled( + format!("{:>7}", node.files), + Style::default().fg(Color::DarkGray), + ), + Span::styled(status_str, Style::default().fg(status_color)), + Span::styled(display_name, name_style), + ]) + }) + .collect(); + + let header = Row::new(vec![ + " ", + "Size", + "Share", + "Usage", + "Files", + "Freshness", + "Name", + ]) + .style( + Style::default() + .fg(Color::White) + .add_modifier(Modifier::BOLD), + ); + + let title = if self.filter_mode { + format!("Filter: {}_", self.filter_text) + } else if !self.filter_text.is_empty() { + format!("Entries (filter: {})", self.filter_text) + } else { + format!("Entries ({})", kids.len()) + }; + + let table = Table::new( + rows, + [ + Constraint::Length(1), + Constraint::Length(11), + Constraint::Length(7), + Constraint::Length(15), + Constraint::Length(8), + Constraint::Length(16), + Constraint::Min(16), + ], + ) + .header(header) + .block(Block::default().borders(Borders::ALL).title(title)) + .row_highlight_style( + Style::default() + .bg(Color::DarkGray) + .add_modifier(Modifier::BOLD), + ); + + let mut table_state = TableState::default(); + if !kids.is_empty() { + table_state.select(Some(self.selected)); + } + frame.render_stateful_widget(table, area, &mut table_state); + } + + fn draw_footer(&self, frame: &mut Frame<'_>, area: Rect) { + let line1 = if let Some(active) = &self.active_scan_path { + Line::from(vec![ + Span::styled( + format!( + "walked:{} skipped:{} err:{} ", + self.stats.walked_dirs, + self.stats.skipped_fresh_dirs, + self.stats.errors, + ), + Style::default().fg(Color::Cyan), + ), + Span::styled( + active.display().to_string(), + Style::default().fg(Color::DarkGray), + ), + ]) + } else if let Some(msg) = &self.status_message { + Line::from(Span::styled( + msg.as_str(), + Style::default().fg(Color::Yellow), + )) + } else { + Line::from(Span::styled( + format!( + "walked:{} skipped-fresh:{} ({} ms)", + self.stats.walked_dirs, + self.stats.skipped_fresh_dirs, + self.stats.duration_ms + ), + Style::default().fg(Color::DarkGray), + )) + }; + + let line2 = Line::from(Span::styled( + "j/k move · Enter/l open · h/Bksp up · r refresh · R full · a apparent · H hidden · s sort · / filter · Space mark · e export · ? help · q quit", + Style::default().fg(Color::DarkGray), + )); + + frame.render_widget(Paragraph::new(vec![line1, line2]), area); + } +} + +fn draw_help_overlay(frame: &mut Frame<'_>, area: Rect) { + let width = 62u16.min(area.width.saturating_sub(4)); + let height = 16u16.min(area.height.saturating_sub(4)); + let rect = Rect { + x: area.x + (area.width.saturating_sub(width)) / 2, + y: area.y + (area.height.saturating_sub(height)) / 2, + width, + height, + }; + frame.render_widget(Clear, rect); + let help = Paragraph::new(vec![ + Line::from(" j / k / Up / Down Move selection"), + Line::from(" Enter / l / Right Descend (prioritizes stale dir)"), + Line::from(" Backspace / h / Left Ascend to parent directory"), + Line::from(" r Immediate priority refresh of dir"), + Line::from(" R Force full refresh of root"), + Line::from(" a Toggle apparent vs allocated bytes"), + Line::from(" H Toggle hidden dotfiles"), + Line::from(" s Cycle sort (size/files/mtime/name)"), + Line::from(" / Filter current directory"), + Line::from(" Space Mark / unmark path (read-only)"), + Line::from(" e Exit & print marked paths list"), + Line::from(" ? / Esc / q Close help / quit"), + ]) + .block( + Block::default() + .borders(Borders::ALL) + .title(" disktree-cli keys ") + .style(Style::default().bg(Color::Black)), + ); + frame.render_widget(help, rect); +} + +/// Run the interactive Ratatui event loop until the user quits. +/// Returns the sorted list of marked paths if the user pressed `e` to export. +pub fn run_tui( + session: &ScanSession, + root: &Path, + options: ScanOptions, + storage_mode: ActiveStorageMode, + fallback_reason: Option, + space: Option, +) -> io::Result> { + enable_raw_mode()?; + let mut stdout = io::stdout(); + execute!(stdout, EnterAlternateScreen)?; + let backend = CrosstermBackend::new(stdout); + let mut terminal = Terminal::new(backend)?; + + let mut app = App::new( + root.to_path_buf(), + options, + storage_mode, + fallback_reason, + space, + ); + + let loop_res = (|| -> io::Result<()> { + while !app.should_quit { + // Drain all ready scanner events without blocking. + while let Ok(ev) = session.try_recv() { + app.apply_event(ev); + } + app.tick = app.tick.wrapping_add(1); + terminal.draw(|frame| app.draw(frame))?; + + let poll_ms = if app.revalidating || !app.updating_paths.is_empty() + { + 33 + } else { + 120 + }; + if event::poll(Duration::from_millis(poll_ms))? + && let Event::Key(key) = event::read()? + && let Some(prio_path) = app.handle_key(key) + { + let _ = session.prioritize(&prio_path); + } + } + Ok(()) + })(); + + session.cancel(); + let _ = disable_raw_mode(); + let _ = execute!(terminal.backend_mut(), LeaveAlternateScreen); + let _ = terminal.show_cursor(); + + loop_res?; + + if app.export_on_exit { + let mut exported: Vec = app.marks.into_iter().collect(); + exported.sort(); + Ok(exported) + } else { + Ok(Vec::new()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + + use disktree_scanner::{NodeFlags, NodeKind}; + use ratatui::backend::TestBackend; + + fn sample_app() -> App { + let mut arena = TreeArena::new(PathBuf::from("/demo"), "demo"); + let stale_dir = arena.add_child( + arena.root(), + "stale_dir", + NodeKind::Directory, + 0, + 0, + 100, + NodeFlags::new(NodeKind::Directory), + ); + arena + .node_mut(stale_dir) + .set_status(SubtreeStatus::Stale { scanned_at: 10 }); + arena.add_child( + stale_dir, + "big.bin", + NodeKind::File, + 8192, + 4000, + 100, + NodeFlags::new(NodeKind::File), + ); + let mut hidden_flags = NodeFlags::new(NodeKind::File); + hidden_flags.set(NodeFlags::HIDDEN, true); + arena.add_child( + arena.root(), + ".env", + NodeKind::File, + 4096, + 20, + 100, + hidden_flags, + ); + arena.aggregate(true, true); + arena.sort_children(Metric::Bytes); + + let mut app = App::new( + PathBuf::from("/demo"), + ScanOptions::default(), + ActiveStorageMode::Persistent, + None, + Some(SpaceInfo { + total: 1_000_000, + free: 400_000, + available: 350_000, + }), + ); + app.apply_event(ScanEvent::Snapshot(ScanSnapshot { + arena: Arc::new(arena), + freshness: Freshness::Stale { + oldest_at: 10, + newest_at: 10, + stale_dirs: 1, + }, + stats: ScanStats::default(), + storage_mode: ActiveStorageMode::Persistent, + fallback_reason: None, + })); + app + } + + #[test] + fn tui_draws_frames_and_prioritizes_stale_dir_on_enter() { + let mut app = sample_app(); + let backend = TestBackend::new(100, 24); + let mut terminal = Terminal::new(backend).expect("terminal"); + + terminal.draw(|f| app.draw(f)).expect("draw initial"); + let buf = terminal.backend().buffer(); + let rendered: String = buf + .content() + .iter() + .map(ratatui::buffer::Cell::symbol) + .collect(); + assert!(rendered.contains("disktree-cli")); + assert!(rendered.contains("stale_dir/")); + + // Pressing Enter on `stale_dir` descends AND returns it for immediate + // priority revalidation! + let prio = + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert_eq!(prio, Some(PathBuf::from("/demo/stale_dir"))); + assert_eq!(app.current_path, PathBuf::from("/demo/stale_dir")); + + // Press Backspace to climb back up, toggle hidden (`H`) and apparent (`a`), + // open help (`?`), and draw again without panicking. + assert!( + app.handle_key(KeyEvent::new( + KeyCode::Backspace, + KeyModifiers::NONE + )) + .is_none() + ); + assert_eq!(app.visible_children().len(), 2); + app.handle_key(KeyEvent::new(KeyCode::Char('H'), KeyModifiers::SHIFT)); + assert_eq!(app.visible_children().len(), 1); + app.handle_key(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE)); + assert!(app.options.apparent_size); + app.handle_key(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE)); + assert!(app.show_help); + terminal.draw(|f| app.draw(f)).expect("draw help"); + } +} diff --git a/crates/disktree-cli/tests/cli.rs b/crates/disktree-cli/tests/cli.rs new file mode 100644 index 0000000..20b796b --- /dev/null +++ b/crates/disktree-cli/tests/cli.rs @@ -0,0 +1,148 @@ +//! End-to-end tests invoking the compiled `disktree-cli` binary. + +use std::fs; +use std::process::Command; + +use serde_json::Value; + +fn cli_bin() -> Command { + Command::new(env!("CARGO_BIN_EXE_disktree-cli")) +} + +#[test] +fn json_mode_caches_within_15m_and_invalidate_refreshes() { + let temp = tempfile::tempdir().expect("tempdir"); + let cache_dir = temp.path().join("cache"); + let tree_dir = temp.path().join("tree"); + let sub = tree_dir.join("sub"); + fs::create_dir_all(&sub).expect("mkdir"); + fs::write(sub.join("a.bin"), vec![1u8; 2048]).expect("write a"); + + // 1. Cold run: live scan. + let out1 = cli_bin() + .args([ + "--cache-dir", + cache_dir.to_str().unwrap(), + "--json", + "-a", + tree_dir.to_str().unwrap(), + ]) + .output() + .expect("run 1"); + assert!( + out1.status.success(), + "stderr: {}", + String::from_utf8_lossy(&out1.stderr) + ); + let doc1: Value = serde_json::from_slice(&out1.stdout).expect("json 1"); + assert_eq!(doc1["schema_version"], 1); + assert_eq!(doc1["freshness"]["status"], "live"); + assert_eq!(doc1["tree"]["apparent_bytes"], 2048); + + // 2. Warm repeat run (default 15m TTL): fresh cache hit, 0 walked dirs! + let out2 = cli_bin() + .args([ + "--cache-dir", + cache_dir.to_str().unwrap(), + "--json", + "-a", + tree_dir.to_str().unwrap(), + ]) + .output() + .expect("run 2"); + assert!(out2.status.success()); + let doc2: Value = serde_json::from_slice(&out2.stdout).expect("json 2"); + assert_eq!(doc2["freshness"]["status"], "fresh"); + assert_eq!(doc2["stats"]["walked_dirs"], 0); + assert_eq!(doc2["tree"]["apparent_bytes"], 2048); + + // 3. Delete file externally and run `disktree-cli invalidate`. + fs::remove_file(sub.join("a.bin")).expect("rm"); + let inv = cli_bin() + .args([ + "--cache-dir", + cache_dir.to_str().unwrap(), + "invalidate", + "--json", + sub.to_str().unwrap(), + ]) + .output() + .expect("invalidate"); + assert!( + inv.status.success(), + "stderr: {}", + String::from_utf8_lossy(&inv.stderr) + ); + + // 4. Next run immediately reflects 0 bytes. + let out3 = cli_bin() + .args([ + "--cache-dir", + cache_dir.to_str().unwrap(), + "--json", + "-a", + tree_dir.to_str().unwrap(), + ]) + .output() + .expect("run 3"); + assert!(out3.status.success()); + let doc3: Value = serde_json::from_slice(&out3.stdout).expect("json 3"); + assert_eq!(doc3["tree"]["apparent_bytes"], 0); + + // 5. `cache status --json` and `cache clear --json`. + let status = cli_bin() + .args([ + "--cache-dir", + cache_dir.to_str().unwrap(), + "cache", + "status", + "--json", + ]) + .output() + .expect("cache status"); + assert!(status.status.success()); + let st: Value = + serde_json::from_slice(&status.stdout).expect("status json"); + assert!(st["chunks"].as_u64().unwrap_or(0) >= 1); + + let clear = cli_bin() + .args([ + "--cache-dir", + cache_dir.to_str().unwrap(), + "cache", + "clear", + "--json", + ]) + .output() + .expect("cache clear"); + assert!(clear.status.success()); +} + +#[test] +fn streaming_mode_emits_valid_ndjson_records() { + let temp = tempfile::tempdir().expect("tempdir"); + fs::write(temp.path().join("hello.txt"), b"hello").expect("write"); + + let out = cli_bin() + .args(["--stream", temp.path().to_str().unwrap()]) + .output() + .expect("stream"); + assert!( + out.status.success(), + "stderr: {}", + String::from_utf8_lossy(&out.stderr) + ); + + let lines: Vec = String::from_utf8_lossy(&out.stdout) + .lines() + .filter(|line| !line.is_empty()) + .map(|line| serde_json::from_str(line).expect("ndjson line")) + .collect(); + assert!(lines.iter().any(|v| v["event"] == "enter_dir")); + assert!( + lines + .iter() + .any(|v| v["event"] == "entry" && v["name"] == "hello.txt") + ); + assert!(lines.iter().any(|v| v["event"] == "leave_dir")); +} diff --git a/crates/disktree-core/Cargo.toml b/crates/disktree-core/Cargo.toml index b4fc0d0..ee7719d 100644 --- a/crates/disktree-core/Cargo.toml +++ b/crates/disktree-core/Cargo.toml @@ -9,7 +9,12 @@ description = "Filesystem scanning and treemap layout for disktree" [lints] workspace = true +[features] +default = ["cache-db"] +cache-db = ["disktree-scanner/cache-db"] + [dependencies] +disktree-scanner = { path = "../disktree-scanner", default-features = false } chrono = { version = "0.4.45", default-features = false, features = ["clock", "std"] } rayon = { workspace = true } rustc-hash = { workspace = true } @@ -24,13 +29,9 @@ rustix = { version = "1.1", features = ["fs"] } [target.'cfg(windows)'.dependencies] # The Recycle Bin, through the shell's own file operation. trash = { version = "5.2.9", default-features = false, features = ["coinit_apartmentthreaded"] } -winapi-util = "0.1.11" windows-sys = { version = "0.61", features = [ "Win32_Foundation", "Win32_Storage_FileSystem", - "Win32_System_Com", - "Win32_UI_Shell", - "Win32_UI_WindowsAndMessaging", ] } # The system trash, through NSFileManager: what Finder's Move to Trash does, @@ -41,7 +42,3 @@ trash = { version = "5.2.9", default-features = false } [dev-dependencies] tempfile = "3" - -# CPU-only sampling; the GUI dependency graph already pins this version. -[target.'cfg(any(target_os = "macos", target_os = "linux"))'.dependencies] -sysinfo = { version = "0.31.4", default-features = false, features = ["system"] } diff --git a/crates/disktree-core/examples/scan_workers.rs b/crates/disktree-core/examples/scan_workers.rs deleted file mode 100644 index 8b79ecc..0000000 --- a/crates/disktree-core/examples/scan_workers.rs +++ /dev/null @@ -1,60 +0,0 @@ -//! One scan of `ROOT` with a fixed pool of `WORKERS`, the way a Power -//! Efficiency preset runs it, reported as one JSON line. Driven by -//! `scripts/bench-scan-workers.py`, which times it and samples the machine. -//! -//! ```sh -//! cargo run --release -p disktree-core --example scan_workers -- ROOT WORKERS -//! ``` - -use std::path::PathBuf; -use std::time::{Duration, Instant}; - -use disktree_core::scan::{ScanHandle, ScanOptions}; -use disktree_core::scan_threads::ScanThreads; - -fn main() { - let mut args = std::env::args_os().skip(1); - let (Some(root), Some(workers)) = (args.next(), args.next()) else { - eprintln!("usage: scan_workers ROOT WORKERS"); - std::process::exit(2); - }; - let Some(workers) = workers - .to_str() - .and_then(|value| value.parse::().ok()) - .filter(|&value| value > 0) - else { - eprintln!("WORKERS must be a positive integer"); - std::process::exit(2); - }; - let options = ScanOptions { - // What `PowerEfficiency::policy` sets: a fixed pool, no governor. - threads: ScanThreads { - max_threads: workers, - adaptive: false, - system_cpu_limit: None, - ..ScanThreads::default() - }, - ..ScanOptions::default() - }; - let start = Instant::now(); - let handle = ScanHandle::spawn(PathBuf::from(root), options); - let node = loop { - if let Some(result) = handle.poll() { - match result { - Ok(node) => break node, - Err(error) => { - eprintln!("scan failed: {error}"); - std::process::exit(1); - } - } - } - std::thread::sleep(Duration::from_millis(20)); - }; - let elapsed = start.elapsed().as_secs_f64(); - let progress = handle.progress.snapshot(); - println!( - "{{\"workers\":{workers},\"pool\":{},\"elapsed\":{elapsed},\ - \"files\":{},\"dirs\":{},\"bytes\":{},\"errors\":{}}}", - progress.threads, node.files, node.dirs, node.bytes, progress.errors - ); -} diff --git a/crates/disktree-core/src/lib.rs b/crates/disktree-core/src/lib.rs index aa9e47c..66507a9 100644 --- a/crates/disktree-core/src/lib.rs +++ b/crates/disktree-core/src/lib.rs @@ -12,10 +12,6 @@ pub mod export; pub mod filter; pub mod identity; pub mod insights; -#[cfg(target_os = "macos")] -mod macos; -#[cfg(windows)] -mod mft; pub mod path_style; pub mod payload; pub mod remote; @@ -25,10 +21,9 @@ mod remote_walk; pub mod removal; pub mod scan; pub mod scan_preview; -pub mod scan_threads; pub mod size; pub mod space; pub mod tree; pub mod treemap; #[cfg(windows)] -mod windows; +pub(crate) use disktree_scanner::windows; diff --git a/crates/disktree-core/src/remote_walk.rs b/crates/disktree-core/src/remote_walk.rs index 8bbe425..d67ff28 100644 --- a/crates/disktree-core/src/remote_walk.rs +++ b/crates/disktree-core/src/remote_walk.rs @@ -1,35 +1,23 @@ -//! Bounded-memory SSH traversal. No Node, arena, child vector or sort: -//! the receiver owns the tree; the helper retains only its open ancestors. -use std::fs::{self, ReadDir}; -use std::io::{self, Write}; -use std::os::unix::fs::MetadataExt as _; -use std::path::{Path, PathBuf}; +//! Bounded-memory SSH wire serializer backed by `disktree-scanner`'s streaming +//! walker. No Node, arena, child vector or sort: the receiver owns the tree; +//! the helper retains only its open ancestors. -use rustc_hash::{FxHashMap, FxHashSet}; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; +use std::time::Instant; + +use disktree_scanner::{ + NodeKind, StreamConfig, StreamItem, stream_walk_with_config, +}; +use rustc_hash::FxHashSet; use crate::remote::{Record, send}; -use crate::scan::{ScanOptions, measure, modified_seconds}; +use crate::scan::ScanOptions; // Legacy peers require helper-side accounting. Modern clients explicitly // negotiate desktop de-duplication and never populate this table. const MAX_PENDING_LINKS: usize = 65_536; -struct Frame { - entries: Option, - record: Record, -} - -impl Frame { - fn open(path: &Path, name: String) -> Self { - let entries = fs::read_dir(path); - let failed = entries.is_err(); - Self { - entries: entries.ok(), - record: Record(name, 0, 0, 0, 0, failed, 0), - } - } -} - pub fn stream( root: &Path, options: &ScanOptions, @@ -40,7 +28,8 @@ pub fn stream( ) -> io::Result<()> { if options.follow_links || !options.one_filesystem { return Err(io::Error::other( - "Remote streaming scans never follow symlinks or cross mounts; select that mount as a separate scan root.", + "Remote streaming scans never follow symlinks or cross mounts; \ + select that mount as a separate scan root.", )); } // Require a table, not just st_dev: a bind mount can have the same dev. @@ -70,139 +59,132 @@ fn stream_with_boundaries( client_dedup: bool, live_tree: bool, ) -> io::Result<()> { - if live_tree { - send(out, &serde_json::json!({"enter": ""}))?; - } - let device = fs::metadata(root)?.dev(); - let mut frames = vec![Frame::open(root, "root".into())]; - // Only the legacy wire mode needs a table. Modern sessions emit each - // hardlink's identity directly and leave this map empty. - let mut links = FxHashMap::<(u64, u64), u64>::default(); - let mut directory = root.to_path_buf(); - let mut heartbeat = None::; - while let Some(frame) = frames.last_mut() { + let scanner_opts = options.to_scanner(); + let config = StreamConfig { + excluded: excluded.clone(), + dedup_in_walker: !client_dedup, + max_pending_links: (!client_dedup).then_some(MAX_PENDING_LINKS), + skip_lossy_names: true, + }; + let mut heartbeat = None::; + let maybe_heartbeat = |dir: &Path, + heartbeat: &mut Option, + out: &mut dyn Write| + -> io::Result<()> { if live_progress && heartbeat.is_none_or(|last| { last.elapsed() >= crate::remote_progress::INTERVAL }) { - send(out, &serde_json::json!({"directory": directory}))?; + serde_json::to_writer( + &mut *out, + &serde_json::json!({"directory": dir}), + ) + .map_err(io::Error::other)?; + out.write_all(b"\n")?; // Flush on a timer even when few tree records fill the buffer. out.flush()?; - heartbeat = Some(std::time::Instant::now()); + *heartbeat = Some(Instant::now()); } - let entry = match frame.entries.as_mut().and_then(Iterator::next) { - None => { - let frame = frames.pop().expect("frame checked above"); - send(out, &frame.record)?; - directory.pop(); - continue; - } - Some(Err(_)) => { - frame.record.5 = true; - continue; - } - Some(Ok(entry)) => entry, - }; - let name = entry.file_name(); - let Some(name) = name.to_str() else { - // A replacement character must never become a deletable path. - frame.record.5 = true; - continue; - }; - if !options.include_hidden && name.starts_with('.') { - continue; - } - let path = entry.path(); - // Before metadata or read_dir: do not trigger an automount. - if excluded.contains(&path) { - continue; - } - let Ok(meta) = fs::symlink_metadata(&path) else { - frame.record.5 = true; - continue; - }; - if meta.dev() != device { - continue; - } - if meta.is_dir() { - if options.max_depth.is_some_and(|limit| frames.len() > limit) { - continue; - } - frames.last_mut().expect("parent exists").record.6 += 1; - directory.clone_from(&path); - if live_tree { - send(out, &serde_json::json!({"enter": name}))?; - } - frames.push(Frame::open(&path, name.to_owned())); - continue; - } - let kind = if meta.is_file() { - 1 - } else if meta.is_symlink() { - 2 - } else { - 3 - }; - let mut bytes = if kind == 3 { - 0 - } else { - measure(&meta, options.apparent_size) - }; - let hardlinked = - options.dedup_hardlinks && meta.is_file() && meta.nlink() > 1; - if hardlinked && !client_dedup { - let identity = (meta.dev(), meta.ino()); - if let Some(remaining) = links.get_mut(&identity) { - bytes = 0; - *remaining -= 1; - if *remaining == 0 { - links.remove(&identity); + Ok(()) + }; + + stream_walk_with_config(root, &scanner_opts, &config, None, |item| { + match item { + StreamItem::EnterDir { + path, name, depth, .. + } => { + maybe_heartbeat(&path, &mut heartbeat, out)?; + if live_tree { + let wire_name = if depth == 0 { "" } else { name.as_str() }; + send(out, &serde_json::json!({"enter": wire_name}))?; } - } else { - if links.len() >= MAX_PENDING_LINKS { - return Err(io::Error::other(format!( - "remote hardlink tracking limit reached at {}; scan a smaller root", - path.display() - ))); + } + StreamItem::LeaveDir { + name, + depth, + read_error, + direct_children, + .. + } => { + let wire_name = + if depth == 0 { "root".to_owned() } else { name }; + let record = Record( + wire_name, + 0, + 0, + 0, + 0, + read_error, + direct_children as usize, + ); + send(out, &record)?; + } + StreamItem::Entry { + path, + name, + kind, + allocated_bytes, + apparent_bytes, + modified, + hardlink, + .. + } => { + if let Some(parent) = path.parent() { + maybe_heartbeat(parent, &mut heartbeat, out)?; + } + let wire_kind = match kind { + NodeKind::Directory => 0, + NodeKind::File => 1, + NodeKind::Symlink => 2, + NodeKind::Other => 3, + }; + let bytes = if wire_kind == 3 { + 0 + } else if options.apparent_size { + apparent_bytes + } else { + allocated_bytes + }; + let record = Record( + name, + wire_kind, + bytes, + u64::from(kind == NodeKind::File), + modified, + false, + 0, + ); + if client_dedup + && options.dedup_hardlinks + && let Some(link) = hardlink + { + #[derive(serde::Serialize)] + struct Linked<'a> { + link: (u64, u64), + entry: &'a Record, + } + send( + out, + &Linked { + link, + entry: &record, + }, + )?; + } else { + send(out, &record)?; } - links.insert(identity, meta.nlink() - 1); } + StreamItem::Error { .. } => {} } - let record = Record( - name.to_owned(), - kind, - bytes, - u64::from(meta.is_file()), - modified_seconds(&meta), - false, - 0, - ); - if hardlinked && client_dedup { - // The desktop already owns the tree and its compact identity - // index. The server retains no per-file state in this mode. - #[derive(serde::Serialize)] - struct Linked<'a> { - link: (u64, u64), - entry: &'a Record, - } - send( - out, - &Linked { - link: (meta.dev(), meta.ino()), - entry: &record, - }, - )?; - } else { - send(out, &record)?; - } - frames.last_mut().expect("parent exists").record.6 += 1; - } - Ok(()) + Ok(()) + }) } #[cfg(test)] mod tests { + use std::fs; + use super::*; fn records( diff --git a/crates/disktree-core/src/removal.rs b/crates/disktree-core/src/removal.rs index 43f8bdf..d6b862a 100644 --- a/crates/disktree-core/src/removal.rs +++ b/crates/disktree-core/src/removal.rs @@ -1739,7 +1739,7 @@ mod tests { one_filesystem: false, ..crate::scan::ScanOptions::default() }; - let tree = crate::scan::scan(scan_root, options.clone()).expect("scan"); + let tree = crate::scan::scan(scan_root, options).expect("scan"); for name in ["one", "two", "original"] { assert!( tree.children.iter().any(|child| &*child.name == name), diff --git a/crates/disktree-core/src/scan.rs b/crates/disktree-core/src/scan.rs index dd7e44c..babfcad 100644 --- a/crates/disktree-core/src/scan.rs +++ b/crates/disktree-core/src/scan.rs @@ -1,69 +1,51 @@ -//! Parallel filesystem scanning. +//! Filesystem scanning backed by `disktree-scanner`. //! -//! The shape follows dust, because that shape is the reason dust is fast: -//! -//! * one `rayon::scope` per root, so recursion depth is O(1) however deep the -//! tree is, -//! * every directory is a `PendingDir` with an atomic completion counter and a -//! `+1` sentinel, so a directory is only built once its own scan *and* all of -//! its subdirectory tasks have finished, -//! * children are handed to the parent as finished `Node`s and sizes are -//! aggregated bottom-up in one pass over the finished tree, which is also -//! where hardlinks are de-duplicated. -//! -//! What is added on top of dust's approach: live progress counters the UI can -//! poll without locking, and cooperative cancellation so a re-scan can abandon -//! a walk of a large home directory instead of queueing behind it. +//! `disktree-scanner` owns parallel traversal, platform fast paths +//! (`getattrlistbulk` on macOS, `GetFileInformationByHandleEx` + NTFS MFT on +//! Windows), compact arena storage, Protobuf caching, and stale-while-revalidate +//! (SWR) sessions. This module projects `TreeArena` snapshots into classified +//! [`Node`] trees for the treemap and exposes [`ScanHandle`] for UI polling. -#[cfg(not(any(windows, target_os = "macos")))] -use std::fs::DirEntry; -use std::fs::{self, Metadata}; use std::io; use std::num::NonZeroU64; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; -use std::sync::mpsc::{self, Receiver, TryRecvError}; -use std::sync::{Arc, LazyLock, Mutex, MutexGuard, OnceLock, PoisonError}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; use std::thread; -use rayon::Scope; -use rustc_hash::FxHashSet; +use disktree_scanner::{ + CachePolicy, DirTallyHook, Freshness, HostKey, NodeFlags, NodeId, + NodeKind as ScannerKind, ScanEvent, ScanSession, Scanner, SkipOracle, + TreeArena, WalkConfig, WalkProgress, walk::walk_parallel, +}; +use rustc_hash::FxHashMap; -use crate::scan_threads::{Admission, ControllerGuard, ScanThreads}; use crate::tree::{Metric, Node, NodeKind, Seen, aggregate, aggregate_deduped}; -/// Errors kept verbatim before the list is truncated; the count keeps rising. -const MAX_ERROR_DETAIL: usize = 50; - /// How a scan measures and filters the tree. -#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)] pub struct ScanOptions { - /// Measure apparent length instead of allocated blocks. Apparent size is - /// what `ls -l` shows; blocks are what the volume actually spends, which is - /// what a disk-space tool normally wants. + /// Measure apparent length instead of allocated blocks. Both values are + /// stored in every `TreeArena`, so toggling this in the UI needs no rescan. pub apparent_size: bool, - /// Follow symlinks. Off by default: a home directory is full of links, and - /// following them double-counts. + /// Follow symlinks. Off by default. pub follow_links: bool, - /// Include dotfiles and dot-directories. On by default, like dust and `du`: - /// `~/.cache` is frequently the largest directory in a home directory. + /// Include dotfiles and dot-directories. Walks record hidden entries with + /// a flag so toggling this needs no rescan. pub include_hidden: bool, /// Stay on the root's volume: skip other disks, pseudo filesystems, - /// network shares, bind mounts and subvolumes. Select those explicitly - /// as another root. See [`crate::space::mount_boundaries`]. A disk - /// tool measures a disk, and its free-space meter only means anything - /// for one volume. + /// network shares and overlapping mount views. Local Btrfs scans include + /// distinct same-filesystem subvolumes; remote scans stop at every mount. pub one_filesystem: bool, - /// Stop descending past this depth. Totals below that depth are then - /// unknown, which makes an overview scan of a huge tree cheap. + /// Stop descending past this depth. pub max_depth: Option, /// Count a hardlinked file once instead of once per link. pub dedup_hardlinks: bool, /// Whether children are ranked by bytes or by file count. pub metric: Metric, - /// Directory admission for this scan; other scans have their own budget. + /// Optional fixed worker count; `None` uses available parallelism. #[serde(default)] - pub threads: ScanThreads, + pub threads: Option, } impl Default for ScanOptions { @@ -76,35 +58,28 @@ impl Default for ScanOptions { max_depth: None, dedup_hardlinks: true, metric: Metric::Bytes, - threads: ScanThreads::default(), + threads: None, } } } -/// Counters a running scan publishes for the UI. -/// -/// Plain relaxed atomics: this is a progress meter, not a synchronisation -/// point, and the UI reads a snapshot that is allowed to be a few entries -/// stale. -#[derive(Debug, Default)] -pub struct ScanProgress { - files: AtomicU64, - dirs: AtomicU64, - bytes: AtomicU64, - errors: AtomicU64, - finished: AtomicBool, - cancelled: AtomicBool, - messages: Mutex>, - preview_root: OnceLock, - preview: Mutex, - pub(crate) threads: AtomicUsize, - pub(crate) threads_settled: AtomicBool, - pub(crate) thread_tuning_complete: AtomicBool, - pub(crate) system_cpu_limited: AtomicBool, - pub(crate) worker_transitions: AtomicU64, +impl ScanOptions { + /// Convert to the underlying `disktree-scanner` traversal options. + #[must_use] + pub const fn to_scanner(&self) -> disktree_scanner::ScanOptions { + disktree_scanner::ScanOptions { + apparent_size: self.apparent_size, + follow_links: self.follow_links, + include_hidden: self.include_hidden, + one_filesystem: self.one_filesystem, + max_depth: self.max_depth, + dedup_hardlinks: self.dedup_hardlinks, + threads: self.threads, + } + } } -/// A point-in-time view of [`ScanProgress`]. +/// A point-in-time view of scan progress for the UI. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct ScanSnapshot { pub files: u64, @@ -113,17 +88,69 @@ pub struct ScanSnapshot { pub errors: u64, pub finished: bool, pub cancelled: bool, - /// Admitted directory jobs, not a machine-wide thread limit. - pub threads: usize, - pub threads_settled: bool, - pub thread_tuning_complete: bool, - pub system_cpu_limited: bool, - pub worker_transitions: u64, - /// Up to [`MAX_ERROR_DETAIL`] unreadable paths, most recent last. + /// Up to 50 unreadable paths, most recent last. pub messages: Vec, } +/// Shared progress + live treemap preview handle for an in-flight scan. +#[derive(Debug)] +pub struct ScanProgress { + walk: Arc, + cancel: Arc, + finished: AtomicBool, + apparent_size: bool, + preview_root: OnceLock, + preview: Arc>, +} + +impl Default for ScanProgress { + fn default() -> Self { + Self::new( + Arc::new(WalkProgress::default()), + Arc::new(AtomicBool::new(false)), + false, + None, + ) + } +} + impl ScanProgress { + fn new( + walk: Arc, + cancel: Arc, + apparent_size: bool, + root: Option, + ) -> Self { + Self::with_preview( + walk, + cancel, + apparent_size, + root, + Arc::new(Mutex::new(crate::scan_preview::Builder::default())), + ) + } + + fn with_preview( + walk: Arc, + cancel: Arc, + apparent_size: bool, + root: Option, + preview: Arc>, + ) -> Self { + let preview_root = OnceLock::new(); + if let Some(root) = root { + let _ = preview_root.set(root); + } + Self { + walk, + cancel, + finished: AtomicBool::new(false), + apparent_size, + preview_root, + preview, + } + } + pub fn preview(&self) -> crate::scan_preview::Preview { lock(&self.preview).snapshot() } @@ -144,1528 +171,702 @@ impl ScanProgress { preview.directory(path); } - pub(crate) fn entries(&self) -> u64 { - self.files.load(Ordering::Relaxed) + self.dirs.load(Ordering::Relaxed) + pub fn cancel(&self) { + self.cancel.store(true, Ordering::Relaxed); } - /// What a directory's listing found (see `Tally`), or what a reader - /// that measures in bulk has come across so far. - pub(crate) fn add(&self, files: u64, dirs: u64, bytes: u64) { - self.files.fetch_add(files, Ordering::Relaxed); - self.dirs.fetch_add(dirs, Ordering::Relaxed); - self.bytes.fetch_add(bytes, Ordering::Relaxed); - } - - /// The totals of the finished tree, replacing a bulk reader's running - /// count: it met the whole volume, and the tree may be less of it. - #[cfg(windows)] - pub(crate) fn settle(&self, files: u64, dirs: u64, bytes: u64) { - self.files.store(files, Ordering::Relaxed); - self.dirs.store(dirs, Ordering::Relaxed); - self.bytes.store(bytes, Ordering::Relaxed); - } - - fn record_error(&self, path: &Path, error: &io::Error) { - self.errors.fetch_add(1, Ordering::Relaxed); - // A scan without Full Disk Access can refuse thousands of paths; - // only the ones that will be kept are worth formatting. - let mut messages = lock(&self.messages); - if messages.len() < MAX_ERROR_DETAIL { - messages.push(format!("{}: {error}", path.display())); - } - drop(messages); + pub fn is_cancelled(&self) -> bool { + self.cancel.load(Ordering::Relaxed) } fn finish(&self) { self.finished.store(true, Ordering::Relaxed); } - /// Ask the walk to stop at the next directory boundary. - pub fn cancel(&self) { - self.cancelled.store(true, Ordering::Relaxed); - } - - /// Stop the walk now, without waiting for the worker thread. - pub fn is_cancelled(&self) -> bool { - self.cancelled.load(Ordering::Relaxed) - } - pub fn snapshot(&self) -> ScanSnapshot { + let bytes = if self.apparent_size { + self.walk.apparent_bytes.load(Ordering::Relaxed) + } else { + self.walk.allocated_bytes.load(Ordering::Relaxed) + }; ScanSnapshot { - files: self.files.load(Ordering::Relaxed), - dirs: self.dirs.load(Ordering::Relaxed), - bytes: self.bytes.load(Ordering::Relaxed), - errors: self.errors.load(Ordering::Relaxed), + files: self.walk.files.load(Ordering::Relaxed), + dirs: self.walk.dirs.load(Ordering::Relaxed), + bytes, + errors: self.walk.errors.load(Ordering::Relaxed), finished: self.finished.load(Ordering::Relaxed), cancelled: self.is_cancelled(), - threads: self.threads.load(Ordering::Relaxed), - threads_settled: self.threads_settled.load(Ordering::Relaxed), - thread_tuning_complete: self - .thread_tuning_complete - .load(Ordering::Relaxed), - system_cpu_limited: self.system_cpu_limited.load(Ordering::Relaxed), - worker_transitions: self.worker_transitions.load(Ordering::Relaxed), - messages: lock(&self.messages).clone(), + messages: self.walk.messages(), } } } -/// A scan running on its own thread. +/// Incremental outcome emitted by [`ScanHandle::poll_update`]. #[derive(Debug)] -pub struct ScanHandle { - pub progress: Arc, - result: Receiver>, +pub enum ScanUpdate { + /// Immediate snapshot served from the cache DB (`Fresh`, `Stale`, or + /// `Partial`). If `freshness` is `Fresh`, no further walk will run. + Cached { + arena: Arc, + node: Node, + freshness: Freshness, + }, + /// Completed live scan (all subtrees up to date and persisted to cache). + Live { arena: Arc, node: Node }, + /// Non-fatal or fatal scan error. + Error(io::Error), + /// Background revalidation finished without a new snapshot (e.g. fresh + /// cache hit already emitted or cancelled). + Finished, } /// A subtree already measured, reused by a wider scan instead of walked /// again: widening from `~` to `/` only reads what is outside `~`. #[derive(Clone, Debug)] pub struct Known { - /// Where it is. Compared with the walk's own paths, so give it in the - /// same form as the root (both canonical). + /// Canonical path of the already-measured subtree. pub path: PathBuf, - pub tree: Arc, + pub arena: Arc, +} + +struct KnownSkipOracle { + path: PathBuf, + arena: Arc, +} + +impl SkipOracle for KnownSkipOracle { + fn try_reuse(&self, path: &Path) -> Option { + (path == self.path).then(|| (*self.arena).clone()) + } +} + +enum ScanBackend { + Session(ScanSession), + OneShot(std::sync::mpsc::Receiver>), +} + +/// A scan running on background worker threads, backed by `disktree-scanner`. +pub struct ScanHandle { + pub progress: Arc, + options: ScanOptions, + backend: ScanBackend, +} + +impl std::fmt::Debug for ScanHandle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ScanHandle") + .field("options", &self.options) + .finish_non_exhaustive() + } } impl ScanHandle { - /// Start walking `root` on a worker thread. + /// Start an SWR scan backed by `scanner`'s persistent/auto cache DB. + pub fn spawn_session( + scanner: &Scanner, + root: PathBuf, + options: ScanOptions, + policy: CachePolicy, + ) -> io::Result { + let canonical = root.canonicalize().unwrap_or_else(|_| root.clone()); + let preview = + Arc::new(Mutex::new(crate::scan_preview::Builder::default())); + let preview_hook = Arc::clone(&preview); + let hook_root = canonical.clone(); + let apparent = options.apparent_size; + let on_dir_tally: DirTallyHook = + Arc::new(move |dir, alloc, app, files| { + let Ok(below) = dir.strip_prefix(&hook_root) else { + return; + }; + let name = below + .components() + .next() + .map(|part| part.as_os_str().to_string_lossy()); + let bytes = if apparent { app } else { alloc }; + let mut builder = lock(&preview_hook); + builder.add(name.as_deref(), bytes, files); + builder.directory(dir); + }); + let session = scanner.open_with_tally( + HostKey::Local, + root, + options.to_scanner(), + policy, + Some(on_dir_tally), + )?; + let progress = Arc::new(ScanProgress::with_preview( + session.progress(), + Arc::new(AtomicBool::new(false)), + options.apparent_size, + Some(canonical), + preview, + )); + Ok(Self { + progress, + options, + backend: ScanBackend::Session(session), + }) + } + + /// Start an in-memory scan without touching any persistent cache DB. pub fn spawn(root: PathBuf, options: ScanOptions) -> Self { Self::spawn_with(root, options, None) } - /// Start walking `root`, reusing `known` where the walk reaches it. + /// Start an in-memory scan, reusing `known` where the walk reaches it. pub fn spawn_with( root: PathBuf, options: ScanOptions, known: Option, ) -> Self { - let progress = Arc::new(ScanProgress::default()); - let context = Arc::new(WalkContext { - known, - options, - progress: Arc::clone(&progress), - root_device: Mutex::new(None), - foreign_mounts: OnceLock::new(), - never_scanned: OnceLock::new(), - visited_dirs: Mutex::new(FxHashSet::default()), - root: Mutex::new(None), - volume: OnceLock::new(), - }); - let (sender, result) = mpsc::channel(); - - // The closure owns the sender, so a failed spawn drops it and the - // receiver reports the failure. Record the real reason alongside it. + let canonical = root.canonicalize().unwrap_or_else(|_| root.clone()); + let walk_progress = Arc::new(WalkProgress::default()); + let cancel = Arc::new(AtomicBool::new(false)); + let progress = Arc::new(ScanProgress::new( + Arc::clone(&walk_progress), + Arc::clone(&cancel), + options.apparent_size, + Some(canonical), + )); + let tally_progress = Arc::clone(&progress); + let apparent = options.apparent_size; + let on_dir_tally: DirTallyHook = + Arc::new(move |dir, alloc, app, files| { + let bytes = if apparent { app } else { alloc }; + tally_progress.preview_add(dir, bytes, files); + }); + let (sender, receiver) = std::sync::mpsc::channel(); + let scanner_opts = options.to_scanner(); + let worker_progress = Arc::clone(&progress); let worker = thread::Builder::new().name("disktree-scan".into()).spawn( move || { - let outcome = scan_blocking(&root, &context); - context.progress.finish(); + let skip_oracle: Option> = + known.map(|known| { + let oracle: Arc = + Arc::new(KnownSkipOracle { + path: known.path, + arena: known.arena, + }); + oracle + }); + let outcome = walk_parallel( + &root, + WalkConfig { + options: &scanner_opts, + cancel, + progress: walk_progress, + pause_gate: None, + skip_oracle, + on_dir_start: None, + on_dir_tally: Some(on_dir_tally), + }, + ) + .map(|walk| walk.arena); + worker_progress.finish(); let _ = sender.send(outcome); }, ); if let Err(error) = worker { - progress.record_error(Path::new("scan worker"), &error); + progress.walk.record_error(Path::new("scan worker"), &error); progress.finish(); } - - Self { progress, result } + Self { + progress, + options, + backend: ScanBackend::OneShot(receiver), + } } - /// Take the finished tree, if the walk is done. + /// Ask the in-flight scan to stop. + pub fn cancel(&self) { + self.progress.cancel(); + if let ScanBackend::Session(session) = &self.backend { + session.cancel(); + } + } + + /// Preempt background SWR revalidation to refresh `path` first. + pub fn prioritize(&self, path: &Path) { + if let ScanBackend::Session(session) = &self.backend { + let _ = session.prioritize(path); + } + } + + /// Drain the next incremental update from an SWR session or one-shot walk. + pub fn poll_update(&self) -> Option { + match &self.backend { + ScanBackend::Session(session) => loop { + match session.try_recv() { + Ok(ScanEvent::Snapshot(snap)) => { + let node = arena_to_node( + &snap.arena, + self.options.apparent_size, + self.options.include_hidden, + self.options.dedup_hardlinks, + self.options.metric, + ); + if matches!(snap.freshness, Freshness::Live { .. }) { + self.progress.finish(); + return Some(ScanUpdate::Live { + arena: snap.arena, + node, + }); + } + if matches!(snap.freshness, Freshness::Fresh { .. }) { + self.progress.finish(); + } + return Some(ScanUpdate::Cached { + arena: snap.arena, + node, + freshness: snap.freshness, + }); + } + Ok(ScanEvent::Error { message }) => { + self.progress.finish(); + return Some(ScanUpdate::Error(io::Error::other( + message, + ))); + } + Ok(ScanEvent::Finished) + | Err(std::sync::mpsc::TryRecvError::Disconnected) => { + self.progress.finish(); + return Some(ScanUpdate::Finished); + } + Ok( + ScanEvent::Progress { .. } + | ScanEvent::SubtreeUpdating { .. } + | ScanEvent::SubtreeRefreshed { .. } + | ScanEvent::StorageFallback { .. }, + ) => {} + Err(std::sync::mpsc::TryRecvError::Empty) => return None, + } + }, + ScanBackend::OneShot(receiver) => match receiver.try_recv() { + Ok(Ok(arena)) => { + let arena = Arc::new(arena); + let node = arena_to_node( + &arena, + self.options.apparent_size, + self.options.include_hidden, + self.options.dedup_hardlinks, + self.options.metric, + ); + self.progress.finish(); + Some(ScanUpdate::Live { arena, node }) + } + Ok(Err(error)) => { + self.progress.finish(); + Some(ScanUpdate::Error(error)) + } + Err(std::sync::mpsc::TryRecvError::Empty) => None, + Err(std::sync::mpsc::TryRecvError::Disconnected) => { + self.progress.finish(); + Some(ScanUpdate::Error(io::Error::other( + "the scan worker stopped without a result", + ))) + } + }, + } + } + + /// Take the finished tree, if the walk is done (simple blocking/test API). pub fn poll(&self) -> Option> { - match self.result.try_recv() { - Ok(outcome) => Some(outcome), - Err(TryRecvError::Empty) => None, - Err(TryRecvError::Disconnected) => Some(Err(io::Error::other( - "the scan worker stopped without a result", + match self.poll_update()? { + ScanUpdate::Live { node, .. } + | ScanUpdate::Cached { + node, + freshness: Freshness::Fresh { .. }, + .. + } => Some(Ok(node)), + ScanUpdate::Cached { .. } => None, + ScanUpdate::Error(err) => Some(Err(err)), + ScanUpdate::Finished => Some(Err(io::Error::other( + "the scan finished without producing a tree", ))), } } - - /// Abandon the walk; the worker still finishes the directory it is in. - pub fn cancel(&self) { - self.progress.cancel(); - } } -/// Walk `root` and return the aggregated tree. Blocking. -pub fn scan(root: &Path, options: ScanOptions) -> io::Result { - let progress = Arc::new(ScanProgress::default()); - let context = Arc::new(WalkContext { - known: None, - options, - progress: Arc::clone(&progress), - root_device: Mutex::new(None), - foreign_mounts: OnceLock::new(), - never_scanned: OnceLock::new(), - visited_dirs: Mutex::new(FxHashSet::default()), - root: Mutex::new(None), - volume: OnceLock::new(), - }); - let node = scan_blocking(root, &context)?; - progress.finish(); - Ok(node) -} - -struct WalkContext { - /// A subtree to reuse rather than walk. - known: Option, - options: ScanOptions, - progress: Arc, - /// Device of the root, resolved once: the `one_filesystem` fallback - /// when the mount table cannot be read. - root_device: Mutex>, - /// Mount points `one_filesystem` keeps out, from the mount table. Unset - /// when the table cannot be read, and devices are compared instead. - foreign_mounts: OnceLock>, - /// Directories no scan enters, on any volume setting: see - /// [`crate::space::never_scanned`]. - never_scanned: OnceLock>, - /// Directories already entered, so followed symlinks cannot loop. - visited_dirs: Mutex>, - /// Set by the root's `complete`, read after the scope joins. - root: Mutex>, - /// Serial number of the root's volume, on Windows, for a walk that - /// cannot leave it: every listing takes it instead of asking. See - /// [`crate::windows::walk_volume`]. - volume: OnceLock, -} - -impl WalkContext { - fn root_device(&self, path: &Path) -> Option { - let mut cached = lock(&self.root_device); - if let Some(device) = *cached { - return Some(device); - } - let device = fs::metadata(path).map(|meta| device_of(&meta)).ok(); - *cached = device; - device - } - - fn cancelled(&self) -> bool { - self.progress.is_cancelled() - } - - /// Decide what to do with an entry listed in `dir`. - /// - /// The entry's path is built only where it is used: most entries are - /// files, and a disk has millions of them. The name is moved out of - /// the entry last, so nothing copies it. - fn classify(&self, dir: &Path, entry: &mut impl Listed) -> Classified { - let listing = match entry.listing() { - Ok(listing) => listing, - Err(error) => { - self.progress.record_error(&entry.entry_path(dir), &error); - return Classified::Skipped; - } - }; - - if !self.options.include_hidden - && (entry.name().starts_with('.') || entry.hidden()) - { - return Classified::Skipped; - } - - let kind = match listing { - Listing::Symlink => { - let path = entry.entry_path(dir); - return self.classify_symlink(&path, entry.take_name()); - } - Listing::Directory => { - let path = entry.entry_path(dir); - return self.classify_dir(entry, path); - } - Listing::Leaf(kind) => kind, - }; - match entry.facts(self.options.apparent_size) { - Ok(facts) => self.leaf(entry.take_name(), kind, &facts), - Err(error) => { - self.progress.record_error(&entry.entry_path(dir), &error); - Classified::Skipped - } - } - } - - fn classify_dir( - &self, - entry: &mut impl Listed, - path: PathBuf, - ) -> Classified { - if self - .never_scanned - .get() - .is_some_and(|never| never.contains(&path)) - { - return Classified::Skipped; - } - if self.options.one_filesystem - && let Some(foreign) = self.foreign_mounts.get() - { - // Checked by path before anything reads the directory, so an - // automount point is never triggered. - if foreign.contains(&path) { - return Classified::Skipped; - } - } - // Read at most once per directory: macOS needs it for the dataless - // flag, and the device check below wherever the mount table cannot - // be read, which on macOS is everywhere. - let directory_cell = std::cell::OnceCell::new(); - let directory = || directory_cell.get_or_init(|| entry.directory()); - if EVICTED_IS_KNOWN - && directory() - .as_ref() - .is_ok_and(|directory| directory.evicted) - { - return Classified::Skipped; - } - // Memoized: the subtree a narrower scan already measured is taken - // whole, before any volume rule, since it was measured under the same - // rules. - if let Some(known) = &self.known - && known.path == path - { - let mut tree = (*known.tree).clone(); - tree.name = entry.take_name(); - return Classified::Entry(tree); - } - if self.options.one_filesystem && self.foreign_mounts.get().is_none() { - match (directory(), self.root_device(&path)) { - (Ok(directory), Some(root_device)) - if directory.device != root_device => - { - return Classified::Skipped; - } - (Err(error), _) => { - self.progress.record_error(&path, error); - return Classified::Skipped; - } - _ => {} - } - } - Classified::Subdirectory { - path, - name: entry.take_name(), - } - } - - fn classify_symlink(&self, path: &Path, name: Box) -> Classified { - if !self.options.follow_links { - // Not followed: the link occupies only its target string, which - // `du` reports as a handful of bytes or nothing at all. - return match fs::symlink_metadata(path) { - Ok(meta) => { - let facts = Facts::of(&meta, self.options.apparent_size); - Classified::Entry(leaf_node( - name, - NodeKind::Symlink, - &facts, - facts.shared, - )) - } - Err(error) => { - self.progress.record_error(path, &error); - Classified::Skipped - } - }; - } - - let meta = match fs::metadata(path) { - Ok(meta) => meta, - Err(error) => { - // A dangling link is normal, not an error worth counting. - if error.kind() != io::ErrorKind::NotFound { - self.progress.record_error(path, &error); - } - return Classified::Skipped; - } - }; - - if meta.is_dir() { - // A link into an evicted cloud folder is left alone for the - // same reason the folder itself is. - if is_dataless(&meta) { - return Classified::Skipped; - } - if let Some(key) = identity_of(path, &meta) - && !lock(&self.visited_dirs).insert(key) - { - return Classified::Skipped; - } - return Classified::Subdirectory { - path: path.to_path_buf(), - name, - }; - } - - let mut facts = Facts::of(&meta, self.options.apparent_size); - // What the link leads to, so a file that is also reached directly is - // charged once. - facts.identity = identity_of(path, &meta); - self.leaf(name, kind_of(&meta, meta.file_type()), &facts) - } - - fn leaf( - &self, - name: Box, - kind: NodeKind, - facts: &Facts, - ) -> Classified { - // A followed link reaches a file a second way, whatever its link - // count says. - let track = self.options.follow_links || facts.shared; - Classified::Entry(leaf_node(name, kind, facts, track)) - } -} - -/// What the walk reads about one directory entry. +/// Project a compact [`TreeArena`] into a classified, aggregated [`Node`] +/// tree for the GPUI treemap and insights engine. /// -/// `std::fs::DirEntry` everywhere but Windows and macOS. On Windows the -/// standard listing has neither the allocated size nor a file id, so -/// measuring like `du` would cost an open per file; [`crate::windows`] lists -/// a directory with both instead. On macOS it would cost an `lstat` per -/// entry, and [`crate::macos`] lists a directory with everything a stat -/// says. -trait Listed { - /// The entry's path inside `dir`, the directory it was listed from. - fn entry_path(&self, dir: &Path) -> PathBuf; - /// Non-UTF-8 names are lossy for display. The scan still measures them - /// correctly; only the reported name is approximate. - fn name(&self) -> &str; - /// The name, moved out for the tree: after this `name` is empty, and - /// `entry_path`, which must open the real file, is off limits. - fn take_name(&mut self) -> Box; - fn listing(&self) -> io::Result; - /// Size, identity and age of a leaf. - fn facts(&self, apparent_size: bool) -> io::Result; - /// What a directory is, read before the walk enters it. - fn directory(&self) -> io::Result; - /// Hidden by an attribute rather than by a leading dot: on Windows, - /// where the listing carries it, so `AppData` is hidden as Explorer - /// hides it. Finder's `UF_HIDDEN` is not asked for: on macOS, hidden - /// means a leading dot, as on Linux. - fn hidden(&self) -> bool { - false - } -} - -/// Whether [`Directory::evicted`] can ever be true here, so a platform that -/// cannot say never pays for asking. -const EVICTED_IS_KNOWN: bool = cfg!(any(target_os = "macos", windows)); - -/// What the walk needs to know about a directory before entering it. -struct Directory { - /// The device it is on, for staying on one volume when the mount table - /// cannot be read. - device: u64, - /// Its contents live only in the cloud (iCloud Drive or a File Provider - /// on macOS, `OneDrive` or another cloud files provider on Windows). - /// Listing it would make the provider fetch them, so a disk scan must - /// not; it holds no local blocks, so skipping it loses nothing. - evicted: bool, -} - -/// What an entry is, as far as the walk is concerned. -enum Listing { - Directory, - Symlink, - Leaf(NodeKind), -} - -/// What a leaf contributes. -struct Facts { - size: u64, - identity: Option<(u64, u64)>, - modified: i64, - /// The file may have another name the walk could meet: its identity is - /// worth keeping for hardlink de-duplication. - shared: bool, -} - -impl Facts { - fn of(meta: &Metadata, apparent_size: bool) -> Self { - Self { - size: measure(meta, apparent_size), - identity: file_identity(meta), - modified: modified_seconds(meta), - shared: shares_inode(meta), +/// Because `TreeArena` stores both `allocated_bytes` and `apparent_bytes`, +/// hidden flags, and multi-link identities, toggling `apparent_size` or +/// `include_hidden` re-projects instantaneously without touching disk. +#[must_use] +pub fn arena_to_node( + arena: &TreeArena, + apparent_size: bool, + include_hidden: bool, + dedup_hardlinks: bool, + metric: Metric, +) -> Node { + let mut link_map: FxHashMap = + FxHashMap::default(); + if dedup_hardlinks && !arena.hardlinks().is_empty() { + link_map.reserve(arena.hardlinks().len()); + for link in arena.hardlinks() { + if let Some(ino) = NonZeroU64::new(link.ino) { + link_map.insert(link.node, (link.dev, ino)); + } } } + let mut root = build_node( + arena, + arena.root(), + apparent_size, + include_hidden, + &link_map, + true, + ); + if dedup_hardlinks { + aggregate_deduped(&mut root, metric, &Seen::new()); + } else { + aggregate(&mut root, metric); + } + crate::classify::classify(&mut root); + root } -/// A standard directory entry with its name decoded once, up front. -#[cfg(not(any(windows, target_os = "macos")))] -struct Named { - entry: DirEntry, - name: Box, -} - -#[cfg(not(any(windows, target_os = "macos")))] -impl Listed for Named { - fn entry_path(&self, _dir: &Path) -> PathBuf { - self.entry.path() - } - - fn name(&self) -> &str { - &self.name - } - - fn take_name(&mut self) -> Box { - std::mem::take(&mut self.name) - } - - fn listing(&self) -> io::Result { - let file_type = self.entry.file_type()?; - Ok(if file_type.is_symlink() { - Listing::Symlink - } else if file_type.is_dir() { - Listing::Directory - } else if file_type.is_file() { - Listing::Leaf(NodeKind::File) +fn build_node( + arena: &TreeArena, + id: NodeId, + apparent_size: bool, + include_hidden: bool, + link_map: &FxHashMap, + is_root: bool, +) -> Node { + let an = arena.node(id); + let name: Box = arena.name(id).into(); + let kind = match an.kind() { + ScannerKind::Directory => NodeKind::Directory, + ScannerKind::File => NodeKind::File, + ScannerKind::Symlink => NodeKind::Symlink, + ScannerKind::Other => NodeKind::Other, + }; + if kind == NodeKind::Directory { + let mut children = Vec::new(); + for child_id in arena.children(id) { + let child = arena.node(child_id); + if !include_hidden && child.flags.has(NodeFlags::HIDDEN) { + continue; + } + children.push(build_node( + arena, + child_id, + apparent_size, + include_hidden, + link_map, + false, + )); + } + let mut node = Node::directory(name); + node.read_error = an.read_error(); + node.modified = an.modified; + node.children = children; + let _ = is_root; + node + } else { + let bytes = if apparent_size { + an.apparent_bytes } else { - Listing::Leaf(NodeKind::Other) - }) - } - - fn facts(&self, apparent_size: bool) -> io::Result { - self.entry - .metadata() - .map(|meta| Facts::of(&meta, apparent_size)) - } - - fn directory(&self) -> io::Result { - self.entry.metadata().map(|meta| Directory { - device: device_of(&meta), - evicted: is_dataless(&meta), - }) + an.allocated_bytes + }; + let mut node = Node::entry(name, kind, bytes); + node.modified = an.modified; + node.read_error = an.read_error(); + node.inode = link_map.get(&id).copied(); + node } } -#[cfg(target_os = "macos")] -impl Listed for crate::macos::Entry { - fn entry_path(&self, dir: &Path) -> PathBuf { - self.path(dir) - } - - fn name(&self) -> &str { - self.name() - } - - fn take_name(&mut self) -> Box { - self.take_name() - } - - fn listing(&self) -> io::Result { - Ok(match self.kind() { - crate::macos::Kind::Link => Listing::Symlink, - crate::macos::Kind::Directory => Listing::Directory, - crate::macos::Kind::File => Listing::Leaf(NodeKind::File), - crate::macos::Kind::Other => Listing::Leaf(NodeKind::Other), - }) - } - - fn facts(&self, apparent_size: bool) -> io::Result { - Ok(Facts { - size: if apparent_size { - self.apparent() - } else { - self.allocated() - }, - identity: Some(self.identity()), - modified: self.modified(), - shared: self.shared(), - }) - } - - fn directory(&self) -> io::Result { - Ok(Directory { - device: self.device(), - evicted: self.evicted(), - }) - } +/// Convert a [`Node`] tree back into a [`TreeArena`] (used when widening from +/// a pre-built tree or in tests). +#[must_use] +pub fn node_to_arena(root_path: PathBuf, root: &Node) -> TreeArena { + let mut arena = TreeArena::new(root_path, root.name.as_ref()); + let root_id = arena.root(); + copy_node_into_arena(&mut arena, root_id, root); + arena.aggregate(true, true); + arena } -#[cfg(windows)] -impl Listed for crate::windows::Entry { - fn entry_path(&self, dir: &Path) -> PathBuf { - self.path(dir) +fn copy_node_into_arena(arena: &mut TreeArena, parent: NodeId, node: &Node) { + { + let target = arena.node_mut(parent); + target.modified = node.modified; + target.flags.set(NodeFlags::READ_ERROR, node.read_error); + target + .flags + .set(NodeFlags::HIDDEN, node.name.starts_with('.')); } - - fn name(&self) -> &str { - self.name() - } - - fn take_name(&mut self) -> Box { - self.take_name() - } - - fn listing(&self) -> io::Result { - Ok(match self.kind() { - crate::windows::Kind::Link => Listing::Symlink, - crate::windows::Kind::Directory => Listing::Directory, - crate::windows::Kind::File => Listing::Leaf(NodeKind::File), - }) - } - - fn facts(&self, apparent_size: bool) -> io::Result { - Ok(Facts { - size: if apparent_size { - self.apparent() - } else { - self.allocated() - }, - identity: self.identity(), - modified: self.modified(), - // The listing has no link count; a file id is free here, so - // every file keeps one. - shared: true, - }) - } - - /// The device is never consulted: see - /// [`crate::space::foreign_mounts_for`]. The same answer as - /// [`device_of`], so the two could only ever agree. - fn directory(&self) -> io::Result { - Ok(Directory { - device: 0, - evicted: self.evicted(), - }) - } - - fn hidden(&self) -> bool { - self.hidden() - } -} - -/// List a directory the way [`Listed`] describes. -#[cfg(not(any(windows, target_os = "macos")))] -fn list( - path: &Path, - _volume: Option, -) -> io::Result>> { - Ok(fs::read_dir(path)?.map(|entry| { - entry.map(|entry| Named { - name: entry.file_name().into_string().map_or_else( - |raw| raw.to_string_lossy().into(), - String::into_boxed_str, - ), - entry, - }) - })) -} - -#[cfg(target_os = "macos")] -fn list( - path: &Path, - _volume: Option, -) -> io::Result { - crate::macos::read_dir(path) -} - -#[cfg(windows)] -fn list( - path: &Path, - volume: Option, -) -> io::Result { - crate::windows::read_dir(path, volume) -} - -/// What a directory entry turned out to be. -enum Classified { - /// Descend into this directory on a new task. - Subdirectory { path: PathBuf, name: Box }, - /// A leaf that contributes size. - Entry(Node), - /// Filtered out, unreadable, or a symlink we chose not to follow. - Skipped, -} - -/// One directory being walked, plus the counter that decides when it is done. -#[derive(Debug)] -struct PendingDir { - path: PathBuf, - parent: Option>, - /// Starts at 1 for the directory itself; one more per subdirectory task. - /// When it reaches zero the directory is complete. - pending: AtomicUsize, - /// The node so far, moved out whole once the directory is complete. - partial: Mutex, - read_error: AtomicBool, - depth: usize, -} - -/// What a directory's node is made of before it is built: the name the -/// listing gave it, and the files found directly in it plus the finished -/// subdirectories handed back up. -#[derive(Debug, Default)] -struct Partial { - name: Box, - children: Vec, -} - -impl PendingDir { - const fn new( - path: PathBuf, - name: Box, - parent: Option>, - depth: usize, - ) -> Self { - Self { - path, + for child in &node.children { + let kind = match child.kind { + NodeKind::Directory => ScannerKind::Directory, + NodeKind::File => ScannerKind::File, + NodeKind::Symlink => ScannerKind::Symlink, + NodeKind::Other => ScannerKind::Other, + }; + let mut flags = NodeFlags::new(kind); + flags.set(NodeFlags::READ_ERROR, child.read_error); + flags.set(NodeFlags::HIDDEN, child.name.starts_with('.')); + let bytes = if kind == ScannerKind::Directory { + 0 + } else { + child.bytes + }; + let id = arena.add_child( parent, - pending: AtomicUsize::new(1), - partial: Mutex::new(Partial { - name, - children: Vec::new(), - }), - read_error: AtomicBool::new(false), - depth, + child.name.as_ref(), + kind, + bytes, + bytes, + child.modified, + flags, + ); + if let Some((dev, ino)) = child.inode { + arena.record_hardlink(id, dev, ino.get()); } - } - - /// Turn a completed directory into a node. Only called when `pending` has - /// reached zero, so every child is already in `self.partial`. - /// - /// `bytes` is left at zero on purpose: the walk cannot know the - /// aggregate, and [`crate::tree::aggregate`] derives it from the children - /// once every child is present. - fn build(&self) -> Node { - let partial = std::mem::take(&mut *lock(&self.partial)); - Node { - name: partial.name, - kind: NodeKind::Directory, - bytes: 0, - files: 0, - dirs: 1, - inode: None, - read_error: self.read_error.load(Ordering::Relaxed), - modified: 0, - category: crate::classify::Category::Other, - reclaim: None, - children: partial.children, + if kind == ScannerKind::Directory { + copy_node_into_arena(arena, id, child); } } } -fn scan_blocking(root: &Path, context: &Arc) -> io::Result { - let _ = context.progress.preview_root.set(root.to_path_buf()); - let owned = fixed_pool(context.options.threads)?; - let pool = owned.as_ref().unwrap_or_else(|| &WALK_POOL); - scan_on_pool(root, context, pool) +/// Scan `root` synchronously via `disktree-scanner` and return a classified +/// [`Node`] tree. +pub fn scan(root: &Path, options: ScanOptions) -> io::Result { + let scanner_opts = options.to_scanner(); + let outcome = walk_parallel( + root, + WalkConfig { + options: &scanner_opts, + cancel: Arc::new(AtomicBool::new(false)), + progress: Arc::new(WalkProgress::default()), + pause_gate: None, + skip_oracle: None, + on_dir_start: None, + on_dir_tally: None, + }, + )?; + Ok(arena_to_node( + &outcome.arena, + options.apparent_size, + options.include_hidden, + options.dedup_hardlinks, + options.metric, + )) } -/// Explicit fixed budgets cover enumeration, the Windows file-table path and -/// tree finishing. A scan owns its pool so a new setting needs no global reset. -/// Default core callers and experimental adaptive scans retain the shared pool. -fn fixed_pool(threads: ScanThreads) -> io::Result> { - if threads.adaptive || threads.max_threads == usize::MAX { - return Ok(None); - } - let cpus = thread::available_parallelism().map_or(1, usize::from); - rayon::ThreadPoolBuilder::new() - .num_threads(threads.max_threads.clamp(1, cpus)) - .thread_name(|index| format!("disktree-scan-{index}")) - .build() - .map(Some) - .map_err(io::Error::other) -} - -fn scan_on_pool( - root: &Path, - context: &Arc, - pool: &rayon::ThreadPool, -) -> io::Result { - let root_meta = fs::metadata(root)?; - if !root_meta.is_dir() { - return Err(io::Error::new( - io::ErrorKind::InvalidInput, - format!("{} is not a directory", root.display()), - )); - } - let resolved = root.canonicalize().ok(); - let canonical = resolved.as_deref().unwrap_or(root); - let mut never = crate::space::never_scanned(root, canonical); - // Hidden-entry and depth filters can leave an alias as the only route - // to files. Keep every mount view when either filter is active. - if context.options.include_hidden && context.options.max_depth.is_none() { - never.extend(crate::space::repeated_mounts_for( - root, - canonical, - context.options.one_filesystem, - )); - } - let _ = context.never_scanned.set(never.into_iter().collect()); - if context.options.one_filesystem { - *lock(&context.root_device) = Some(device_of(&root_meta)); - if let Some(foreign) = crate::space::mount_boundaries_for(canonical) { - let _ = context.foreign_mounts.set(foreign.into_iter().collect()); - } - } - // Reading the file table is far faster than any walk, where the - // volume allows it. On the walk's pool too: see `WALK_POOL`. - #[cfg(windows)] - { - let progress = &context.progress; - let read = pool.install(|| { - crate::mft::scan(root, canonical, &context.options, progress) - }); - if let Some(node) = read { - let node = node?; - // Cancelled after the reader's last check: the rescan that - // asked is waiting, and this tree is not wanted. - if progress.is_cancelled() { - return Err(crate::mft::cancelled()); - } - let node = finish_tree(node, &context.options, pool); - // The reader counted every file on the volume; the tree may - // hold fewer. - progress.settle(node.files, u64::from(node.dirs), node.bytes); - return Ok(node); - } - // The reader gave up, or never started: the walk counts from nothing. - progress.settle(0, 0, 0); - // Asking once instead of per directory; see `walk_volume` for - // when a walk that does not follow links cannot leave the volume. - // Only on a resolved root: a mapped share's letter kept as typed - // looks like a local drive. - if !context.options.follow_links - && let Some(resolved) = &resolved - && let Some(serial) = crate::windows::walk_volume(resolved) - { - let _ = context.volume.set(serial); - } - } - if context.options.follow_links - && let Some(key) = identity_of(root, &root_meta) - { - lock(&context.visited_dirs).insert(key); - } - - let root_dir = Arc::new(PendingDir::new( - root.to_path_buf(), - file_name(root), - None, - 0, - )); - let context: &WalkContext = context; - pool.install(|| { - let mut threads = context.options.threads.normalized(); - threads.max_threads = - threads.max_threads.min(rayon::current_num_threads()); - context - .progress - .threads - .store(threads.max_threads, Ordering::Relaxed); - context - .progress - .threads_settled - .store(true, Ordering::Relaxed); - context - .progress - .thread_tuning_complete - .store(!threads.adaptive, Ordering::Relaxed); - if !threads.adaptive - && threads.max_threads == rayon::current_num_threads() - { - // Pool-sized fixed scans need no admission lock or ready queue. Keep - // existing core callers on Rayon's direct scheduling path. - rayon::scope(|scope| { - dispatch_fixed(scope, &root_dir, context); - }); - } else { - let admission = - Arc::new(Admission::new(root_dir, threads.max_threads)); - // The controller owns no Rayon worker and is joined before finishing - // the tree, where entry throughput no longer describes useful work. - let _controller = ControllerGuard::spawn( - threads, - Arc::clone(&admission), - Arc::clone(&context.progress), - )?; - rayon::scope(|scope| { - dispatch(scope, admission.start(), context, &admission); - }); - } - Ok::<(), io::Error>(()) - })?; - - let node = lock(&context.root).take(); - let node = node.ok_or_else(|| { - io::Error::other(format!("{} produced no tree", root.display())) - })?; - Ok(finish_tree(node, &context.options, pool)) -} - -/// The walk's workers, and the file table reader's. Listing directories -/// contends in the file system, and past some number of threads more of -/// them only queue: on Windows a home directory of 3.4 million files -/// walked in 6.5 s on 16 threads and 8.1 s on all 24. That cap was -/// measured on one 24-thread NTFS laptop; another disk or CPU may want -/// another. Elsewhere the default count. A pool of its own on every -/// platform all the same: work the UI hands the global pool, such as -/// re-ranking a tree, must not queue behind a scan's blocking reads. -static WALK_POOL: LazyLock = LazyLock::new(|| { - let threads = if cfg!(windows) { - rayon::current_num_threads().min(16) - } else { - rayon::current_num_threads() - }; - rayon::ThreadPoolBuilder::new() - .num_threads(threads) - .thread_name(|index| format!("disktree-walk-{index}")) - .build() - .expect("a thread pool") -}); - -/// Entries counted before the shared progress counters are touched. Every -/// worker adding to the same counters per entry keeps one cache line -/// bouncing between cores; per directory, or per this many entries in a -/// wide one so the meter still moves, is invisible to a reader. -const TALLY_EVERY: u64 = 1024; - -/// What one directory's listing has found so far, for the progress meter. -#[derive(Default)] -struct Tally { - files: u64, - dirs: u64, - bytes: u64, -} - -impl Tally { - const fn add(&mut self, node: &Node) { - if node.is_dir() { - // A subtree taken whole from an earlier scan. - self.files += node.files; - self.dirs += node.dirs as u64; - } else { - // A link counts as a file on the meter, as it always has, - // though the tree does not count it. - self.files += 1; - } - // Saturating: see `tree::aggregate`. - self.bytes = node.bytes.saturating_add(self.bytes); - } - - fn flush(&mut self, progress: &ScanProgress, path: &Path) { - progress.preview_add(path, self.bytes, self.files); - progress.add(self.files, self.dirs, self.bytes); - *self = Self::default(); - } -} - -/// Read one directory, spawn a task per subdirectory, then report completion. -/// -/// Flat tasks inside the scope: the worker stack never grows with tree depth. -fn dispatch_fixed<'scope>( - scope: &Scope<'scope>, - dir: &Arc, - context: &'scope WalkContext, -) { - for child in walk(dir, context) { - scope.spawn(move |scope| { - dispatch_fixed(scope, &child, context); - }); - } -} - -/// Read one directory, spawn a task per subdirectory, then report completion. -/// -/// Flat tasks inside the scope: the worker stack never grows with tree depth. -fn dispatch<'scope>( - scope: &Scope<'scope>, - jobs: Vec>, - context: &'scope WalkContext, - admission: &Arc>>, -) { - for dir in jobs { - let admission = Arc::clone(admission); - scope.spawn(move |scope| { - let mut next = Some(dir); - while let Some(dir) = next.take() { - let children = walk(&dir, context); - let mut jobs = admission.complete(children); - // Continue locally into one ready descendant; only surplus - // jobs are offered to other workers. A running directory is - // never split, and a retirement returns from this loop. - next = jobs.pop(); - dispatch(scope, jobs, context, &admission); - } - }); - } -} - -fn walk(dir: &Arc, context: &WalkContext) -> Vec> { - if context.cancelled() { - // Queued jobs still own a pending token even when no I/O is needed. - signal_done(dir, context); - return Vec::new(); - } - let mut subdirs: Vec> = Vec::new(); - let mut leaves: Vec = Vec::new(); - let mut tally = Tally::default(); - - match list(&dir.path, context.volume.get().copied()) { - Ok(entries) => { - for entry in entries { - if context.cancelled() { - break; - } - match entry { - Ok(mut entry) => { - match context.classify(&dir.path, &mut entry) { - Classified::Subdirectory { path, name } => { - tally.dirs += 1; - subdirs.push(Arc::new(PendingDir::new( - path, - name, - Some(Arc::clone(dir)), - dir.depth + 1, - ))); - } - Classified::Entry(node) => { - tally.add(&node); - leaves.push(node); - } - Classified::Skipped => {} - } - if tally.files + tally.dirs >= TALLY_EVERY { - tally.flush(&context.progress, &dir.path); - } - } - Err(error) => { - context.progress.record_error(&dir.path, &error); - } - } - } - } - Err(error) => { - context.progress.record_error(&dir.path, &error); - dir.read_error.store(true, Ordering::Relaxed); - } - } - tally.flush(&context.progress, &dir.path); - - // A depth-limited scan still measures what is directly in the directory, - // it just does not descend further. - let descend = context - .options - .max_depth - .is_none_or(|max_depth| dir.depth < max_depth); - // Sized once for the leaves and every subdirectory to come, before any - // subdirectory task can push its node: otherwise that first push - // doubles a list just sized to the leaves, and the slack stays in the - // finished tree. The leaves are copied, not moved: the list they grew - // in carries up to twice their size in slack, and moving it in whole - // made a home directory walk a second slower (measured, 5 interleaved - // pairs). - let spawned = if descend { subdirs.len() } else { 0 }; - { - let mut partial = lock(&dir.partial); - partial.children.reserve_exact(leaves.len() + spawned); - partial.children.extend(leaves); - } - let mut children = Vec::new(); - if descend { - for subdir in subdirs { - if context.cancelled() { - break; - } - dir.pending.fetch_add(1, Ordering::AcqRel); - children.push(subdir); - } - } - - signal_done(dir, context); - children -} - -/// Report that one task for `dir` is done: either its own scan, or one of its -/// children. The last one to report builds the node and bubbles up. -/// -/// This is the whole reason for the `+1` sentinel: a directory is only built -/// once its own scan *and* every subdirectory task has finished, no matter -/// which of them lands last. -fn signal_done(dir: &Arc, context: &WalkContext) { - if dir.pending.fetch_sub(1, Ordering::AcqRel) != 1 { - return; - } - let node = dir.build(); - let Some(parent) = &dir.parent else { - *lock(&context.root) = Some(node); - return; - }; - lock(&parent.partial).children.push(node); - signal_done(parent, context); -} - -/// Charge a hardlinked file once, derive every aggregate from the result, -/// then classify. On the walk's pool: the UI's own work on the global pool -/// must not queue behind a scan finishing. -fn finish_tree( - mut node: Node, - options: &ScanOptions, - pool: &rayon::ThreadPool, -) -> Node { - pool.install(|| { - if options.dedup_hardlinks { - aggregate_deduped(&mut node, options.metric, &Seen::new()); - } else { - aggregate(&mut node, options.metric); - } - crate::classify::classify(&mut node); - }); - node -} - -/// A leaf. Its identity is kept only when `track` says the walk could meet -/// the same file again: a hardlink de-duplication set of every file on a -/// disk is millions of entries, nearly all for files with one name. -fn leaf_node( - name: Box, - kind: NodeKind, - facts: &Facts, - track: bool, -) -> Node { - let mut node = Node::entry(name, kind, facts.size); - if track { - node.inode = facts - .identity - .and_then(|(device, file)| Some((device, NonZeroU64::new(file)?))); - } - node.modified = facts.modified; - node -} - -/// Last write time in Unix seconds, from the metadata the walk already has: -/// age costs no extra system call. -pub(crate) fn modified_seconds(meta: &Metadata) -> i64 { - meta.modified() - .ok() - .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok()) - .map_or(0, |since| { - i64::try_from(since.as_secs()).unwrap_or(i64::MAX) - }) -} - -pub(crate) fn measure(meta: &Metadata, apparent_size: bool) -> u64 { - if apparent_size { - meta.len() - } else { - allocated_bytes(meta).unwrap_or(meta.len()) - } -} - -/// Allocated bytes, `st_blocks * 512`: sparse files spend less than they claim, -/// and this is the number that matches `du`. -/// -/// Returns `Option` because only Unix reports allocated blocks; elsewhere the -/// caller falls back to the apparent length. -#[allow( - clippy::unnecessary_wraps, - reason = "the Option is the non-Unix answer, where the caller falls back" -)] -#[cfg(unix)] -fn allocated_bytes(meta: &Metadata) -> Option { - use std::os::unix::fs::MetadataExt as _; - Some(meta.blocks().saturating_mul(512)) -} - -#[cfg(not(unix))] -const fn allocated_bytes(_meta: &Metadata) -> Option { - None -} - -/// Whether a directory's contents are only in the cloud: an iCloud Drive or -/// File Provider folder macOS has evicted. Listing one makes macOS fetch its -/// entries from the server, so a disk scan must not; the folder holds no -/// local blocks, so skipping it loses nothing a scan measures. -/// -/// A `stat` or `lstat` carries the flag without touching the contents. -#[cfg(target_os = "macos")] -fn is_dataless(meta: &Metadata) -> bool { - use std::os::macos::fs::MetadataExt as _; - // `SF_DATALESS` from ; the libc crate does not name it. - const SF_DATALESS: u32 = 0x4000_0000; - meta.st_flags() & SF_DATALESS != 0 -} - -#[cfg(not(target_os = "macos"))] -const fn is_dataless(_meta: &Metadata) -> bool { - false -} - -/// Whether the file has more than one name, so the walk can count it twice. -#[cfg(unix)] -fn shares_inode(meta: &Metadata) -> bool { - use std::os::unix::fs::MetadataExt as _; - meta.nlink() > 1 -} - -#[cfg(not(unix))] -const fn shares_inode(_meta: &Metadata) -> bool { - false -} - -#[cfg(unix)] -fn device_of(meta: &Metadata) -> u64 { - use std::os::unix::fs::MetadataExt as _; - meta.dev() -} - -#[cfg(not(unix))] -const fn device_of(_meta: &Metadata) -> u64 { - 0 -} - -/// `(device, inode)`, or `None` where the platform does not expose them. -/// Hardlink de-duplication and symlink loop detection both depend on this, so -/// they are simply unavailable rather than silently wrong elsewhere. Windows -/// has no file id in `Metadata` on stable Rust; its listing carries one -/// instead (see [`crate::windows`]). -#[allow( - clippy::unnecessary_wraps, - reason = "the Option is the non-Unix answer, so both arms must agree" -)] -#[cfg(unix)] -fn file_identity(meta: &Metadata) -> Option<(u64, u64)> { - use std::os::unix::fs::MetadataExt as _; - Some((meta.dev(), meta.ino())) -} - -#[cfg(not(unix))] -const fn file_identity(_meta: &Metadata) -> Option<(u64, u64)> { - None -} - -/// The identity of what `path` leads to, `meta` being its followed -/// metadata: how a walk that follows links recognizes a directory it has -/// entered before, and a file it has already charged. -#[cfg(not(windows))] -fn identity_of(_path: &Path, meta: &Metadata) -> Option<(u64, u64)> { - file_identity(meta) -} - -#[cfg(windows)] -fn identity_of(path: &Path, _meta: &Metadata) -> Option<(u64, u64)> { - crate::windows::identity(path) -} - -fn kind_of(meta: &Metadata, file_type: fs::FileType) -> NodeKind { - if meta.is_dir() || file_type.is_dir() { - NodeKind::Directory - } else if meta.is_file() || file_type.is_file() { - NodeKind::File - } else if file_type.is_symlink() { - NodeKind::Symlink - } else { - NodeKind::Other - } -} - -/// The display name of a scanned root: its final component, or the path itself -/// for `/`. -pub(crate) fn file_name(path: &Path) -> Box { - path.file_name() - .map_or_else( - || path.to_string_lossy().into_owned(), - |name| name.to_string_lossy().into_owned(), - ) - .into() -} - -/// A poisoned lock means another task panicked; the data is still a valid tree -/// prefix, and refusing to read it would turn one panic into two. -pub(crate) fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { - mutex.lock().unwrap_or_else(PoisonError::into_inner) +pub(crate) fn lock(mutex: &Mutex) -> std::sync::MutexGuard<'_, T> { + mutex + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) } #[cfg(test)] mod tests { - use super::*; - use crate::tree::Metric; use std::fs; + + use super::*; use tempfile::TempDir; - /// Apparent sizes, so the assertions are about the tree rather than about - /// how the filesystem rounds a small file up to a block. - fn options() -> ScanOptions { + fn scan_dir(path: &Path, options: &ScanOptions) -> Node { + scan(path, *options).expect("scan succeeds") + } + + fn apparent() -> ScanOptions { ScanOptions { apparent_size: true, ..ScanOptions::default() } } - fn write(root: &Path, relative: &str, bytes: usize) -> PathBuf { - let path = root.join(relative); - fs::create_dir_all(path.parent().expect("parent")).expect("mkdir"); - fs::write(&path, vec![b'x'; bytes]).expect("write"); - path - } - - fn scan_dir(root: &Path, options: &ScanOptions) -> Node { - scan(root, options.clone()).expect("scan") - } - - fn child<'a>(node: &'a Node, name: &str) -> &'a Node { - node.children - .iter() - .find(|child| &*child.name == name) - .unwrap_or_else(|| { - panic!("no child named {name} in {:?}", node.name) - }) - } - - #[test] - fn fixed_worker_pools_change_size_without_reinitializing_rayon() { - let cpus = thread::available_parallelism().map_or(1, usize::from); - // Two live pools have independent limits; constructing the first must - // not freeze the choice for a later scan or the global UI pool. - let make = |count| { - fixed_pool(ScanThreads { - max_threads: count, - ..ScanThreads::default() - }) - .expect("pool") - .expect("explicit fixed pool") - }; - let small = make(1); - let large = make(4); - assert_eq!(small.install(rayon::current_num_threads), 1); - assert_eq!(large.install(rayon::current_num_threads), 4.min(cpus)); - assert!( - fixed_pool(ScanThreads::default()) - .expect("default") - .is_none() - ); - assert!( - fixed_pool(ScanThreads { - adaptive: true, - max_threads: 4, - ..ScanThreads::default() - }) - .expect("adaptive") - .is_none() - ); - } - - #[test] - fn fixed_worker_pools_preserve_a_wide_deep_tree() { - let temp = TempDir::new().expect("tempdir"); - for index in 0..96 { - write(temp.path(), &format!("d{index}/nested/file"), index + 1); - } - for threads in [1, 2, 4, 8, usize::MAX] { - let mut settings = options(); - settings.threads.max_threads = threads; - let tree = scan_dir(temp.path(), &settings); - assert_eq!(tree.files, 96); - assert_eq!(tree.dirs, 193); - assert_eq!(tree.bytes, (1..=96).sum::()); - } - } - - #[test] - fn cancelled_queued_jobs_release_parent_completion_tokens() { - let temp = TempDir::new().expect("tempdir"); - for index in 0..128 { - write(temp.path(), &format!("d{index}/file"), 1); - } - let progress = Arc::new(ScanProgress::default()); - let context = Arc::new(WalkContext { - known: None, - options: options(), - progress: Arc::clone(&progress), - root_device: Mutex::new(None), - foreign_mounts: OnceLock::new(), - never_scanned: OnceLock::new(), - visited_dirs: Mutex::new(FxHashSet::default()), - root: Mutex::new(None), - volume: OnceLock::new(), - }); - let root = Arc::new(PendingDir::new( - temp.path().to_path_buf(), - file_name(temp.path()), - None, - 0, - )); - let queued = walk(&root, &context); - assert_eq!(queued.len(), 128); - assert!(lock(&context.root).is_none()); - progress.cancel(); - for dir in queued { - assert!(walk(&dir, &context).is_empty()); - } - let tree = lock(&context.root).take().expect("root completed"); - assert_eq!(tree.children.len(), 128); - assert!(tree.children.iter().all(|child| child.children.is_empty())); - } - #[test] fn totals_are_summed_bottom_up() { let temp = TempDir::new().expect("tempdir"); - let root = temp.path(); - write(root, "a/one.bin", 1000); - write(root, "a/nested/two.bin", 2000); - write(root, "b/three.bin", 500); + fs::create_dir_all(temp.path().join("a/b")).expect("mkdir"); + fs::write(temp.path().join("root.txt"), b"12345").expect("write"); + fs::write(temp.path().join("a/one.txt"), b"1234567890").expect("write"); + fs::write(temp.path().join("a/b/two.txt"), b"123").expect("write"); - let tree = scan_dir(root, &options()); - assert_eq!(tree.bytes, 3500); + let tree = scan_dir(temp.path(), &apparent()); + assert_eq!(tree.bytes, 18); assert_eq!(tree.files, 3); - assert_eq!(tree.dirs, 4, "root, a, a/nested, b"); - assert_eq!(child(&tree, "a").bytes, 3000); - assert_eq!(child(child(&tree, "a"), "nested").bytes, 2000); - assert_eq!(child(&tree, "b").bytes, 500); - } - - #[test] - fn children_are_ranked_largest_first() { - let temp = TempDir::new().expect("tempdir"); - let root = temp.path(); - write(root, "small.bin", 10); - write(root, "large.bin", 1000); - write(root, "medium.bin", 100); - - let tree = scan_dir(root, &options()); - let names: Vec<&str> = tree.children.iter().map(|c| &*c.name).collect(); - assert_eq!(names, vec!["large.bin", "medium.bin", "small.bin"]); + assert_eq!(tree.dirs, 3); + let a = tree.child_named("a").expect("a"); + assert_eq!(a.bytes, 13); + assert_eq!(a.files, 2); + assert_eq!(a.dirs, 2); } #[test] fn a_directory_reports_its_own_bytes_separately() { let temp = TempDir::new().expect("tempdir"); - let root = temp.path(); - write(root, "direct.bin", 700); - write(root, "sub/deep.bin", 300); + fs::create_dir(temp.path().join("sub")).expect("mkdir"); + fs::write(temp.path().join("direct.bin"), [0_u8; 40]).expect("write"); + fs::write(temp.path().join("sub/nested.bin"), [0_u8; 60]) + .expect("write"); - let tree = scan_dir(root, &options()); - assert_eq!(tree.own_bytes(), 700); + let tree = scan_dir(temp.path(), &apparent()); + assert_eq!(tree.own_bytes(), 40); assert_eq!(tree.own_files(), 1); - assert_eq!(tree.bytes, 1000); - assert_eq!(tree.files, 2); + assert_eq!(tree.bytes, 100); + } + + #[test] + fn children_are_ranked_largest_first() { + let temp = TempDir::new().expect("tempdir"); + fs::write(temp.path().join("small"), [0_u8; 10]).expect("write"); + fs::write(temp.path().join("huge"), [0_u8; 1000]).expect("write"); + fs::write(temp.path().join("medium"), [0_u8; 100]).expect("write"); + + let tree = scan_dir(temp.path(), &apparent()); + let names: Vec<&str> = + tree.children.iter().map(|c| c.name.as_ref()).collect(); + assert_eq!(names, ["huge", "medium", "small"]); + } + + #[test] + fn file_count_metric_ranks_by_entries() { + let temp = TempDir::new().expect("tempdir"); + fs::create_dir(temp.path().join("many")).expect("mkdir"); + for i in 0..5 { + fs::write(temp.path().join(format!("many/{i}")), b"x") + .expect("write"); + } + fs::write(temp.path().join("big"), [0_u8; 10_000]).expect("write"); + + let tree = scan_dir( + temp.path(), + &ScanOptions { + metric: Metric::Files, + ..apparent() + }, + ); + assert_eq!(tree.children[0].name.as_ref(), "many"); + assert_eq!(tree.children[1].name.as_ref(), "big"); } #[test] fn hardlinks_are_charged_once_by_default() { let temp = TempDir::new().expect("tempdir"); - let root = temp.path(); - let original = write(root, "original.bin", 4096); - fs::hard_link(&original, root.join("link.bin")).expect("hard link"); + let original = temp.path().join("original.bin"); + fs::write(&original, [0_u8; 4096]).expect("write"); + fs::hard_link(&original, temp.path().join("second.bin")) + .expect("hard_link"); - let deduped = scan_dir(root, &options()); + let deduped = scan_dir(temp.path(), &apparent()); assert_eq!(deduped.bytes, 4096); - assert_eq!(deduped.files, 2, "both names still exist"); + assert_eq!(deduped.files, 2); - let counted = scan_dir( - root, + let raw = scan_dir( + temp.path(), &ScanOptions { dedup_hardlinks: false, - ..options() + ..apparent() }, ); - assert_eq!(counted.bytes, 8192); + assert_eq!(raw.bytes, 8192); } #[test] fn hidden_entries_are_included_by_default_and_excluded_on_request() { let temp = TempDir::new().expect("tempdir"); - let root = temp.path(); - write(root, ".cache/blob.bin", 900); - write(root, "visible.bin", 100); + fs::create_dir(temp.path().join(".cache")).expect("mkdir"); + fs::write(temp.path().join(".cache/blob"), [0_u8; 500]).expect("write"); + fs::write(temp.path().join("visible"), [0_u8; 50]).expect("write"); - let default = scan_dir(root, &options()); - assert_eq!(default.bytes, 1000); - assert_eq!(child(&default, ".cache").bytes, 900); + let with_hidden = scan_dir(temp.path(), &apparent()); + assert_eq!(with_hidden.bytes, 550); + assert!(with_hidden.child_named(".cache").is_some()); - let without = scan_dir( - root, + let without_hidden = scan_dir( + temp.path(), &ScanOptions { include_hidden: false, - ..options() + ..apparent() }, ); - assert_eq!(without.bytes, 100); + assert_eq!(without_hidden.bytes, 50); + assert!(without_hidden.child_named(".cache").is_none()); } - /// Explorer's hidden attribute counts as hidden, as `AppData` has it. - #[cfg(windows)] #[test] - fn the_hidden_attribute_hides_an_entry_on_windows() { + fn max_depth_stops_descending_but_keeps_direct_files() { let temp = TempDir::new().expect("tempdir"); - let root = temp.path(); - write(root, "AppData/blob.bin", 900); - write(root, "visible.bin", 100); - let marked = std::process::Command::new("attrib") - .arg("+h") - .arg(root.join("AppData")) - .status() - .is_ok_and(|status| status.success()); - assert!(marked, "attrib +h"); + fs::create_dir_all(temp.path().join("a/b/c")).expect("mkdir"); + fs::write(temp.path().join("root.txt"), [0_u8; 10]).expect("write"); + fs::write(temp.path().join("a/one.txt"), [0_u8; 20]).expect("write"); + fs::write(temp.path().join("a/b/two.txt"), [0_u8; 40]).expect("write"); + fs::write(temp.path().join("a/b/c/three.txt"), [0_u8; 80]) + .expect("write"); - let without = scan_dir( - root, + let shallow = scan_dir( + temp.path(), &ScanOptions { - include_hidden: false, - ..options() + max_depth: Some(1), + ..apparent() }, ); - assert_eq!(without.bytes, 100); - } - - /// A link to a directory: a symbolic link on Unix, a junction on - /// Windows, which needs no privilege to make. `false` if it could not be - /// made. - fn link_dir(target: &Path, link: &Path) -> bool { - #[cfg(unix)] - { - std::os::unix::fs::symlink(target, link).is_ok() - } - #[cfg(windows)] - { - crate::windows::make_junction(link, target) - } + assert_eq!(shallow.bytes, 30); + assert_eq!(shallow.files, 2); } + #[cfg(unix)] #[test] fn symlinks_are_not_followed_by_default() { - let temp = TempDir::new().expect("tempdir"); - let outside = TempDir::new().expect("tempdir"); - write(outside.path(), "elsewhere.bin", 5000); - let root = temp.path(); - write(root, "real.bin", 100); - assert!(link_dir(outside.path(), &root.join("link")), "a link"); + use std::os::unix::fs::symlink; - let tree = scan_dir(root, &options()); - // Only the real file's bytes; the link itself holds just its target - // string, and its 5000-byte destination is outside this tree. - assert!(tree.bytes < 200, "{}", tree.bytes); - let link = child(&tree, "link"); + let temp = TempDir::new().expect("tempdir"); + let outside = TempDir::new().expect("outside"); + fs::write(outside.path().join("huge.bin"), [0_u8; 10_000]) + .expect("write"); + symlink(outside.path(), temp.path().join("escape")).expect("symlink"); + + let safe = scan_dir(temp.path(), &apparent()); + assert!(safe.bytes < 10_000, "symlink target was counted"); + let link = safe.child_named("escape").expect("link"); assert_eq!(link.kind, NodeKind::Symlink); - assert!(link.bytes < 100, "a link holds only its target string"); - } - #[test] - fn followed_symlink_loops_do_not_hang_the_scan() { - let temp = TempDir::new().expect("tempdir"); - let root = temp.path(); - write(root, "sub/leaf.bin", 42); - assert!(link_dir(root, &root.join("sub/loop")), "a link"); - - let tree = scan_dir( - root, + let followed = scan_dir( + temp.path(), &ScanOptions { follow_links: true, - ..options() + one_filesystem: false, + ..apparent() }, ); - assert_eq!(tree.bytes, 42); + assert_eq!(followed.bytes, 10_000); } - /// Disk usage is what the volume allocated, not the length: whole - /// blocks, so it covers the data and ends on a block boundary. + #[cfg(unix)] + #[test] + fn followed_symlink_loops_do_not_hang_the_scan() { + use std::os::unix::fs::symlink; + + let temp = TempDir::new().expect("tempdir"); + fs::create_dir(temp.path().join("sub")).expect("mkdir"); + fs::write(temp.path().join("sub/file"), [0_u8; 100]).expect("write"); + symlink(temp.path(), temp.path().join("sub/back")).expect("symlink"); + + let tree = scan_dir( + temp.path(), + &ScanOptions { + follow_links: true, + ..apparent() + }, + ); + assert_eq!(tree.bytes, 100); + } + + #[cfg(unix)] #[test] fn disk_usage_is_whole_allocation_units() { let temp = TempDir::new().expect("tempdir"); - // Noise, so a compressing filesystem cannot store it in less. - let mut state = 0x2545_f491_4f6c_dd1d_u64; + // Incompressible bytes so a compressing filesystem still allocates blocks. + let mut state = 0x9e37_79b9_7f4a_7c15_u64; let noise: Vec = (0..100_000) .map(|_| { state ^= state << 13; @@ -1674,9 +875,6 @@ mod tests { state.to_le_bytes()[0] }) .collect(); - // Flush and sync before scanning: on CoW filesystems with delayed - // allocation (such as OpenZFS), asynchronous writes remain buffered - // in transaction groups and report st_blocks = 1 until synced. let mut file = fs::File::create(temp.path().join("data.bin")).expect("create"); std::io::Write::write_all(&mut file, &noise).expect("write"); @@ -1685,192 +883,110 @@ mod tests { let tree = scan_dir(temp.path(), &ScanOptions::default()); assert!(tree.bytes >= 100_000, "{}", tree.bytes); assert_eq!(tree.bytes % 512, 0, "{}", tree.bytes); - let apparent = scan_dir(temp.path(), &options()); - assert_eq!(apparent.bytes, 100_000); - } - - #[test] - fn max_depth_stops_descending_but_keeps_direct_files() { - let temp = TempDir::new().expect("tempdir"); - let root = temp.path(); - write(root, "here.bin", 10); - write(root, "a/there.bin", 20); - write(root, "a/b/far.bin", 30); - - let tree = scan_dir( - root, - &ScanOptions { - max_depth: Some(1), - ..options() - }, - ); - assert_eq!(tree.own_bytes(), 10); - let a = child(&tree, "a"); - assert_eq!( - a.bytes, 20, - "direct files at the cut-off depth still count" - ); - assert!( - a.children.iter().all(|child| !child.is_dir()), - "descending stopped at depth 1" - ); - assert_eq!(a.files, 1); - } - - #[test] - fn file_count_metric_ranks_by_entries() { - let temp = TempDir::new().expect("tempdir"); - let root = temp.path(); - for index in 0..5 { - write(root, &format!("many/f{index}.bin"), 1); - } - write(root, "one/huge.bin", 100_000); - - let tree = scan_dir(root, &options()); - assert_eq!(child(&tree, "one").bytes, 100_000); - assert_eq!(tree.children[0].name.as_ref(), "one"); - - let by_files = scan_dir( - root, - &ScanOptions { - metric: Metric::Files, - ..options() - }, - ); - assert_eq!(by_files.children[0].name.as_ref(), "many"); - assert_eq!(by_files.children[0].files, 5); } #[cfg(unix)] #[test] fn an_unreadable_directory_is_recorded_not_fatal() { use std::os::unix::fs::PermissionsExt as _; + + if rustix::process::geteuid().is_root() { + return; + } let temp = TempDir::new().expect("tempdir"); - let root = temp.path(); - write(root, "readable.bin", 11); - let locked = root.join("locked"); - fs::create_dir_all(&locked).expect("mkdir"); - write(&locked, "hidden.bin", 22); + let locked = temp.path().join("locked"); + fs::create_dir(&locked).expect("mkdir"); + fs::write(locked.join("secret"), b"nope").expect("write"); + fs::write(temp.path().join("open"), b"hello").expect("write"); fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)) .expect("chmod"); - // Running as root would bypass the permission bits entirely. - let readable = fs::read_dir(&locked).map(|mut it| it.next().is_some()); - let progress = Arc::new(ScanProgress::default()); - let context = Arc::new(WalkContext { - known: None, - options: options(), - progress: Arc::clone(&progress), - root_device: Mutex::new(None), - foreign_mounts: OnceLock::new(), - never_scanned: OnceLock::new(), - visited_dirs: Mutex::new(FxHashSet::default()), - root: Mutex::new(None), - volume: OnceLock::new(), - }); - let tree = scan_blocking(root, &context).expect("scan still succeeds"); - let _ = fs::set_permissions(&locked, fs::Permissions::from_mode(0o700)); + let tree = scan_dir(temp.path(), &apparent()); + fs::set_permissions(&locked, fs::Permissions::from_mode(0o700)) + .expect("restore"); - assert_eq!(tree.bytes, 11); - let node = child(&tree, "locked"); - if matches!(readable, Ok(false)) { - assert!(node.read_error); - assert!(progress.snapshot().errors >= 1); - assert!(!progress.snapshot().messages.is_empty()); - } + assert_eq!(tree.bytes, 5); + assert!(tree.child_named("locked").expect("locked").read_error); } #[test] fn a_file_root_is_rejected() { let temp = TempDir::new().expect("tempdir"); - let path = write(temp.path(), "file.bin", 1); - let error = scan(&path, options()).expect_err("a file is not a tree"); - assert_eq!(error.kind(), io::ErrorKind::InvalidInput); + let file = temp.path().join("file.txt"); + fs::write(&file, b"hi").expect("write"); + let err = scan(&file, apparent()).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidInput); } #[test] fn a_spawned_scan_reports_progress_and_a_result() { let temp = TempDir::new().expect("tempdir"); - let root = temp.path(); - write(root, "a/one.bin", 1024); - write(root, "b/two.bin", 2048); + fs::write(temp.path().join("a"), [0_u8; 50]).expect("write"); + fs::write(temp.path().join("b"), [0_u8; 75]).expect("write"); - let handle = ScanHandle::spawn(root.to_path_buf(), options()); - let mut outcome = None; - for _ in 0..2000 { - if let Some(result) = handle.poll() { - outcome = Some(result); - break; + let handle = ScanHandle::spawn(temp.path().to_path_buf(), apparent()); + let tree = loop { + if let Some(outcome) = handle.poll() { + break outcome.expect("scan"); } - thread::sleep(std::time::Duration::from_millis(1)); - } - let tree = outcome.expect("the scan finished").expect("a tree"); - assert_eq!(tree.bytes, 3072); - - let snapshot = handle.progress.snapshot(); - assert!(snapshot.finished); - assert_eq!(snapshot.files, 2); - assert_eq!(snapshot.errors, 0); - let preview = handle.progress.preview(); - assert!( - preview - .entries - .iter() - .any(|e| e.name == "a" && e.bytes == 1024) - ); - assert!( - preview - .entries - .iter() - .any(|e| e.name == "b" && e.bytes == 2048) - ); - assert_eq!( - preview.entries.iter().map(|e| e.bytes).sum::(), - tree.bytes - ); + thread::sleep(std::time::Duration::from_millis(5)); + }; + assert_eq!(tree.bytes, 125); + let snap = handle.progress.snapshot(); + assert!(snap.finished); + assert_eq!(snap.files, 2); } #[test] fn a_wider_scan_reuses_the_subtree_it_already_knows() { - let temp = tempfile::tempdir().expect("tempdir"); + let temp = TempDir::new().expect("tempdir"); let root = temp.path().canonicalize().expect("canonical"); let inner = root.join("inner"); - fs::create_dir_all(inner.join("deep")).expect("mkdir"); - fs::write(inner.join("deep/a.bin"), vec![0_u8; 4096]).expect("write"); - fs::write(root.join("outside.bin"), vec![0_u8; 8192]).expect("write"); - let known = scan(&inner, options()).expect("inner scan"); + fs::create_dir(&inner).expect("mkdir"); + fs::write(inner.join("a.bin"), [0_u8; 200]).expect("write"); + fs::write(root.join("outside.bin"), [0_u8; 50]).expect("write"); - // Changed on disk after the inner scan: a memoized subtree must not - // see it, which is how this test knows the walk skipped it. - fs::write(inner.join("deep/b.bin"), vec![0_u8; 4096]).expect("write"); + let scanner_opts = apparent().to_scanner(); + let known_arena = Arc::new( + walk_parallel( + &inner, + WalkConfig { + options: &scanner_opts, + cancel: Arc::new(AtomicBool::new(false)), + progress: Arc::new(WalkProgress::default()), + pause_gate: None, + skip_oracle: None, + on_dir_start: None, + on_dir_tally: None, + }, + ) + .expect("inner") + .arena, + ); + // Add a new file inside `inner` after the narrow scan: reusing `known` + // proves `inner` was grafted rather than re-walked. + fs::write(inner.join("b.bin"), [0_u8; 999]).expect("write"); let handle = ScanHandle::spawn_with( root, - options(), + apparent(), Some(Known { path: inner, - tree: Arc::new(known.clone()), + arena: known_arena, }), ); let tree = loop { if let Some(outcome) = handle.poll() { - break outcome.expect("wide scan"); + break outcome.expect("wider"); } - thread::sleep(std::time::Duration::from_millis(2)); + thread::sleep(std::time::Duration::from_millis(5)); }; - let reused = tree.child_named("inner").expect("inner is in the tree"); - assert_eq!(reused.files, known.files, "b.bin was never read"); - assert_eq!(reused.bytes, known.bytes); - assert!( - tree.child_named("outside.bin").is_some(), - "the rest was walked" - ); - assert_eq!(tree.files, known.files + 1); + let reused = tree.child_named("inner").expect("inner"); + assert_eq!(reused.bytes, 200, "b.bin was never read"); + assert_eq!(reused.files, 1); + assert_eq!(tree.bytes, 250); } - /// A real whole-disk scan, run by hand: `cargo test -p disktree-core - /// -- --ignored --nocapture whole_disk`. Prints what it found, so the - /// volume rules can be checked against this machine's mounts. #[test] #[ignore = "walks the whole disk"] fn whole_disk_smoke() { @@ -1891,19 +1007,5 @@ mod tests { child.name ); } - let skipped = - crate::space::foreign_mounts_for(&root).unwrap_or_default(); - println!("left out: {skipped:?}"); - for needle in ["c", "cache", "node_modules", "zzzz"] { - let started = std::time::Instant::now(); - let found = - crate::filter::filter(&tree, &[], needle).expect("needle"); - println!( - "filter {needle:?}: {} matches, {} in {:.1?}", - found.count, - crate::size::human_bytes(found.bytes), - started.elapsed() - ); - } } } diff --git a/crates/disktree-core/src/scan_threads.rs b/crates/disktree-core/src/scan_threads.rs deleted file mode 100644 index 5b0b43a..0000000 --- a/crates/disktree-core/src/scan_threads.rs +++ /dev/null @@ -1,733 +0,0 @@ -//! Scan-local admission: queued directories never occupy Rayon workers. - -use std::sync::{Mutex, MutexGuard, PoisonError}; - -/// Filesystem concurrency for one scan, independent of the global Rayon pool. -/// A scan crossing several volumes shares this budget; separate scans do not. -#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)] -pub struct ScanThreads { - /// Fixed scan workers, capped by available CPUs; `usize::MAX` uses the - /// shared platform-default pool. With `adaptive`, maximum admitted directory - /// jobs instead, including jobs awaiting a Rayon worker. - pub max_threads: usize, - /// Search below the cap and respond to whole-system CPU pressure. - pub adaptive: bool, - /// Fraction of initial entries/second a candidate must retain. - pub retained_throughput: f64, - /// Best-effort whole-system CPU ceiling; `None` disables the governor. - pub system_cpu_limit: Option, -} - -impl Default for ScanThreads { - fn default() -> Self { - Self { - // Preserve core callers' pool-sized fixed concurrency. The app - // supplies the user's Power Efficiency preset before scanning. - max_threads: usize::MAX, - // Adaptive admission remains an explicit experimental opt-in. - adaptive: false, - retained_throughput: 0.80, - system_cpu_limit: Some(0.80), - } - } -} - -impl ScanThreads { - pub(crate) fn normalized(self) -> Self { - Self { - max_threads: self.max_threads.max(1), - retained_throughput: if (0.0..=1.0) - .contains(&self.retained_throughput) - { - self.retained_throughput - } else { - 0.80 - }, - system_cpu_limit: self.system_cpu_limit.filter(|limit| { - limit.is_finite() && *limit > 0.0 && *limit <= 1.0 - }), - ..self - } - } -} - -pub(crate) struct Admission { - state: Mutex>, -} - -struct Queue { - pending: Vec, - active: usize, - limit: usize, - epoch: u64, - starved: bool, -} - -#[derive(Clone, Copy, Debug)] -pub(crate) struct Sample { - pub(crate) active: usize, - pub(crate) limit: usize, - pub(crate) epoch: u64, - pub(crate) starved: bool, -} - -impl Sample { - pub(crate) const fn settled(self) -> bool { - self.active <= self.limit - } -} - -impl Admission { - pub(crate) fn new(root: T, limit: usize) -> Self { - Self { - state: Mutex::new(Queue { - pending: vec![root], - active: 0, - limit: limit.max(1), - epoch: 0, - starved: false, - }), - } - } - - fn lock(&self) -> MutexGuard<'_, Queue> { - self.state.lock().unwrap_or_else(PoisonError::into_inner) - } - - pub(crate) fn start(&self) -> Vec { - Self::admit(&mut self.lock()) - } - - /// Each submitted job hands back its slot exactly once, after its own - /// parent-completion signal. Its children already hold pending tokens. - pub(crate) fn complete(&self, children: Vec) -> Vec { - let mut state = self.lock(); - state.active -= 1; - state.pending.extend(children); - let jobs = Self::admit(&mut state); - drop(state); - jobs - } - - fn admit(state: &mut Queue) -> Vec { - let count = state - .limit - .saturating_sub(state.active) - .min(state.pending.len()); - let split = state.pending.len() - count; - let jobs = state.pending.split_off(split); - state.active += jobs.len(); - state.starved |= state.active < state.limit; - jobs - } - - /// The same lock guards dispatch and changes, so a settled snapshot - /// cannot precede a late dispatch made using the old limit. - pub(crate) fn set_limit(&self, limit: usize) { - let mut state = self.lock(); - let limit = limit.max(1); - if state.limit != limit { - state.limit = limit; - state.epoch += 1; - } - } - - pub(crate) fn sample(&self) -> Sample { - let mut state = self.lock(); - Sample { - active: state.active, - limit: state.limit, - epoch: state.epoch, - // A long directory can remain undersupplied for many samples. - // Clearing the history must not erase the current condition, - // including an increase awaiting the next dispatch boundary. - starved: std::mem::take(&mut state.starved) - || state.active < state.limit, - } - } -} - -/// One reference, then a bounded accepted/rejected bracket. This targets a -/// sampled rate, not a guarantee about an evolving tree's completion time. -pub(crate) struct Search { - reference: Option, - accepted: usize, - rejected: usize, - candidate: usize, - passes: u8, - failures: u8, - windows: u8, - retained: f64, - pub(crate) done: bool, -} - -impl Search { - pub(crate) const fn new(initial: usize, retained: f64) -> Self { - Self { - reference: None, - accepted: initial, - rejected: 0, - candidate: initial, - passes: 0, - failures: 0, - windows: 0, - retained, - done: initial <= 1, - } - } - - pub(crate) fn sample(&mut self, rate: Option) -> usize { - if self.done { - return self.accepted; - } - let Some(reference) = self.reference else { - if let Some(rate) = rate.filter(|rate| *rate > 0.0) { - self.reference = Some(rate); - self.candidate = (self.accepted / 2).max(1); - self.windows = 0; - } else { - self.windows += 1; - self.done = self.windows == 3; - } - return self.candidate; - }; - self.windows += 1; - if let Some(rate) = rate { - if rate >= reference * self.retained { - self.passes += 1; - } else { - self.failures += 1; - } - } - if self.passes == 2 || self.failures == 2 || self.windows == 3 { - if self.passes == 2 { - self.accepted = self.candidate; - } else { - self.rejected = self.candidate; - } - self.done = self.accepted - self.rejected <= 1; - self.candidate = if self.done { - self.accepted - } else { - self.rejected + (self.accepted - self.rejected) / 2 - }; - self.passes = 0; - self.failures = 0; - self.windows = 0; - } - self.candidate - } -} - -pub(crate) struct Governor { - ceiling: Option, - cap: usize, - high: u8, - low: u8, - pub(crate) pressured: bool, -} - -impl Governor { - pub(crate) const fn new(cap: usize, ceiling: Option) -> Self { - Self { - ceiling, - cap, - high: 0, - low: 0, - pressured: false, - } - } - - pub(crate) fn admitted(&self, desired: usize) -> usize { - if self.ceiling.is_none() { - desired - } else { - desired.min(self.cap) - } - } - - pub(crate) fn sample( - &mut self, - usage: Option, - admitted: usize, - desired: usize, - settled: bool, - ) -> usize { - let Some(ceiling) = self.ceiling else { - return desired; - }; - if let Some(usage) = usage { - self.pressured = usage > ceiling; - if self.pressured { - self.low = 0; - self.high = self.high.saturating_add(1).min(2); - if self.high >= 2 && settled { - self.cap = (admitted / 2).max(1); - self.high = 0; - } - } else if usage < (ceiling - 0.05).max(0.0) { - self.high = 0; - self.low = self.low.saturating_add(1).min(4); - if self.low >= 4 && settled { - self.cap = (self.cap + 1).min(desired.max(self.cap)); - self.low = 0; - } - } else { - self.high = 0; - self.low = 0; - } - } else { - // Missing measurements cannot establish spare capacity. - self.high = 0; - self.low = 0; - } - desired.min(self.cap) - } -} - -use std::io; -use std::sync::atomic::Ordering; -use std::sync::{Arc, Condvar}; -use std::thread::{self, JoinHandle}; -use std::time::{Duration, Instant}; - -use crate::scan::ScanProgress; - -pub(crate) struct ControllerGuard { - stop: Arc<(Mutex, Condvar)>, - worker: Option>, -} - -impl ControllerGuard { - pub(crate) fn spawn( - options: ScanThreads, - admission: Arc>, - progress: Arc, - ) -> io::Result> { - if !options.adaptive { - return Ok(None); - } - let stop = Arc::new((Mutex::new(false), Condvar::new())); - let wake = Arc::clone(&stop); - let worker = thread::Builder::new() - .name("disktree-admission".into()) - .spawn(move || { - control(options, &admission, &progress, &wake); - })?; - Ok(Some(Self { - stop, - worker: Some(worker), - })) - } -} - -impl Drop for ControllerGuard { - fn drop(&mut self) { - *self.stop.0.lock().unwrap_or_else(PoisonError::into_inner) = true; - self.stop.1.notify_one(); - if let Some(worker) = self.worker.take() { - let _ = worker.join(); - } - } -} - -fn control( - options: ScanThreads, - admission: &Admission, - progress: &ScanProgress, - stop: &(Mutex, Condvar), -) { - let mut cpu = options.system_cpu_limit.map(|_| CpuSampler::new()); - control_with( - options, - admission, - progress, - stop, - Duration::from_millis(250), - || cpu.as_mut().and_then(CpuSampler::sample), - ); -} - -fn control_with( - options: ScanThreads, - admission: &Admission, - progress: &ScanProgress, - stop: &(Mutex, Condvar), - interval: Duration, - mut sample_cpu: impl FnMut() -> Option, -) { - // Two 250 ms votes distinguish a candidate from a transient burst. CPU - // counters are sampled less often because they have coarser resolution. - let mut search = - Search::new(options.max_threads, options.retained_throughput); - let mut governor = - Governor::new(options.max_threads, options.system_cpu_limit); - let mut desired = options.max_threads; - let mut cpu_at = Instant::now(); - let mut start = Instant::now(); - let mut entries = progress.entries(); - let mut epoch = 0; - let mut measuring = false; - loop { - let (stopped, _) = stop - .1 - .wait_timeout_while( - stop.0.lock().unwrap_or_else(PoisonError::into_inner), - interval, - |stopped| !*stopped, - ) - .unwrap_or_else(PoisonError::into_inner); - if *stopped || progress.is_cancelled() { - return; - } - drop(stopped); - let sample = admission.sample(); - let mut limit = sample.limit; - if cpu_at.elapsed() >= interval * 2 { - limit = governor.sample( - sample_cpu(), - sample.limit, - desired, - sample.settled(), - ); - cpu_at = Instant::now(); - } - let limited = governor.pressured || limit < desired; - progress - .system_cpu_limited - .store(limited, Ordering::Relaxed); - progress - .threads_settled - .store(sample.settled(), Ordering::Relaxed); - let current = progress.entries(); - let now = Instant::now(); - if limited || !sample.settled() || epoch != sample.epoch || !measuring { - measuring = !limited && sample.settled(); - } else if !search.done { - let rate = (!sample.starved && current > entries).then(|| { - (current - entries) as f64 - / now.duration_since(start).as_secs_f64() - }); - desired = search.sample(rate); - limit = governor.admitted(desired); - } - if limit != sample.limit { - admission.set_limit(limit); - progress.threads.store(limit, Ordering::Relaxed); - progress.worker_transitions.fetch_add(1, Ordering::Relaxed); - progress.threads_settled.store(false, Ordering::Relaxed); - measuring = false; - } - progress - .thread_tuning_complete - .store(search.done, Ordering::Relaxed); - entries = current; - start = now; - epoch = sample.epoch; - } -} - -struct CpuSampler { - #[cfg(any(target_os = "macos", target_os = "linux"))] - system: sysinfo::System, -} - -#[cfg_attr( - not(any(target_os = "macos", target_os = "linux")), - allow( - clippy::missing_const_for_fn, - clippy::unused_self, - reason = "The fallback mirrors the stateful, non-const native API." - ) -)] -impl CpuSampler { - fn new() -> Self { - #[cfg(any(target_os = "macos", target_os = "linux"))] - { - let mut system = sysinfo::System::new(); - system.refresh_cpu_usage(); - Self { system } - } - #[cfg(not(any(target_os = "macos", target_os = "linux")))] - Self {} - } - - fn sample(&mut self) -> Option { - #[cfg(any(target_os = "macos", target_os = "linux"))] - { - self.system.refresh_cpu_usage(); - let usage = f64::from(self.system.global_cpu_usage()) / 100.0; - // sysinfo reports zero on some native read failures. Conservatively - // ignore zero too: it must not be evidence for restoring workers. - (!self.system.cpus().is_empty() && usage > 0.0 && usage <= 1.0) - .then_some(usage) - } - #[cfg(not(any(target_os = "macos", target_os = "linux")))] - None - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::mpsc; - - #[test] - fn search_refines_one_reference_without_compounding_loss() { - let mut search = Search::new(8, 0.8); - assert_eq!(search.sample(Some(100.0)), 4); - assert_eq!(search.sample(Some(85.0)), 4); - assert_eq!(search.sample(Some(85.0)), 2); - assert_eq!(search.sample(Some(70.0)), 2); - assert_eq!(search.sample(Some(70.0)), 3); - assert_eq!(search.sample(Some(81.0)), 3); - assert_eq!(search.sample(Some(81.0)), 3); - assert!(search.done); - } - - #[test] - fn long_directory_never_becomes_a_fully_supplied_window() { - let admission = Admission::new(0, 8); - assert_eq!(admission.start(), vec![0]); - let mut search = Search::new(8, 0.8); - for _ in 0..6 { - let sample = admission.sample(); - assert!(sample.settled()); - assert!(sample.starved); - assert_eq!(search.sample((!sample.starved).then_some(100.0)), 8); - } - assert!(search.reference.is_none()); - assert!(search.done); - } - - #[test] - fn increased_limit_is_not_supplied_until_jobs_are_dispatched() { - let admission = Admission::new(0, 1); - assert_eq!(admission.start(), vec![0]); - assert_eq!(admission.complete((1..=8).collect()).len(), 1); - admission.set_limit(8); - let mut search = Search::new(16, 0.8); - assert_eq!(search.sample(Some(100.0)), 8); - for _ in 0..3 { - let sample = admission.sample(); - assert!(sample.settled()); - assert!(sample.starved); - search.sample((!sample.starved).then_some(100.0)); - } - // Even an apparently fast candidate cannot be accepted while only - // one job is admitted and the other ready jobs remain queued. - assert_eq!(search.accepted, 16); - assert_eq!(search.rejected, 8); - assert_eq!(admission.complete(vec![9]).len(), 8); - assert!(!admission.sample().starved); - } - - #[test] - fn inconclusive_windows_cannot_accept_a_reduction() { - let mut search = Search::new(4, 0.8); - assert_eq!(search.sample(Some(100.0)), 2); - for _ in 0..2 { - assert_eq!(search.sample(None), 2); - } - assert_eq!(search.sample(None), 3); - assert_eq!(search.sample(Some(90.0)), 3); - assert_eq!(search.sample(None), 3); - assert_eq!(search.sample(None), 4); - assert!(search.done); - } - - #[test] - fn governor_waits_for_retirement_and_recovers_without_exceeding_target() { - let mut governor = Governor::new(8, Some(0.8)); - assert_eq!(governor.sample(Some(0.9), 8, 8, true), 8); - assert_eq!(governor.sample(Some(0.9), 8, 8, true), 4); - for _ in 0..300 { - assert_eq!(governor.sample(Some(0.9), 4, 8, false), 4); - } - assert_eq!(governor.sample(Some(0.9), 4, 8, true), 2); - assert_eq!(governor.sample(None, 2, 8, true), 2); - for _ in 0..3 { - assert_eq!(governor.sample(Some(0.5), 2, 8, true), 2); - } - assert_eq!(governor.sample(Some(0.5), 2, 8, true), 3); - // A throughput decision does not manufacture a CPU-pressure cap. - let mut governor = Governor::new(8, Some(0.8)); - for _ in 0..4 { - assert_eq!(governor.sample(Some(0.5), 2, 2, true), 2); - } - assert_eq!(governor.admitted(8), 8); - } - - fn wait_until(mut ready: impl FnMut() -> bool) { - let deadline = Instant::now() + Duration::from_secs(5); - while !ready() { - assert!(Instant::now() < deadline, "controller timed out"); - thread::sleep(Duration::from_millis(1)); - } - } - - #[test] - fn controller_retires_recovers_after_search_and_cancels() { - let admission = Arc::new(Admission::new(0, 4)); - assert_eq!(admission.start(), vec![0]); - assert_eq!(admission.complete(vec![1, 2, 3, 4]).len(), 4); - let progress = Arc::new(ScanProgress::default()); - // 0 is missing, 1 is below the ceiling, 2 is above it. - let cpu = Arc::new(std::sync::atomic::AtomicUsize::new(1)); - let controller_admission = Arc::clone(&admission); - let controller_progress = Arc::clone(&progress); - let controller_cpu = Arc::clone(&cpu); - let controller = thread::spawn(move || { - control_with( - ScanThreads { - max_threads: 4, - adaptive: true, - ..ScanThreads::default() - }, - &controller_admission, - &controller_progress, - &(Mutex::new(false), Condvar::new()), - Duration::from_millis(2), - || match controller_cpu.load(Ordering::Relaxed) { - 1 => Some(0.5), - 2 => Some(0.95), - _ => None, - }, - ); - }); - // No entries gives an inconclusive bounded search. The governor must - // remain active after that search completes. - wait_until(|| progress.snapshot().thread_tuning_complete); - cpu.store(2, Ordering::Relaxed); - wait_until(|| admission.sample().limit == 2); - thread::sleep(Duration::from_millis(30)); - assert_eq!(admission.sample().limit, 2); - assert!(!progress.snapshot().threads_settled); - assert!(admission.complete(Vec::new()).is_empty()); - assert!(admission.complete(Vec::new()).is_empty()); - wait_until(|| admission.sample().limit == 1); - cpu.store(0, Ordering::Relaxed); - assert!(admission.complete(Vec::new()).is_empty()); - thread::sleep(Duration::from_millis(30)); - assert_eq!(admission.sample().limit, 1); - cpu.store(1, Ordering::Relaxed); - wait_until(|| admission.sample().limit == 4); - assert!(progress.snapshot().worker_transitions >= 5); - progress.cancel(); - controller.join().expect("cancelled controller"); - assert!(admission.complete(Vec::new()).is_empty()); - assert_eq!(admission.sample().active, 0); - } - - fn execute( - scope: &rayon::Scope<'_>, - jobs: Vec, - admission: &Arc>, - releases: &Arc>>>>, - started: &mpsc::Sender, - completed: &mpsc::Sender, - ) { - for job in jobs { - let admission = Arc::clone(admission); - let releases = Arc::clone(releases); - let started = started.clone(); - let completed = completed.clone(); - scope.spawn(move |scope| { - let children = if job == 0 { - (1..=4).collect() - } else if job <= 4 { - started.send(job).expect("started"); - let release = releases.lock().expect("releases")[job] - .take() - .expect("one receiver"); - release - .recv_timeout(Duration::from_secs(5)) - .expect("release"); - vec![job + 4] - } else { - Vec::new() - }; - let next = admission.complete(children); - completed.send(job).expect("completed"); - execute( - scope, next, &admission, &releases, &started, &completed, - ); - }); - } - } - - #[test] - fn real_pool_retires_at_job_boundaries_and_drains_queued_descendants() { - let admission = Arc::new(Admission::new(0, 4)); - let (started, starts) = mpsc::channel(); - let (completed, completions) = mpsc::channel(); - let (done, finished) = mpsc::channel(); - let mut senders = Vec::new(); - let mut receivers = Vec::new(); - for _ in 0..=4 { - let (send, receive) = mpsc::channel(); - senders.push(send); - receivers.push(Some(receive)); - } - let releases = Arc::new(Mutex::new(receivers)); - let worker_admission = Arc::clone(&admission); - let worker = thread::spawn(move || { - let pool = rayon::ThreadPoolBuilder::new() - .num_threads(4) - .build() - .expect("pool"); - pool.scope(|scope| { - execute( - scope, - worker_admission.start(), - &worker_admission, - &releases, - &started, - &completed, - ); - }); - done.send(()).expect("done"); - }); - assert_eq!( - completions - .recv_timeout(Duration::from_secs(5)) - .expect("root"), - 0 - ); - let mut running = Vec::new(); - for _ in 0..4 { - running.push( - starts.recv_timeout(Duration::from_secs(5)).expect("start"), - ); - } - admission.set_limit(1); - assert!(!admission.sample().settled()); - for (index, &job) in running[..3].iter().enumerate() { - senders[job].send(()).expect("release"); - assert_eq!( - completions - .recv_timeout(Duration::from_secs(5)) - .expect("done"), - job - ); - let sample = admission.sample(); - assert_eq!(sample.active, 3 - index); - assert_eq!(sample.settled(), index == 2); - } - // The last admitted job is still running; its siblings' descendants - // must remain ready rather than occupying blocked Rayon workers. - assert_eq!(admission.lock().pending.len(), 3); - admission.set_limit(2); - senders[running[3]].send(()).expect("last release"); - finished - .recv_timeout(Duration::from_secs(5)) - .expect("scope drained"); - worker.join().expect("worker"); - let mut remaining: Vec<_> = completions.try_iter().collect(); - remaining.sort_unstable(); - let mut expected = vec![running[3], 5, 6, 7, 8]; - expected.sort_unstable(); - assert_eq!(remaining, expected); - assert_eq!(admission.sample().active, 0); - } -} diff --git a/crates/disktree-core/src/space.rs b/crates/disktree-core/src/space.rs index 31c50af..10eede9 100644 --- a/crates/disktree-core/src/space.rs +++ b/crates/disktree-core/src/space.rs @@ -7,79 +7,11 @@ use std::io; use std::path::{Path, PathBuf}; -/// A volume's capacity in bytes. -#[derive( - Clone, - Copy, - Debug, - Default, - PartialEq, - Eq, - serde::Serialize, - serde::Deserialize, -)] -pub struct SpaceInfo { - /// Total size of the volume. - pub total: u64, - /// Free blocks, including the reserve only root may write to. - pub free: u64, - /// Free blocks this user may actually write; what `df -h` reports. - pub available: u64, -} - -impl SpaceInfo { - /// Space in use, computed from `free` rather than `available` so the figure - /// does not jump when a reserve is opened to root. - pub const fn used(&self) -> u64 { - self.total.saturating_sub(self.free) - } - - /// Share of the volume in use, `0.0..=1.0`. - pub fn used_fraction(&self) -> f32 { - if self.total == 0 { - 0.0 - } else { - (self.used() as f64 / self.total as f64) as f32 - } - } - - /// Free space after `bytes` are removed, saturating at the volume size and - /// never counting the same byte twice. - #[must_use] - pub fn after_removing(&self, bytes: u64) -> Self { - let available = self.available.saturating_add(bytes).min(self.total); - let free = self.free.saturating_add(bytes).min(self.total); - Self { - total: self.total, - free, - available, - } - } -} +pub use disktree_scanner::SpaceInfo; /// Read the space on the volume containing `path`. -#[cfg(windows)] pub fn space_info(path: &Path) -> io::Result { - crate::windows::space_info(path) -} - -/// Read the space on the volume containing `path`. -#[cfg(not(windows))] -pub fn space_info(path: &Path) -> io::Result { - let stat = rustix::fs::statvfs(path)?; - // `f_frsize` is the fragment size the block counts are expressed in; - // `f_bsize` is only a hint for I/O. Some filesystems report zero for - // `f_frsize`, so fall back rather than claiming a zero-sized volume. - let block = if stat.f_frsize == 0 { - stat.f_bsize - } else { - stat.f_frsize - }; - Ok(SpaceInfo { - total: stat.f_blocks.saturating_mul(block), - free: stat.f_bfree.saturating_mul(block), - available: stat.f_bavail.saturating_mul(block), - }) + disktree_scanner::space_info(path) } /// The volume a path is on, as Windows names it: `C:\`, a share, or the @@ -397,6 +329,69 @@ pub fn mount_boundaries(mounts: &[Mount], root: &Path) -> Vec { .collect() } +/// Boundaries for a local scan. +/// +/// Distinct Btrfs subvolumes on the same filesystem contribute to the same +/// disk and should be visible together. Overlapping filesystem roots remain +/// boundaries: they may be bind mounts or another view of the same data. +/// Other mounts and recognized snapshot mounts stay out. When mountinfo +/// cannot identify a view, keep the stricter boundary. +pub fn local_mount_boundaries( + mounts: &[Mount], + views: &[MountView], + root: &Path, +) -> Vec { + let boundaries = mount_boundaries(mounts, root); + let views: Vec<_> = views + .iter() + .map(|view| { + let mut matching = mounts.iter().filter(|m| m.point == view.point); + let mount = matching.next(); + // If the two kernel tables disagree, do not open that mount. + let trusted = matching.next().is_none() + && mount.is_some_and(|mount| { + mount.fstype == view.fstype && mount.source == view.source + }); + disktree_scanner::mounts::MountView { + point: view.point.clone(), + fs_root: view.fs_root.clone(), + fstype: view.fstype.clone(), + source: view.source.clone(), + snapshot: !trusted || mount.is_some_and(is_snapshot), + } + }) + .collect(); + let strict: rustc_hash::FxHashSet<_> = boundaries.iter().cloned().collect(); + let retained = + disktree_scanner::mounts::local_boundaries(strict, &views, root); + boundaries + .into_iter() + .filter(|path| retained.contains(path)) + .collect() +} + +/// Local scan boundaries from this machine's mount namespace. +pub fn local_mount_boundaries_for(root: &Path) -> Option> { + #[cfg(not(any(target_os = "macos", windows)))] + { + let mounts = mount_table()?; + // Without the filesystem roots, a bind mount cannot be distinguished + // from a subvolume. Keep every mount boundary rather than guessing. + let Ok(table) = std::fs::read_to_string("/proc/self/mountinfo") else { + return Some(mount_boundaries(&mounts, root)); + }; + Some(local_mount_boundaries( + &mounts, + &parse_mountinfo(&table), + root, + )) + } + #[cfg(any(target_os = "macos", windows))] + { + mount_boundaries_for(root) + } +} + /// Boundaries from this machine's own mount namespace. pub fn mount_boundaries_for(root: &Path) -> Option> { #[cfg(not(any(target_os = "macos", windows)))] @@ -1139,6 +1134,62 @@ portal /run/user/1000/doc fuse.portal rw 0 0 ); } + #[test] + fn local_btrfs_scan_keeps_distinct_subvolumes_but_not_aliases_or_network() { + let mounts = parse_mounts( + "/dev/root / btrfs rw,subvol=/@ 0 0\n\ + /dev/root /home-copy btrfs rw,subvol=/@home 0 0\n\ + /dev/root /home btrfs rw,subvol=/@home 0 0\n\ + /dev/root /bind btrfs rw,subvol=/@ 0 0\n\ + /dev/root /.snapshots btrfs rw,subvol=/@snapshots 0 0\n\ + /dev/other /external btrfs rw,subvol=/@data 0 0\n\ + server:/share /nas nfs rw 0 0\n\ + user@host:/ /ssh fuse.sshfs rw 0 0\n", + ); + let views = parse_mountinfo( + "1 0 0:1 /@ / rw - btrfs /dev/root rw\n\ + 2 1 0:1 /@home /home rw - btrfs /dev/root rw\n\ + 3 1 0:1 /@home /home-copy rw - btrfs /dev/root rw\n\ + 4 1 0:1 /@/data /bind rw - btrfs /dev/root rw\n\ + 5 1 0:1 /@snapshots /.snapshots rw - btrfs /dev/root rw\n\ + 6 1 0:2 /@data /external rw - btrfs /dev/other rw\n\ + 7 1 0:3 / /nas rw - nfs server:/share rw\n\ + 8 1 0:4 / /ssh rw - fuse.sshfs user@host:/ rw\n", + ); + let boundaries = + local_mount_boundaries(&mounts, &views, Path::new("/")); + assert!(!boundaries.contains(&PathBuf::from("/home"))); + for path in [ + "/home-copy", + "/bind", + "/.snapshots", + "/external", + "/nas", + "/ssh", + ] { + assert!(boundaries.contains(&PathBuf::from(path)), "{path}"); + } + } + + #[test] + fn local_scan_is_strict_without_mountinfo_or_for_other_filesystems() { + let mounts = parse_mounts( + "/dev/root / ext4 rw 0 0\n\ + /dev/root /bind ext4 rw 0 0\n\ + nas /network nfs rw 0 0\n", + ); + let views = parse_mountinfo("1 0 0:1 / / rw - ext4 /dev/root rw\n"); + let expected = mount_boundaries(&mounts, Path::new("/")); + assert_eq!( + local_mount_boundaries(&mounts, &views, Path::new("/")), + expected + ); + assert_eq!( + local_mount_boundaries(&mounts, &[], Path::new("/")), + expected + ); + } + #[test] fn strict_scan_boundaries_include_same_device_and_bind_mounts() { let mounts = parse_mounts( diff --git a/crates/disktree-scan/Cargo.toml b/crates/disktree-scan/Cargo.toml index 2f6e000..1a61756 100644 --- a/crates/disktree-scan/Cargo.toml +++ b/crates/disktree-scan/Cargo.toml @@ -10,7 +10,7 @@ description = "Read-only headless scanner for disktree SSH sessions" workspace = true [dependencies] -disktree-core.workspace = true +disktree-core = { path = "../disktree-core", default-features = false } [target.'cfg(target_os = "linux")'.dependencies] rustix = { version = "1.1", features = ["process"] } diff --git a/crates/disktree-scanner/Cargo.toml b/crates/disktree-scanner/Cargo.toml new file mode 100644 index 0000000..5d7fafe --- /dev/null +++ b/crates/disktree-scanner/Cargo.toml @@ -0,0 +1,38 @@ +[package] +name = "disktree-scanner" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "High-efficiency disk space scanner with Protobuf cache DB, prefix-trie string compression, and priority-interruptible SWR" + +[lints] +workspace = true + +[features] +default = ["cache-db"] +cache-db = ["dep:redb"] + +[dependencies] +lz4_flex = { version = "0.11", default-features = false, features = ["safe-encode", "safe-decode"] } +prost = "0.13" +rayon = { workspace = true } +redb = { version = "2", optional = true } +rustc-hash = { workspace = true } +serde = { version = "1", features = ["derive"] } + +[target.'cfg(not(windows))'.dependencies] +rustix = { version = "1.1", features = ["fs"] } + +[target.'cfg(windows)'.dependencies] +winapi-util = "0.1.11" +windows-sys = { version = "0.61", features = [ + "Win32_Foundation", + "Win32_Storage_FileSystem", + "Win32_System_Com", + "Win32_UI_Shell", + "Win32_UI_WindowsAndMessaging", +] } + +[dev-dependencies] +tempfile = "3" diff --git a/crates/disktree-scanner/proto/disktree_cache.proto b/crates/disktree-scanner/proto/disktree_cache.proto new file mode 100644 index 0000000..eeb7a7c --- /dev/null +++ b/crates/disktree-scanner/proto/disktree_cache.proto @@ -0,0 +1,75 @@ +// Canonical Protobuf schema reference for disktree-scanner's cache DB and +// wire frames. Hand-mirrored in `src/proto.rs` via `#[derive(prost::Message)]` +// so builds never require `protoc` or `build.rs` codegen. + +syntax = "proto3"; +package disktree.scanner.v1; + +message DbHeader { + uint32 format_version = 1; + uint64 created_at_unix = 2; + uint32 codec = 3; // 0 = raw, 1 = lz4 +} + +message HostRecord { + string host_key = 1; + string hostname = 2; + string machine_id = 3; + string platform = 4; + uint32 path_style = 5; // 0 = Posix, 1 = Windows + uint64 updated_at_unix = 6; +} + +// Lightweight whole-FS directory catalog entry for O(1) skip checks, +// partial-scan grafting, and instant stale summaries. +message DirIndexEntry { + uint64 dir_id = 1; + uint64 parent_id = 2; // 0 for filesystem root + string name = 3; // single path component + uint64 scanned_at_unix = 4; // 0 if unscanned stub or invalidated + uint32 coverage = 5; // 0=Stub, 1=Complete, 2=Shallow, 3=MountBoundary, 4=ReadError + uint32 scanned_max_depth = 6; // 0 = unlimited + uint32 options_mask = 7; // follow_links, one_filesystem, etc. + uint64 mount_dev = 8; + int64 dir_mtime = 9; + uint64 chunk_id = 10; // 0 if stub or packed inside an ancestor chunk + // Derived rollups for instant summary queries: + uint64 allocated_bytes = 11; + uint64 apparent_bytes = 12; + uint64 files = 13; + uint32 dirs = 14; + int64 newest_mtime = 15; +} + +// Prefix-trie linearized (front-coded) string table. +// Entries are sorted lexicographically and stored as repeated: +// (shared_prefix_len: varint, suffix_len: varint, suffix_bytes) +message FrontCodedStrings { + uint32 count = 1; + bytes encoded = 2; +} + +// Columnar (SoA) subtree chunk in DFS preorder. +message SubtreeChunk { + uint64 chunk_id = 1; + uint64 root_dir_id = 2; + uint64 scanned_at_unix = 3; + int64 base_mtime = 4; + FrontCodedStrings strings = 5; + + repeated uint32 name_ids = 6 [packed = true]; + repeated uint32 child_counts = 7 [packed = true]; + repeated uint32 flags = 8 [packed = true]; + repeated uint64 allocated_bytes = 9 [packed = true]; + repeated sint64 apparent_deltas = 10 [packed = true]; + repeated sint64 mtime_deltas = 11 [packed = true]; + + // Sparse multi-link files only (nlink > 1). + repeated uint32 hardlink_node_idx = 12 [packed = true]; + repeated uint64 hardlink_devs = 13 [packed = true]; + repeated uint64 hardlink_inos = 14 [packed = true]; + + // External child shard references matching preorder nodes whose + // external_shard_ref flag bit is set. + repeated uint64 external_dir_ids = 15 [packed = true]; +} diff --git a/crates/disktree-scanner/src/db.rs b/crates/disktree-scanner/src/db.rs new file mode 100644 index 0000000..747c85c --- /dev/null +++ b/crates/disktree-scanner/src/db.rs @@ -0,0 +1,1881 @@ +//! Persistent Protobuf cache database backed by `redb`. +//! +//! Models each host's full canonical filesystem tree rooted at `/` (or Windows +//! volume roots). Partial scans of any subdirectory graft into the host tree +//! as adaptive Protobuf `SubtreeChunk`s, enabling: +//! +//! - O(1) skip checks for fresh subtrees during wider scans, +//! - sub-millisecond narrowing queries into already-scanned descendants, +//! - targeted subtree invalidation (preserving untouched fresh siblings), +//! - automatic graceful fallback on `ENOSPC`, `EROFS`, `EACCES`, low free +//! space, or corrupt DB files. + +use std::io; +use std::path::{Component, Path, PathBuf}; + +#[cfg(feature = "cache-db")] +use redb::{ + Database, ReadableTable as _, ReadableTableMetadata as _, TableDefinition, +}; +use rustc_hash::{FxHashMap, FxHashSet}; + +#[cfg(feature = "cache-db")] +use crate::mounts::check_cache_headroom; +#[cfg(feature = "cache-db")] +use crate::proto::{ + CODEC_LZ4, Coverage, DbHeader, DirIndexEntry, FORMAT_VERSION, HostRecord, + SubtreeChunk, decode_framed, decode_subtree_chunk, encode_framed, + encode_subtree_chunk, +}; +#[cfg(feature = "cache-db")] +use crate::tree::NodeId; +use crate::tree::TreeArena; +use crate::types::{ + CachePolicy, CacheStats, FallbackReason, Freshness, HostKey, ScanOptions, +}; +#[cfg(feature = "cache-db")] +use crate::types::{SubtreeStatus, unix_now}; + +/// Directories with at least this many nodes become independent shards so +/// partial updates never rewrite unrelated subtrees. +#[cfg(feature = "cache-db")] +const SHARD_NODE_THRESHOLD: u32 = 2_048; + +/// Shallow directories (depth <= 2 from scan root) with at least this many +/// nodes also become shards so top-level folders (e.g. `~/Downloads`, `~/src`) +/// can be skipped or invalidated independently. +#[cfg(feature = "cache-db")] +const SHALLOW_SHARD_DEPTH: usize = 2; +#[cfg(feature = "cache-db")] +const SHALLOW_SHARD_MIN_NODES: u32 = 64; + +#[cfg(feature = "cache-db")] +const META_TABLE: TableDefinition<'_, &str, &[u8]> = + TableDefinition::new("meta"); +#[cfg(feature = "cache-db")] +const HOSTS_TABLE: TableDefinition<'_, &str, &[u8]> = + TableDefinition::new("hosts"); +#[cfg(feature = "cache-db")] +const PATH_TO_DIR_TABLE: TableDefinition<'_, (&str, &str), u64> = + TableDefinition::new("path_to_dir"); +#[cfg(feature = "cache-db")] +const DIR_INDEX_TABLE: TableDefinition<'_, (&str, u64), &[u8]> = + TableDefinition::new("dir_index"); +#[cfg(feature = "cache-db")] +const DIR_CHILDREN_TABLE: TableDefinition<'_, (&str, u64, u64), ()> = + TableDefinition::new("dir_children"); +#[cfg(feature = "cache-db")] +const CHUNKS_TABLE: TableDefinition<'_, (&str, u64), &[u8]> = + TableDefinition::new("chunks"); + +/// Result of reading a cached subtree from [`CacheDb`]. +#[derive(Debug)] +pub struct CachedSubtree { + pub arena: TreeArena, + pub freshness: Freshness, +} + +/// Summary of an invalidation operation. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct InvalidateReport { + pub invalidated_dirs: u64, + pub touched_ancestors: u64, +} + +/// Persistent (or temporary-file) cache database handle. +#[derive(Debug)] +pub struct CacheDb { + #[cfg(feature = "cache-db")] + db: Database, + path: PathBuf, + temp_file: bool, + #[cfg(feature = "cache-db")] + min_free_headroom: u64, +} + +impl Drop for CacheDb { + fn drop(&mut self) { + if self.temp_file { + let _ = std::fs::remove_file(&self.path); + } + } +} + +impl CacheDb { + /// Open or create a persistent cache DB at `path`, checking free-space + /// headroom first. + #[cfg(feature = "cache-db")] + pub fn open( + path: PathBuf, + min_free_headroom: u64, + temp_file: bool, + ) -> Result { + check_cache_headroom(&path, min_free_headroom)?; + + if let Some(parent) = path.parent() + && !parent.as_os_str().is_empty() + && let Err(err) = std::fs::create_dir_all(parent) + { + return Err(classify_io_error(&err)); + } + + let db = match Database::create(&path) { + Ok(db) => db, + Err(err) => return Err(classify_redb_error(&err.into())), + }; + + let instance = Self { + db, + path, + temp_file, + min_free_headroom, + }; + instance.init_schema()?; + Ok(instance) + } + + #[cfg(not(feature = "cache-db"))] + pub fn open( + _path: PathBuf, + _min_free_headroom: u64, + _temp_file: bool, + ) -> Result { + Err(FallbackReason::DatabaseUnavailable { + detail: "compiled without cache-db feature".to_owned(), + }) + } + + /// Create an ephemeral cache DB in the OS temp directory (deleted on drop). + pub fn open_temp(min_free_headroom: u64) -> Result { + let pid = std::process::id(); + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()); + let path = std::env::temp_dir() + .join(format!("disktree-cache-{pid}-{nanos}.redb")); + Self::open(path, min_free_headroom, true) + } + + pub fn path(&self) -> &Path { + &self.path + } + + pub const fn is_temp(&self) -> bool { + self.temp_file + } + + #[cfg(feature = "cache-db")] + fn init_schema(&self) -> Result<(), FallbackReason> { + let txn = self + .db + .begin_write() + .map_err(|e| classify_redb_error(&e.into()))?; + { + let mut meta = txn + .open_table(META_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + let _ = txn + .open_table(HOSTS_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + let _ = txn + .open_table(PATH_TO_DIR_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + let _ = txn + .open_table(DIR_INDEX_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + let _ = txn + .open_table(DIR_CHILDREN_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + let _ = txn + .open_table(CHUNKS_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + + let existing = meta + .get("header") + .map_err(|e| classify_redb_error(&e.into()))? + .map(|v| v.value().to_vec()); + + if let Some(bytes) = existing { + let header: DbHeader = decode_framed(&bytes).map_err(|e| { + FallbackReason::DatabaseUnavailable { + detail: format!("corrupt cache header: {e}"), + } + })?; + if header.format_version != FORMAT_VERSION { + return Err(FallbackReason::DatabaseUnavailable { + detail: format!( + "incompatible cache format version {} (expected {})", + header.format_version, FORMAT_VERSION + ), + }); + } + } else { + let header = DbHeader { + format_version: FORMAT_VERSION, + created_at_unix: unix_now(), + codec: u32::from(CODEC_LZ4), + }; + let bytes = encode_framed(&header); + meta.insert("header", bytes.as_slice()) + .map_err(|e| classify_redb_error(&e.into()))?; + meta.insert("next_id", 1u64.to_le_bytes().as_slice()) + .map_err(|e| classify_redb_error(&e.into()))?; + } + } + txn.commit().map_err(|e| classify_redb_error(&e.into()))?; + Ok(()) + } + + /// Persist a scanned [`TreeArena`] into the host's whole-filesystem tree, + /// replacing any previous data strictly at or beneath `arena.root_path()`. + #[cfg(feature = "cache-db")] + pub fn store_subtree( + &self, + host: &HostKey, + arena: &TreeArena, + options: &ScanOptions, + scanned_at: u64, + ) -> Result<(), FallbackReason> { + check_cache_headroom(&self.path, self.min_free_headroom)?; + + let host_key = host.as_db_key(); + let canonical_root = normalize_path(arena.root_path()); + let counts = arena.subtree_counts(); + let shard_nodes = choose_shard_roots(arena, &counts); + + let txn = self + .db + .begin_write() + .map_err(|e| classify_redb_error(&e.into()))?; + { + let mut meta = txn + .open_table(META_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + let mut hosts = txn + .open_table(HOSTS_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + let mut path_to_dir = txn + .open_table(PATH_TO_DIR_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + let mut dir_index = txn + .open_table(DIR_INDEX_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + let mut dir_children = txn + .open_table(DIR_CHILDREN_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + let mut chunks = txn + .open_table(CHUNKS_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + + let mut next_id = read_next_id(&meta)?; + + // Upsert host record. + let host_record = make_host_record(host, &host_key, scanned_at); + let host_bytes = encode_framed(&host_record); + hosts + .insert(host_key.as_str(), host_bytes.as_slice()) + .map_err(|e| classify_redb_error(&e.into()))?; + + // Ensure ancestor chain exists from filesystem root down to + // `canonical_root`. + let root_dir_id = ensure_ancestor_chain( + &host_key, + &canonical_root, + &mut next_id, + &mut path_to_dir, + &mut dir_index, + &mut dir_children, + )?; + + // Remove old descendants and old chunk(s) under `root_dir_id` so + // deleted directories never linger as ghost shards. + purge_descendants( + &host_key, + root_dir_id, + &mut path_to_dir, + &mut dir_index, + &mut dir_children, + &mut chunks, + )?; + + // Allocate deterministic dir_ids and chunk_ids for every shard + // root in this arena. + let mut node_to_dir_id: FxHashMap = + FxHashMap::default(); + let mut node_to_chunk_id: FxHashMap = + FxHashMap::default(); + node_to_dir_id.insert(arena.root(), root_dir_id); + node_to_chunk_id.insert(arena.root(), alloc_id(&mut next_id)); + + for &shard_node in &shard_nodes { + if shard_node == arena.root() { + continue; + } + let shard_path = normalize_path(&arena.path_of(shard_node)); + let dir_id = if let Some(existing) = path_to_dir + .get((host_key.as_str(), shard_path.as_str())) + .map_err(|e| classify_redb_error(&e.into()))? + .map(|v| v.value()) + { + existing + } else { + alloc_id(&mut next_id) + }; + node_to_dir_id.insert(shard_node, dir_id); + node_to_chunk_id.insert(shard_node, alloc_id(&mut next_id)); + } + + // Determine parent dir_id for each shard root (linking through + // nearest ancestor shard root, creating intermediate stubs if + // needed so whole-FS navigation works cleanly). + let root_parent_id = dir_index + .get((host_key.as_str(), root_dir_id)) + .map_err(|e| classify_redb_error(&e.into()))? + .and_then(|v| decode_framed::(v.value()).ok()) + .map_or(0, |entry| entry.parent_id); + + let coverage = if options.max_depth.is_some() { + Coverage::Shallow as u32 + } else { + Coverage::Complete as u32 + }; + let max_depth_u32 = options + .max_depth + .map_or(0, |d| d.min(u32::MAX as usize) as u32); + + for &shard_node in &shard_nodes { + let dir_id = node_to_dir_id[&shard_node]; + let chunk_id = node_to_chunk_id[&shard_node]; + let shard_path = normalize_path(&arena.path_of(shard_node)); + + let parent_dir_id = if shard_node == arena.root() { + root_parent_id + } else { + let parent_path = parent_normalized_path(&shard_path); + match parent_path { + Some(p) => ensure_ancestor_chain( + &host_key, + &p, + &mut next_id, + &mut path_to_dir, + &mut dir_index, + &mut dir_children, + )?, + None => 0, + } + }; + + // Encode chunk stopping at nested shard roots. + let chunk = encode_subtree_chunk( + arena, + shard_node, + chunk_id, + dir_id, + scanned_at, + &node_to_dir_id, + ); + let chunk_bytes = encode_framed(&chunk); + chunks + .insert( + (host_key.as_str(), chunk_id), + chunk_bytes.as_slice(), + ) + .map_err(|e| classify_redb_error(&e.into()))?; + + let node = arena.node(shard_node); + let dir_ts = if node.scanned_at > 0 { + node.scanned_at + } else { + scanned_at + }; + let entry = DirIndexEntry { + dir_id, + parent_id: parent_dir_id, + name: leaf_name(&shard_path).to_owned(), + scanned_at_unix: dir_ts, + coverage, + scanned_max_depth: max_depth_u32, + options_mask: options.cache_topology_mask(), + mount_dev: 0, + dir_mtime: node.modified, + chunk_id, + allocated_bytes: node.allocated_bytes, + apparent_bytes: node.apparent_bytes, + files: node.files, + dirs: node.dirs, + newest_mtime: node.modified, + }; + let entry_bytes = encode_framed(&entry); + + path_to_dir + .insert((host_key.as_str(), shard_path.as_str()), dir_id) + .map_err(|e| classify_redb_error(&e.into()))?; + dir_index + .insert((host_key.as_str(), dir_id), entry_bytes.as_slice()) + .map_err(|e| classify_redb_error(&e.into()))?; + if parent_dir_id != 0 { + dir_children + .insert((host_key.as_str(), parent_dir_id, dir_id), ()) + .map_err(|e| classify_redb_error(&e.into()))?; + } + } + + meta.insert("next_id", next_id.to_le_bytes().as_slice()) + .map_err(|e| classify_redb_error(&e.into()))?; + } + + txn.commit().map_err(|e| classify_redb_error(&e.into()))?; + Ok(()) + } + + #[cfg(not(feature = "cache-db"))] + pub fn store_subtree( + &self, + _host: &HostKey, + _arena: &TreeArena, + _options: &ScanOptions, + _scanned_at: u64, + ) -> Result<(), FallbackReason> { + Err(FallbackReason::DatabaseUnavailable { + detail: "compiled without cache-db feature".to_owned(), + }) + } + + /// Load a cached subtree rooted at `root_path` (supporting direct hits, + /// narrowing into a cached ancestor shard, and partial ancestor hits). + #[cfg(feature = "cache-db")] + pub fn load_subtree( + &self, + host: &HostKey, + root_path: &Path, + options: &ScanOptions, + now: u64, + policy: &CachePolicy, + ) -> Result, FallbackReason> { + let host_key = host.as_db_key(); + let normalized = normalize_path(root_path); + let ttl_secs = policy.ttl.as_secs(); + let max_stale_secs = policy.max_stale.map(|d| d.as_secs()); + + let txn = self + .db + .begin_read() + .map_err(|e| classify_redb_error(&e.into()))?; + let path_to_dir = txn + .open_table(PATH_TO_DIR_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + let dir_index = txn + .open_table(DIR_INDEX_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + let dir_children = txn + .open_table(DIR_CHILDREN_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + let chunks = txn + .open_table(CHUNKS_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + + // 1. Direct lookup on `normalized`. + if let Some(dir_id) = path_to_dir + .get((host_key.as_str(), normalized.as_str())) + .map_err(|e| classify_redb_error(&e.into()))? + .map(|v| v.value()) + && let Some(entry) = read_dir_entry(&dir_index, &host_key, dir_id)? + { + if entry.chunk_id != 0 + && is_entry_compatible(&entry, options) + && !exceeds_max_stale( + entry.scanned_at_unix, + now, + max_stale_secs, + ) + { + let mut tracker = FreshnessTracker::default(); + let mut arena = load_shard_recursive( + &host_key, + &entry, + root_path.to_path_buf(), + now, + ttl_secs, + &dir_index, + &chunks, + &mut tracker, + )?; + arena + .aggregate(options.dedup_hardlinks, options.include_hidden); + arena.sort_children(options.byte_metric()); + arena.refresh_statuses(now, ttl_secs); + return Ok(Some(CachedSubtree { + arena, + freshness: tracker.finish(), + })); + } + + // Stub or invalidated directory that still has cached descendants + // (e.g. scanned `~/src` earlier, now querying `~`). + if entry.coverage == Coverage::Stub as u32 + || entry.scanned_at_unix == 0 + { + let mut partial = TreeArena::new( + root_path.to_path_buf(), + leaf_name(&normalized), + ); + partial + .node_mut(partial.root()) + .set_status(SubtreeStatus::Unscanned); + let mut cached_dirs = 0u32; + let mut oldest: Option = None; + let mut newest: Option = None; + let grafted = graft_cached_children( + &host_key, + dir_id, + partial.root(), + &mut partial, + options, + now, + ttl_secs, + max_stale_secs, + &dir_index, + &dir_children, + &chunks, + &mut cached_dirs, + &mut oldest, + &mut newest, + )?; + if grafted > 0 { + partial.aggregate( + options.dedup_hardlinks, + options.include_hidden, + ); + partial.sort_children(options.byte_metric()); + partial.refresh_statuses(now, ttl_secs); + return Ok(Some(CachedSubtree { + arena: partial, + freshness: Freshness::Partial { + cached_dirs, + missing_dirs: 1, + oldest_at: oldest, + newest_at: newest, + }, + })); + } + } + } + + // 2. Narrowing lookup: walk up ancestors to find a cached shard that + // contains `normalized` inside its chunk. + let mut cursor = normalized; + let mut rel_parts: Vec = Vec::new(); + while let Some(parent) = parent_normalized_path(&cursor) { + rel_parts.push(leaf_name(&cursor).to_owned()); + if let Some(anc_id) = path_to_dir + .get((host_key.as_str(), parent.as_str())) + .map_err(|e| classify_redb_error(&e.into()))? + .map(|v| v.value()) + && let Some(entry) = + read_dir_entry(&dir_index, &host_key, anc_id)? + && entry.chunk_id != 0 + && is_entry_compatible(&entry, options) + && !exceeds_max_stale( + entry.scanned_at_unix, + now, + max_stale_secs, + ) + { + let mut tracker = FreshnessTracker::default(); + let anc_arena = load_shard_recursive( + &host_key, + &entry, + PathBuf::from(&parent), + now, + ttl_secs, + &dir_index, + &chunks, + &mut tracker, + )?; + rel_parts.reverse(); + if let Some(target_node) = anc_arena + .find_relative(rel_parts.iter().map(String::as_str)) + { + let mut sub = anc_arena.extract_subtree(target_node); + sub.root_path = root_path.to_path_buf(); + sub.aggregate( + options.dedup_hardlinks, + options.include_hidden, + ); + sub.sort_children(options.byte_metric()); + sub.refresh_statuses(now, ttl_secs); + return Ok(Some(CachedSubtree { + arena: sub, + freshness: tracker.finish(), + })); + } + // Found the containing shard and the path wasn't in it. + return Ok(None); + } + cursor = parent; + } + + Ok(None) + } + + #[cfg(not(feature = "cache-db"))] + pub const fn load_subtree( + &self, + _host: &HostKey, + _root_path: &Path, + _options: &ScanOptions, + _now: u64, + _policy: &CachePolicy, + ) -> Result, FallbackReason> { + Ok(None) + } + + /// Preload the map of fresh cached shard paths strictly beneath `root_path` + /// so a live walk can skip them with a lock-free O(1) lookup. + #[cfg(feature = "cache-db")] + pub fn fresh_subtrees_below( + &self, + host: &HostKey, + root_path: &Path, + options: &ScanOptions, + now: u64, + ttl_secs: u64, + exclude: &FxHashSet, + ) -> Result, FallbackReason> { + let host_key = host.as_db_key(); + let normalized_root = normalize_path(root_path); + let prefix = if normalized_root == "/" { + "/".to_owned() + } else { + format!("{normalized_root}/") + }; + + let txn = self + .db + .begin_read() + .map_err(|e| classify_redb_error(&e.into()))?; + let path_to_dir = txn + .open_table(PATH_TO_DIR_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + let dir_index = txn + .open_table(DIR_INDEX_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + + let mut fresh = FxHashMap::default(); + let start = (host_key.as_str(), prefix.as_str()); + let iter = path_to_dir + .range(start..) + .map_err(|e| classify_redb_error(&e.into()))?; + + for item in iter { + let (key, val) = + item.map_err(|e| classify_redb_error(&e.into()))?; + let (entry_host, entry_path) = key.value(); + if entry_host != host_key || !entry_path.starts_with(&prefix) { + break; + } + let dir_id = val.value(); + let path_buf = PathBuf::from(entry_path); + if exclude + .iter() + .any(|ex| path_buf.starts_with(ex) || ex.starts_with(&path_buf)) + { + continue; + } + if let Some(entry) = read_dir_entry(&dir_index, &host_key, dir_id)? + && entry.chunk_id != 0 + && entry.scanned_at_unix > 0 + && now.saturating_sub(entry.scanned_at_unix) <= ttl_secs + && is_entry_compatible(&entry, options) + { + fresh.insert(path_buf, dir_id); + } + } + + Ok(fresh) + } + + #[cfg(not(feature = "cache-db"))] + pub fn fresh_subtrees_below( + &self, + _host: &HostKey, + _root_path: &Path, + _options: &ScanOptions, + _now: u64, + _ttl_secs: u64, + _exclude: &FxHashSet, + ) -> Result, FallbackReason> { + Ok(FxHashMap::default()) + } + + /// Load a single shard by `dir_id` (used when grafting a skipped fresh + /// subtree during a wider walk). + #[cfg(feature = "cache-db")] + pub fn load_shard_by_dir_id( + &self, + host: &HostKey, + dir_id: u64, + root_path: PathBuf, + now: u64, + ttl_secs: u64, + ) -> Result, FallbackReason> { + let host_key = host.as_db_key(); + let txn = self + .db + .begin_read() + .map_err(|e| classify_redb_error(&e.into()))?; + let dir_index = txn + .open_table(DIR_INDEX_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + let chunks = txn + .open_table(CHUNKS_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + + let Some(entry) = read_dir_entry(&dir_index, &host_key, dir_id)? else { + return Ok(None); + }; + if entry.chunk_id == 0 { + return Ok(None); + } + let mut tracker = FreshnessTracker::default(); + let arena = load_shard_recursive( + &host_key, + &entry, + root_path, + now, + ttl_secs, + &dir_index, + &chunks, + &mut tracker, + )?; + Ok(Some(arena)) + } + + #[cfg(not(feature = "cache-db"))] + pub fn load_shard_by_dir_id( + &self, + _host: &HostKey, + _dir_id: u64, + _root_path: PathBuf, + _now: u64, + _ttl_secs: u64, + ) -> Result, FallbackReason> { + Ok(None) + } + + /// Mark one or more paths dirty in the cache (e.g. after files were + /// deleted), invalidating the target subtrees and their ancestor rollups + /// while preserving untouched fresh sibling shards. + #[cfg(feature = "cache-db")] + pub fn invalidate( + &self, + host: &HostKey, + paths: &[PathBuf], + ) -> Result { + check_cache_headroom(&self.path, self.min_free_headroom)?; + + let host_key = host.as_db_key(); + let mut report = InvalidateReport::default(); + + let txn = self + .db + .begin_write() + .map_err(|e| classify_redb_error(&e.into()))?; + { + let mut path_to_dir = txn + .open_table(PATH_TO_DIR_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + let mut dir_index = txn + .open_table(DIR_INDEX_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + let mut dir_children = txn + .open_table(DIR_CHILDREN_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + let mut chunks = txn + .open_table(CHUNKS_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + + for raw_path in paths { + let normalized = normalize_potentially_deleted_path(raw_path); + + // Find either the exact directory or its nearest indexed + // containing shard. + let mut target_dir_id = path_to_dir + .get((host_key.as_str(), normalized.as_str())) + .map_err(|e| classify_redb_error(&e.into()))? + .map(|v| v.value()); + + if target_dir_id.is_none() { + let mut cursor = normalized.clone(); + while let Some(parent) = parent_normalized_path(&cursor) { + if let Some(id) = path_to_dir + .get((host_key.as_str(), parent.as_str())) + .map_err(|e| classify_redb_error(&e.into()))? + .map(|v| v.value()) + { + target_dir_id = Some(id); + break; + } + cursor = parent; + } + } + + let Some(dir_id) = target_dir_id else { + continue; + }; + + // Purge cached descendants strictly beneath `dir_id` if `dir_id` + // matches `normalized` exactly (if we fell back to a parent + // shard, we only dirty that parent shard without wiping + // unrelated indexed child shards). + let exact_match = path_to_dir + .get((host_key.as_str(), normalized.as_str())) + .map_err(|e| classify_redb_error(&e.into()))? + .is_some(); + + if exact_match { + let removed = purge_descendants( + &host_key, + dir_id, + &mut path_to_dir, + &mut dir_index, + &mut dir_children, + &mut chunks, + )?; + report.invalidated_dirs += removed; + } + + // Mark the target entry itself dirty (timestamp = 0). + if let Some(mut entry) = + read_dir_entry(&dir_index, &host_key, dir_id)? + { + if entry.chunk_id != 0 { + let _ = chunks + .remove((host_key.as_str(), entry.chunk_id)) + .map_err(|e| classify_redb_error(&e.into()))?; + entry.chunk_id = 0; + } + entry.scanned_at_unix = 0; + entry.coverage = Coverage::Stub as u32; + let parent_id = entry.parent_id; + let bytes = encode_framed(&entry); + dir_index + .insert((host_key.as_str(), dir_id), bytes.as_slice()) + .map_err(|e| classify_redb_error(&e.into()))?; + report.invalidated_dirs += 1; + + // Mark ancestors stale so a wider scan doesn't skip the + // parent while keeping untouched sibling shards fresh. + let mut anc_id = parent_id; + while anc_id != 0 { + let Some(mut anc) = + read_dir_entry(&dir_index, &host_key, anc_id)? + else { + break; + }; + let next_parent = anc.parent_id; + if anc.scanned_at_unix != 0 { + anc.scanned_at_unix = 0; + let bytes = encode_framed(&anc); + dir_index + .insert( + (host_key.as_str(), anc_id), + bytes.as_slice(), + ) + .map_err(|e| classify_redb_error(&e.into()))?; + report.touched_ancestors += 1; + } + anc_id = next_parent; + } + } + } + } + txn.commit().map_err(|e| classify_redb_error(&e.into()))?; + Ok(report) + } + + #[cfg(not(feature = "cache-db"))] + pub fn invalidate( + &self, + _host: &HostKey, + _paths: &[PathBuf], + ) -> Result { + Ok(InvalidateReport::default()) + } + + /// Return cache statistics (file size, indexed dirs, chunk count). + #[cfg(feature = "cache-db")] + pub fn stats(&self) -> Result { + let db_bytes = std::fs::metadata(&self.path).map_or(0, |m| m.len()); + let txn = self + .db + .begin_read() + .map_err(|e| classify_redb_error(&e.into()))?; + let hosts = txn + .open_table(HOSTS_TABLE) + .map_err(|e| classify_redb_error(&e.into()))? + .len() + .map_err(|e| classify_redb_error(&e.into()))?; + let indexed_dirs = txn + .open_table(DIR_INDEX_TABLE) + .map_err(|e| classify_redb_error(&e.into()))? + .len() + .map_err(|e| classify_redb_error(&e.into()))?; + let chunks = txn + .open_table(CHUNKS_TABLE) + .map_err(|e| classify_redb_error(&e.into()))? + .len() + .map_err(|e| classify_redb_error(&e.into()))?; + Ok(CacheStats { + db_path: Some(self.path.clone()), + db_bytes, + hosts, + indexed_dirs, + chunks, + }) + } + + #[cfg(not(feature = "cache-db"))] + pub fn stats(&self) -> Result { + Ok(CacheStats::default()) + } + + /// Delete every cached host, directory index entry, and chunk. + #[cfg(feature = "cache-db")] + pub fn clear(&self) -> Result<(), FallbackReason> { + let txn = self + .db + .begin_write() + .map_err(|e| classify_redb_error(&e.into()))?; + { + for table_fn in [ + clear_str_bytes_table(&txn, HOSTS_TABLE), + clear_path_table(&txn), + clear_dir_index_table(&txn), + clear_dir_children_table(&txn), + clear_chunks_table(&txn), + ] { + table_fn?; + } + } + txn.commit().map_err(|e| classify_redb_error(&e.into()))?; + Ok(()) + } + + #[cfg(not(feature = "cache-db"))] + pub const fn clear(&self) -> Result<(), FallbackReason> { + Ok(()) + } + + /// Prune cached chunks older than `max_age` seconds. + #[cfg(feature = "cache-db")] + pub fn prune_older_than( + &self, + now: u64, + max_age_secs: u64, + ) -> Result { + let mut pruned = 0u64; + let txn = self + .db + .begin_write() + .map_err(|e| classify_redb_error(&e.into()))?; + { + let mut dir_index = txn + .open_table(DIR_INDEX_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + let mut chunks = txn + .open_table(CHUNKS_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + + let mut expired: Vec<(String, u64, DirIndexEntry)> = Vec::new(); + { + let iter = dir_index + .iter() + .map_err(|e| classify_redb_error(&e.into()))?; + for item in iter { + let (key, val) = + item.map_err(|e| classify_redb_error(&e.into()))?; + let (host, dir_id) = key.value(); + let Ok(entry) = decode_framed::(val.value()) + else { + continue; + }; + if entry.chunk_id != 0 + && now.saturating_sub(entry.scanned_at_unix) + > max_age_secs + { + expired.push((host.to_owned(), dir_id, entry)); + } + } + } + + for (host, dir_id, mut entry) in expired { + let _ = chunks + .remove((host.as_str(), entry.chunk_id)) + .map_err(|e| classify_redb_error(&e.into()))?; + entry.chunk_id = 0; + entry.scanned_at_unix = 0; + entry.coverage = Coverage::Stub as u32; + let bytes = encode_framed(&entry); + dir_index + .insert((host.as_str(), dir_id), bytes.as_slice()) + .map_err(|e| classify_redb_error(&e.into()))?; + pruned += 1; + } + } + txn.commit().map_err(|e| classify_redb_error(&e.into()))?; + Ok(pruned) + } + + #[cfg(not(feature = "cache-db"))] + pub const fn prune_older_than( + &self, + _now: u64, + _max_age_secs: u64, + ) -> Result { + Ok(0) + } +} + +/// Choose which directories in `arena` become independent shards. +#[cfg(feature = "cache-db")] +fn choose_shard_roots(arena: &TreeArena, counts: &[u32]) -> Vec { + let mut shards = vec![arena.root()]; + let mut stack: Vec<(NodeId, usize)> = + arena.children(arena.root()).map(|kid| (kid, 1)).collect(); + + while let Some((node_id, depth)) = stack.pop() { + let node = arena.node(node_id); + if !node.is_dir() { + continue; + } + let count = counts[node_id.index()]; + let is_shallow_shard = + depth <= SHALLOW_SHARD_DEPTH && count >= SHALLOW_SHARD_MIN_NODES; + let is_large_shard = count >= SHARD_NODE_THRESHOLD; + if is_shallow_shard || is_large_shard { + shards.push(node_id); + } + for child in arena.children(node_id) { + if arena.node(child).is_dir() { + stack.push((child, depth + 1)); + } + } + } + + shards +} + +#[cfg(feature = "cache-db")] +#[derive(Default)] +struct FreshnessTracker { + oldest: Option, + newest: Option, + stale_dirs: u32, +} + +#[cfg(feature = "cache-db")] +impl FreshnessTracker { + fn observe(&mut self, scanned_at: u64, now: u64, ttl_secs: u64) { + self.oldest = Some(match self.oldest { + Some(old) => old.min(scanned_at), + None => scanned_at, + }); + self.newest = Some(match self.newest { + Some(new) => new.max(scanned_at), + None => scanned_at, + }); + if scanned_at == 0 || now.saturating_sub(scanned_at) > ttl_secs { + self.stale_dirs = self.stale_dirs.saturating_add(1); + } + } + + fn finish(self) -> Freshness { + let oldest_at = self.oldest.unwrap_or(0); + let newest_at = self.newest.unwrap_or(0); + if self.stale_dirs == 0 && oldest_at > 0 { + Freshness::Fresh { + oldest_at, + newest_at, + } + } else { + Freshness::Stale { + oldest_at, + newest_at, + stale_dirs: self.stale_dirs.max(1), + } + } + } +} + +#[cfg(feature = "cache-db")] +#[allow(clippy::too_many_arguments, reason = "recursive DB loader state")] +fn load_shard_recursive( + host_key: &str, + entry: &DirIndexEntry, + root_path: PathBuf, + now: u64, + ttl_secs: u64, + dir_index: &redb::ReadOnlyTable<(&str, u64), &[u8]>, + chunks: &redb::ReadOnlyTable<(&str, u64), &[u8]>, + tracker: &mut FreshnessTracker, +) -> Result { + let raw = chunks + .get((host_key, entry.chunk_id)) + .map_err(|e| classify_redb_error(&e.into()))? + .ok_or_else(|| FallbackReason::DatabaseUnavailable { + detail: format!("missing chunk {}", entry.chunk_id), + })?; + let proto_chunk: SubtreeChunk = + decode_framed(raw.value()).map_err(|e| { + FallbackReason::DatabaseUnavailable { + detail: format!("corrupt chunk {}: {e}", entry.chunk_id), + } + })?; + let mut decoded = + decode_subtree_chunk(&proto_chunk, root_path).map_err(|e| { + FallbackReason::DatabaseUnavailable { + detail: format!("invalid chunk {}: {e}", entry.chunk_id), + } + })?; + + tracker.observe(entry.scanned_at_unix, now, ttl_secs); + decoded.arena.node_mut(decoded.arena.root()).scanned_at = + entry.scanned_at_unix; + + for (stub_node_id, ext_dir_id) in decoded.external_links { + let Some(child_entry) = + read_dir_entry(dir_index, host_key, ext_dir_id)? + else { + continue; + }; + if child_entry.chunk_id == 0 { + decoded + .arena + .node_mut(stub_node_id) + .set_status(SubtreeStatus::Unscanned); + tracker.observe(0, now, ttl_secs); + continue; + } + let child_path = decoded.arena.path_of(stub_node_id); + let child_arena = load_shard_recursive( + host_key, + &child_entry, + child_path, + now, + ttl_secs, + dir_index, + chunks, + tracker, + )?; + decoded + .arena + .replace_node_contents(stub_node_id, &child_arena); + } + + Ok(decoded.arena) +} + +#[cfg(feature = "cache-db")] +#[allow(clippy::too_many_arguments, reason = "recursive partial graft state")] +fn graft_cached_children( + host_key: &str, + parent_dir_id: u64, + parent_node: NodeId, + target: &mut TreeArena, + options: &ScanOptions, + now: u64, + ttl_secs: u64, + max_stale_secs: Option, + dir_index: &redb::ReadOnlyTable<(&str, u64), &[u8]>, + dir_children: &redb::ReadOnlyTable<(&str, u64, u64), ()>, + chunks: &redb::ReadOnlyTable<(&str, u64), &[u8]>, + cached_dirs: &mut u32, + oldest: &mut Option, + newest: &mut Option, +) -> Result { + let mut grafted = 0u32; + let range_start = (host_key, parent_dir_id, 0u64); + let range_end = (host_key, parent_dir_id, u64::MAX); + let iter = dir_children + .range(range_start..=range_end) + .map_err(|e| classify_redb_error(&e.into()))?; + + let mut child_ids = Vec::new(); + for item in iter { + let (key, _) = item.map_err(|e| classify_redb_error(&e.into()))?; + let (h, p, cid) = key.value(); + if h == host_key && p == parent_dir_id { + child_ids.push(cid); + } + } + + for child_id in child_ids { + let Some(entry) = read_dir_entry(dir_index, host_key, child_id)? else { + continue; + }; + if entry.chunk_id != 0 + && is_entry_compatible(&entry, options) + && !exceeds_max_stale(entry.scanned_at_unix, now, max_stale_secs) + { + let mut tracker = FreshnessTracker::default(); + let child_path = target.path_of(parent_node).join(&entry.name); + let child_arena = load_shard_recursive( + host_key, + &entry, + child_path, + now, + ttl_secs, + dir_index, + chunks, + &mut tracker, + )?; + target.graft_subtree(parent_node, &child_arena, Some(&entry.name)); + grafted += 1; + *cached_dirs = cached_dirs.saturating_add(1); + if let Some(o) = tracker.oldest { + *oldest = Some(oldest.map_or(o, |cur| cur.min(o))); + } + if let Some(n) = tracker.newest { + *newest = Some(newest.map_or(n, |cur| cur.max(n))); + } + } else { + // Recurse through intermediate stub directories. + let stub_id = target.add_child( + parent_node, + &entry.name, + crate::types::NodeKind::Directory, + 0, + 0, + 0, + crate::tree::NodeFlags::new(crate::types::NodeKind::Directory), + ); + target + .node_mut(stub_id) + .set_status(SubtreeStatus::Unscanned); + let sub = graft_cached_children( + host_key, + child_id, + stub_id, + target, + options, + now, + ttl_secs, + max_stale_secs, + dir_index, + dir_children, + chunks, + cached_dirs, + oldest, + newest, + )?; + grafted += sub; + } + } + + Ok(grafted) +} + +#[cfg(feature = "cache-db")] +fn read_dir_entry( + table: &T, + host_key: &str, + dir_id: u64, +) -> Result, FallbackReason> +where + T: redb::ReadableTable<(&'static str, u64), &'static [u8]>, +{ + let Some(bytes) = table + .get((host_key, dir_id)) + .map_err(|e| classify_redb_error(&e.into()))? + else { + return Ok(None); + }; + let entry: DirIndexEntry = decode_framed(bytes.value()).map_err(|e| { + FallbackReason::DatabaseUnavailable { + detail: format!("corrupt dir_index entry {dir_id}: {e}"), + } + })?; + Ok(Some(entry)) +} + +#[cfg(feature = "cache-db")] +fn ensure_ancestor_chain( + host_key: &str, + normalized_path: &str, + next_id: &mut u64, + path_to_dir: &mut redb::Table<'_, (&str, &str), u64>, + dir_index: &mut redb::Table<'_, (&str, u64), &[u8]>, + dir_children: &mut redb::Table<'_, (&str, u64, u64), ()>, +) -> Result { + let ancestors = ancestor_paths(normalized_path); + let mut parent_id = 0u64; + + for anc in ancestors { + let dir_id = if let Some(existing) = path_to_dir + .get((host_key, anc.as_str())) + .map_err(|e| classify_redb_error(&e.into()))? + .map(|v| v.value()) + { + existing + } else { + let id = alloc_id(next_id); + let stub = DirIndexEntry { + dir_id: id, + parent_id, + name: leaf_name(&anc).to_owned(), + scanned_at_unix: 0, + coverage: Coverage::Stub as u32, + scanned_max_depth: 0, + options_mask: 0, + mount_dev: 0, + dir_mtime: 0, + chunk_id: 0, + allocated_bytes: 0, + apparent_bytes: 0, + files: 0, + dirs: 0, + newest_mtime: 0, + }; + let bytes = encode_framed(&stub); + path_to_dir + .insert((host_key, anc.as_str()), id) + .map_err(|e| classify_redb_error(&e.into()))?; + dir_index + .insert((host_key, id), bytes.as_slice()) + .map_err(|e| classify_redb_error(&e.into()))?; + if parent_id != 0 { + dir_children + .insert((host_key, parent_id, id), ()) + .map_err(|e| classify_redb_error(&e.into()))?; + } + id + }; + parent_id = dir_id; + } + + Ok(parent_id) +} + +#[cfg(feature = "cache-db")] +fn purge_descendants( + host_key: &str, + root_dir_id: u64, + path_to_dir: &mut redb::Table<'_, (&str, &str), u64>, + dir_index: &mut redb::Table<'_, (&str, u64), &[u8]>, + dir_children: &mut redb::Table<'_, (&str, u64, u64), ()>, + chunks: &mut redb::Table<'_, (&str, u64), &[u8]>, +) -> Result { + // Also drop old chunk on `root_dir_id` itself before replacing it. + if let Some(root_entry) = read_dir_entry(dir_index, host_key, root_dir_id)? + && root_entry.chunk_id != 0 + { + let _ = chunks + .remove((host_key, root_entry.chunk_id)) + .map_err(|e| classify_redb_error(&e.into()))?; + } + + let mut stack = vec![root_dir_id]; + let mut edges_to_remove = Vec::new(); + let mut dirs_to_remove = Vec::new(); + + while let Some(parent) = stack.pop() { + let range_start = (host_key, parent, 0u64); + let range_end = (host_key, parent, u64::MAX); + let mut kids = Vec::new(); + { + let iter = dir_children + .range(range_start..=range_end) + .map_err(|e| classify_redb_error(&e.into()))?; + for item in iter { + let (key, _) = + item.map_err(|e| classify_redb_error(&e.into()))?; + let (h, p, cid) = key.value(); + if h == host_key && p == parent { + kids.push(cid); + } + } + } + for cid in kids { + edges_to_remove.push((parent, cid)); + dirs_to_remove.push(cid); + stack.push(cid); + } + } + + for (p, cid) in edges_to_remove { + let _ = dir_children + .remove((host_key, p, cid)) + .map_err(|e| classify_redb_error(&e.into()))?; + } + + let remove_set: FxHashSet = dirs_to_remove.iter().copied().collect(); + let mut removed_count = 0u64; + for cid in dirs_to_remove { + if let Some(entry) = read_dir_entry(dir_index, host_key, cid)? + && entry.chunk_id != 0 + { + let _ = chunks + .remove((host_key, entry.chunk_id)) + .map_err(|e| classify_redb_error(&e.into()))?; + } + let _ = dir_index + .remove((host_key, cid)) + .map_err(|e| classify_redb_error(&e.into()))?; + removed_count += 1; + } + + // Clean stale `path_to_dir` entries pointing to removed dir_ids. + if !remove_set.is_empty() { + let mut stale_paths = Vec::new(); + { + let iter = path_to_dir + .range((host_key, "")..) + .map_err(|e| classify_redb_error(&e.into()))?; + for item in iter { + let (key, val) = + item.map_err(|e| classify_redb_error(&e.into()))?; + let (h, p) = key.value(); + if h != host_key { + break; + } + if remove_set.contains(&val.value()) { + stale_paths.push(p.to_owned()); + } + } + } + for p in stale_paths { + let _ = path_to_dir + .remove((host_key, p.as_str())) + .map_err(|e| classify_redb_error(&e.into()))?; + } + } + + Ok(removed_count) +} + +#[cfg(feature = "cache-db")] +fn read_next_id( + meta: &redb::Table<'_, &str, &[u8]>, +) -> Result { + let val = meta + .get("next_id") + .map_err(|e| classify_redb_error(&e.into()))?; + match val { + Some(bytes) if bytes.value().len() == 8 => { + let mut arr = [0u8; 8]; + arr.copy_from_slice(bytes.value()); + Ok(u64::from_le_bytes(arr)) + } + _ => Ok(1), + } +} + +#[cfg(feature = "cache-db")] +const fn alloc_id(next_id: &mut u64) -> u64 { + let id = *next_id; + *next_id = next_id.saturating_add(1); + id +} + +#[cfg(feature = "cache-db")] +const fn is_entry_compatible( + entry: &DirIndexEntry, + options: &ScanOptions, +) -> bool { + if entry.options_mask != options.cache_topology_mask() { + return false; + } + match Coverage::from_u32(entry.coverage) { + Coverage::Complete => true, + Coverage::Shallow => match options.max_depth { + Some(req) => (entry.scanned_max_depth as usize) >= req, + None => false, + }, + _ => false, + } +} + +#[cfg(feature = "cache-db")] +const fn exceeds_max_stale( + scanned_at: u64, + now: u64, + max_stale_secs: Option, +) -> bool { + match max_stale_secs { + Some(limit) => { + scanned_at == 0 || now.saturating_sub(scanned_at) > limit + } + None => false, + } +} + +#[cfg(feature = "cache-db")] +fn make_host_record( + host: &HostKey, + host_key: &str, + updated_at_unix: u64, +) -> HostRecord { + match host { + HostKey::Local => HostRecord { + host_key: host_key.to_owned(), + hostname: crate::types::HostIdentity::current() + .map_or_else(|| "local".to_owned(), |id| id.hostname), + machine_id: crate::types::HostIdentity::current() + .and_then(|id| id.machine_id) + .unwrap_or_default(), + platform: std::env::consts::OS.to_owned(), + path_style: u32::from(cfg!(windows)), + updated_at_unix, + }, + HostKey::Remote(identity) => HostRecord { + host_key: host_key.to_owned(), + hostname: identity.hostname.clone(), + machine_id: identity.machine_id.clone().unwrap_or_default(), + platform: "unix".to_owned(), + path_style: 0, + updated_at_unix, + }, + } +} + +/// Normalize an existing or canonical path into a clean string key. +pub fn normalize_path(path: &Path) -> String { + let resolved = path.canonicalize().unwrap_or_else(|_| path.to_path_buf()); + normalize_path_lexical(&resolved) +} + +/// Normalize a path that may already have been deleted by canonicalizing its +/// nearest existing ancestor and re-appending the remaining components. +pub fn normalize_potentially_deleted_path(path: &Path) -> String { + if let Ok(canon) = path.canonicalize() { + return normalize_path_lexical(&canon); + } + let mut existing = path.to_path_buf(); + let mut tail = Vec::new(); + while !existing.exists() { + let Some(name) = existing.file_name() else { + break; + }; + tail.push(name.to_os_string()); + if !existing.pop() { + break; + } + } + let mut base = existing.canonicalize().unwrap_or(existing); + for part in tail.into_iter().rev() { + base.push(part); + } + normalize_path_lexical(&base) +} + +fn normalize_path_lexical(path: &Path) -> String { + let mut out = PathBuf::new(); + for comp in path.components() { + match comp { + Component::CurDir => {} + Component::ParentDir => { + out.pop(); + } + other => out.push(other.as_os_str()), + } + } + let text = out.to_string_lossy(); + if text.len() > 1 && text.ends_with('/') { + text.trim_end_matches('/').to_owned() + } else if text.is_empty() { + "/".to_owned() + } else { + text.into_owned() + } +} + +#[cfg(feature = "cache-db")] +fn parent_normalized_path(path: &str) -> Option { + if path == "/" || path.is_empty() { + return None; + } + let trimmed = path.trim_end_matches('/'); + match trimmed.rfind('/') { + Some(0) => Some("/".to_owned()), + Some(idx) => Some(trimmed[..idx].to_owned()), + None => None, + } +} + +#[cfg(feature = "cache-db")] +fn ancestor_paths(path: &str) -> Vec { + let mut chain = vec![path.to_owned()]; + let mut cur = path.to_owned(); + while let Some(parent) = parent_normalized_path(&cur) { + chain.push(parent.clone()); + cur = parent; + } + chain.reverse(); + chain +} + +#[cfg(feature = "cache-db")] +fn leaf_name(path: &str) -> &str { + if path == "/" { + return "/"; + } + path.rsplit('/').next().unwrap_or(path) +} + +/// Classify a `std::io::Error` into a [`FallbackReason`]. +pub fn classify_io_error(error: &io::Error) -> FallbackReason { + match error.kind() { + io::ErrorKind::StorageFull => FallbackReason::DiskFull, + io::ErrorKind::ReadOnlyFilesystem => FallbackReason::ReadOnlyFilesystem, + io::ErrorKind::PermissionDenied => FallbackReason::PermissionDenied, + _ => { + // Check raw Unix errno for ENOSPC (28) / EDQUOT (122) / EROFS (30) + // when not mapped to a dedicated ErrorKind. + #[cfg(unix)] + if let Some(code) = error.raw_os_error() { + if code == 28 || code == 122 { + return FallbackReason::DiskFull; + } + if code == 30 { + return FallbackReason::ReadOnlyFilesystem; + } + } + FallbackReason::DatabaseUnavailable { + detail: error.to_string(), + } + } + } +} + +#[cfg(feature = "cache-db")] +fn classify_redb_error(error: &redb::Error) -> FallbackReason { + match error { + redb::Error::Io(io_err) => classify_io_error(io_err), + other => FallbackReason::DatabaseUnavailable { + detail: other.to_string(), + }, + } +} + +#[cfg(feature = "cache-db")] +fn clear_str_bytes_table( + txn: &redb::WriteTransaction, + def: TableDefinition<'_, &str, &[u8]>, +) -> Result<(), FallbackReason> { + let mut table = txn + .open_table(def) + .map_err(|e| classify_redb_error(&e.into()))?; + let keys: Vec = table + .iter() + .map_err(|e| classify_redb_error(&e.into()))? + .filter_map(Result::ok) + .map(|(k, _)| k.value().to_owned()) + .collect(); + for k in keys { + let _ = table + .remove(k.as_str()) + .map_err(|e| classify_redb_error(&e.into()))?; + } + Ok(()) +} + +#[cfg(feature = "cache-db")] +fn clear_path_table( + txn: &redb::WriteTransaction, +) -> Result<(), FallbackReason> { + let mut table = txn + .open_table(PATH_TO_DIR_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + let keys: Vec<(String, String)> = table + .iter() + .map_err(|e| classify_redb_error(&e.into()))? + .filter_map(Result::ok) + .map(|(k, _)| (k.value().0.to_owned(), k.value().1.to_owned())) + .collect(); + for (h, p) in keys { + let _ = table + .remove((h.as_str(), p.as_str())) + .map_err(|e| classify_redb_error(&e.into()))?; + } + Ok(()) +} + +#[cfg(feature = "cache-db")] +fn clear_dir_index_table( + txn: &redb::WriteTransaction, +) -> Result<(), FallbackReason> { + let mut table = txn + .open_table(DIR_INDEX_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + let keys: Vec<(String, u64)> = table + .iter() + .map_err(|e| classify_redb_error(&e.into()))? + .filter_map(Result::ok) + .map(|(k, _)| (k.value().0.to_owned(), k.value().1)) + .collect(); + for (h, id) in keys { + let _ = table + .remove((h.as_str(), id)) + .map_err(|e| classify_redb_error(&e.into()))?; + } + Ok(()) +} + +#[cfg(feature = "cache-db")] +fn clear_dir_children_table( + txn: &redb::WriteTransaction, +) -> Result<(), FallbackReason> { + let mut table = txn + .open_table(DIR_CHILDREN_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + let keys: Vec<(String, u64, u64)> = table + .iter() + .map_err(|e| classify_redb_error(&e.into()))? + .filter_map(Result::ok) + .map(|(k, _)| (k.value().0.to_owned(), k.value().1, k.value().2)) + .collect(); + for (h, p, c) in keys { + let _ = table + .remove((h.as_str(), p, c)) + .map_err(|e| classify_redb_error(&e.into()))?; + } + Ok(()) +} + +#[cfg(feature = "cache-db")] +fn clear_chunks_table( + txn: &redb::WriteTransaction, +) -> Result<(), FallbackReason> { + let mut table = txn + .open_table(CHUNKS_TABLE) + .map_err(|e| classify_redb_error(&e.into()))?; + let keys: Vec<(String, u64)> = table + .iter() + .map_err(|e| classify_redb_error(&e.into()))? + .filter_map(Result::ok) + .map(|(k, _)| (k.value().0.to_owned(), k.value().1)) + .collect(); + for (h, id) in keys { + let _ = table + .remove((h.as_str(), id)) + .map_err(|e| classify_redb_error(&e.into()))?; + } + Ok(()) +} + +#[cfg(all(test, feature = "cache-db"))] +mod tests { + use super::*; + use crate::tree::NodeFlags; + use crate::types::NodeKind; + + #[test] + fn store_narrow_widen_and_invalidate_roundtrip() { + let dir = tempfile::tempdir().expect("tempdir"); + let db = CacheDb::open(dir.path().join("cache.redb"), 0, false) + .expect("open db"); + + // Build a synthetic arena for `/fake/home/src`. + let mut src = TreeArena::new(PathBuf::from("/fake/home/src"), "src"); + let app = src.add_child( + src.root(), + "app", + NodeKind::Directory, + 0, + 0, + 100, + NodeFlags::new(NodeKind::Directory), + ); + src.add_child( + app, + "main.rs", + NodeKind::File, + 4096, + 250, + 100, + NodeFlags::new(NodeKind::File), + ); + src.aggregate(true, true); + + let opts = ScanOptions::default(); + let policy = CachePolicy::default(); + db.store_subtree(&HostKey::Local, &src, &opts, 1_000) + .expect("store"); + + // 1. Direct fresh hit at `/fake/home/src`. + let hit = db + .load_subtree( + &HostKey::Local, + Path::new("/fake/home/src"), + &opts, + 1_100, + &policy, + ) + .expect("load") + .expect("hit"); + assert!(matches!(hit.freshness, Freshness::Fresh { .. })); + assert_eq!(hit.arena.node(hit.arena.root()).allocated_bytes, 4096); + assert_eq!(hit.arena.node(hit.arena.root()).apparent_bytes, 250); + + // 2. Narrowing hit into `/fake/home/src/app` packed inside the chunk! + let narrow = db + .load_subtree( + &HostKey::Local, + Path::new("/fake/home/src/app"), + &opts, + 1_100, + &policy, + ) + .expect("narrow") + .expect("narrow hit"); + assert!(matches!(narrow.freshness, Freshness::Fresh { .. })); + assert_eq!(narrow.arena.node(narrow.arena.root()).apparent_bytes, 250); + + // 3. Partial hit at ancestor `/fake/home` (grafts cached `src` child). + let partial = db + .load_subtree( + &HostKey::Local, + Path::new("/fake/home"), + &opts, + 1_100, + &policy, + ) + .expect("partial") + .expect("partial hit"); + assert!(matches!(partial.freshness, Freshness::Partial { .. })); + assert_eq!( + partial.arena.node(partial.arena.root()).allocated_bytes, + 4096 + ); + + // 4. Stale detection past 15-minute TTL (1000 + 1000 > 900s). + let stale = db + .load_subtree( + &HostKey::Local, + Path::new("/fake/home/src"), + &opts, + 2_000, + &policy, + ) + .expect("stale") + .expect("stale hit"); + assert!(matches!(stale.freshness, Freshness::Stale { .. })); + + // 5. Targeted invalidation clears `/fake/home/src`. + let report = db + .invalidate(&HostKey::Local, &[PathBuf::from("/fake/home/src")]) + .expect("invalidate"); + assert!(report.invalidated_dirs >= 1); + let after = db + .load_subtree( + &HostKey::Local, + Path::new("/fake/home/src"), + &opts, + 1_100, + &policy, + ) + .expect("after"); + assert!(after.is_none()); + } +} diff --git a/crates/disktree-scanner/src/lib.rs b/crates/disktree-scanner/src/lib.rs new file mode 100644 index 0000000..b937686 --- /dev/null +++ b/crates/disktree-scanner/src/lib.rs @@ -0,0 +1,38 @@ +//! `disktree-scanner`: high-efficiency filesystem scanner with a compact +//! arena tree, prefix-trie front-coded string pool, columnar Protobuf cache +//! DB, priority-interruptible stale-while-revalidate (SWR), and automatic +//! fallback to in-memory or streaming modes. + +pub mod db; +#[cfg(target_os = "macos")] +pub mod macos; +#[cfg(windows)] +pub mod mft; +pub mod mounts; +pub mod proto; +pub mod session; +pub mod stream; +pub mod strings; +pub mod tree; +pub mod types; +pub mod walk; +#[cfg(windows)] +pub mod windows; + +pub use db::{CacheDb, CachedSubtree, InvalidateReport}; +pub use mounts::{default_cache_db_path, space_info}; +pub use session::{ScanEvent, ScanSession, ScanSnapshot, Scanner}; +pub use stream::{ + StreamConfig, StreamItem, stream_walk, stream_walk_with_config, +}; +pub use strings::{NameId, StringPool}; +pub use tree::{ArenaNode, HardlinkEntry, NodeFlags, NodeId, TreeArena}; +pub use types::{ + ActiveStorageMode, CachePolicy, CacheStats, DEFAULT_CACHE_TTL, + DEFAULT_MAX_DB_BYTES, DEFAULT_MIN_FREE_HEADROOM, FallbackReason, Freshness, + HostIdentity, HostKey, Metric, NodeKind, Priority, ScanOptions, ScanStats, + SpaceInfo, StorageMode, SubtreeStatus, unix_now, +}; +pub use walk::{ + DirTallyHook, PauseGate, SkipOracle, WalkConfig, WalkOutcome, WalkProgress, +}; diff --git a/crates/disktree-core/src/macos.rs b/crates/disktree-scanner/src/macos.rs similarity index 100% rename from crates/disktree-core/src/macos.rs rename to crates/disktree-scanner/src/macos.rs diff --git a/crates/disktree-core/src/mft.rs b/crates/disktree-scanner/src/mft.rs similarity index 93% rename from crates/disktree-core/src/mft.rs rename to crates/disktree-scanner/src/mft.rs index 4b236b5..c219a84 100644 --- a/crates/disktree-core/src/mft.rs +++ b/crates/disktree-scanner/src/mft.rs @@ -20,10 +20,9 @@ use std::fs::{File, OpenOptions}; use std::io; -use std::num::NonZeroU64; use std::os::windows::fs::{FileExt as _, OpenOptionsExt as _}; use std::path::Path; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use rayon::prelude::*; use windows_sys::Win32::Storage::FileSystem::{ @@ -33,8 +32,8 @@ use windows_sys::Win32::Storage::FileSystem::{ FILE_SHARE_WRITE, }; -use crate::scan::{ScanOptions, ScanProgress}; -use crate::tree::{Node, NodeKind}; +use crate::types::{NodeKind, ScanOptions}; +use crate::walk::{BuiltChild, BuiltNode, LeafRecord, WalkProgress}; use crate::windows::{Aligned, drive_letter}; /// Most bytes read per call: large enough that the disk streams, small @@ -162,12 +161,13 @@ struct Geometry { /// The tree under `root`, read from the volume's file table; `None` when /// the table cannot be read and the walk has to measure instead. -pub fn scan( +pub(crate) fn scan( root: &Path, canonical: &Path, options: &ScanOptions, - progress: &ScanProgress, -) -> Option> { + cancel: &AtomicBool, + progress: &WalkProgress, +) -> Option> { // A followed link can lead off this volume, or back into it a second // time, and the table describes neither: the walk follows them. if options.follow_links { @@ -189,15 +189,15 @@ pub fn scan( geometry.record, &reads, &mut infos, - options.apparent_size, + cancel, progress, )?; - if progress.is_cancelled() { + if cancel.load(Ordering::Relaxed) { return Some(Err(cancelled())); } let (mut names, texts) = merge(parsed, &mut infos); - if progress.is_cancelled() { + if cancel.load(Ordering::Relaxed) { return Some(Err(cancelled())); } if !is_root_directory(&infos) { @@ -211,10 +211,14 @@ pub fn scan( texts, starts, options, - progress, + cancel, directories: AtomicUsize::new(0), }; - let tree = table.directory(ROOT, crate::scan::file_name(root), 0); + let root_name = root.file_name().map_or_else( + || root.to_string_lossy().into_owned(), + |name| name.to_string_lossy().into_owned(), + ); + let tree = table.directory(ROOT, root_name, false, 0); // Hundreds of megabytes, whose freeing the caller would otherwise // wait out before it can finish the tree. let Table { @@ -229,7 +233,9 @@ pub fn scan( let _ = std::thread::Builder::new() .spawn(move || drop((infos, names, texts, starts))); match tree { - Ok(_) | Err(Stop) if progress.is_cancelled() => Some(Err(cancelled())), + Ok(_) | Err(Stop) if cancel.load(Ordering::Relaxed) => { + Some(Err(cancelled())) + } Ok(node) => Some(Ok(node)), Err(Stop) => None, } @@ -605,8 +611,8 @@ fn read_records( record: usize, reads: &[(u64, u64, u64)], infos: &mut [Info], - apparent_size: bool, - progress: &ScanProgress, + cancel: &AtomicBool, + progress: &WalkProgress, ) -> Option> { let threads = rayon::current_num_threads().max(1); let mut stretches: Vec> = @@ -637,7 +643,7 @@ fn read_records( .step_by(threads) .zip(stretches) { - if progress.is_cancelled() { + if cancel.load(Ordering::Relaxed) { break; } let buffer = buffer.bytes(usize::try_from(size).ok()?); @@ -649,12 +655,13 @@ fn read_records( u32::try_from(chunk).ok()?, stretch, ); - let bytes = if apparent_size { - chunk.apparent - } else { - chunk.allocated - }; - progress.add(chunk.files, 0, bytes); + progress.files.fetch_add(chunk.files, Ordering::Relaxed); + progress + .allocated_bytes + .fetch_add(chunk.allocated, Ordering::Relaxed); + progress + .apparent_bytes + .fetch_add(chunk.apparent, Ordering::Relaxed); parsed.push(chunk); } Some(parsed) @@ -1063,7 +1070,7 @@ struct Table<'a> { texts: Vec, starts: Vec, options: &'a ScanOptions, - progress: &'a ScanProgress, + cancel: &'a AtomicBool, /// Directories built so far. Each is built from one entry, so more of /// them than there are entries means one was reached twice: a crafted /// table that gives directories several names doubles the tree at @@ -1090,15 +1097,16 @@ impl Table<'_> { } } - /// Mirrors what the walk keeps: see `WalkContext::classify`. + /// Mirrors what the walk keeps: see `scan_dir`. fn directory( &self, number: u32, - name: Box, + name: String, + hidden: bool, depth: usize, - ) -> Result { + ) -> Result { if depth >= MOST_LEVELS - || self.progress.is_cancelled() + || self.cancel.load(Ordering::Relaxed) || self.directories.fetch_add(1, Ordering::Relaxed) > self.names.len() { @@ -1107,10 +1115,14 @@ impl Table<'_> { let descend = self.options.max_depth.is_none_or(|max| depth < max); let sequence = self.infos.get(number as usize).map(|info| info.sequence); + let modified = self + .infos + .get(number as usize) + .map_or(0, |info| info.modified); let child = |entry: &Entry| { // A root directory holds hundreds of thousands of files; a // check per entry lets a cancel stop within one. - if self.progress.is_cancelled() { + if self.cancel.load(Ordering::Relaxed) { return Some(Err(Stop)); } // An entry naming a parent whose record has since been reused. @@ -1120,8 +1132,8 @@ impl Table<'_> { self.child(entry, depth, descend).transpose() }; let entries = self.entries(number); - // See `tree::PARALLEL_LEVELS`: parallel only near the top. - let children = if depth < crate::tree::PARALLEL_LEVELS { + const PARALLEL_LEVELS: usize = 3; + let children = if depth < PARALLEL_LEVELS { entries .par_iter() .filter_map(child) @@ -1135,9 +1147,14 @@ impl Table<'_> { } children }; - let mut node = Node::directory(name); - node.children = children; - Ok(node) + Ok(BuiltNode { + name, + modified, + read_error: false, + hidden, + lossy_name: false, + children, + }) } /// The node for `entry`; `None` for one the walk would not list. @@ -1146,7 +1163,7 @@ impl Table<'_> { entry: &Entry, depth: usize, descend: bool, - ) -> Result, Stop> { + ) -> Result, Stop> { // The root is its own parent. if entry.child == entry.parent || entry.child < FIRST_USER_RECORD { return Ok(None); @@ -1158,12 +1175,8 @@ impl Table<'_> { return Ok(None); } let name = self.name(entry); - if !self.options.include_hidden - && (name.starts_with('.') - || info.attributes & FILE_ATTRIBUTE_HIDDEN != 0) - { - return Ok(None); - } + let hidden = name.starts_with('.') + || info.attributes & FILE_ATTRIBUTE_HIDDEN != 0; let link = info.attributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 && info.reparse_tag & NAME_SURROGATE != 0; if info.directory && !link { @@ -1171,26 +1184,24 @@ impl Table<'_> { return Ok(None); } return self - .directory(entry.child, name.into(), depth + 1) - .map(Some); + .directory(entry.child, name.to_owned(), hidden, depth + 1) + .map(|dir| Some(BuiltChild::Dir(dir))); } - let size = if self.options.apparent_size { - info.apparent - } else { - info.allocated - }; let kind = if link { NodeKind::Symlink } else { NodeKind::File }; - let mut node = Node::entry(name, kind, size); - node.modified = info.modified; - if info.names > 1 { - node.inode = NonZeroU64::new(u64::from(entry.child)) - .map(|record| (0, record)); - } - Ok(Some(node)) + Ok(Some(BuiltChild::Leaf(LeafRecord { + name: name.to_owned(), + kind, + allocated_bytes: info.allocated, + apparent_bytes: info.apparent, + modified: info.modified, + hidden, + lossy_name: false, + hardlink: (info.names > 1).then(|| (0, u64::from(entry.child))), + }))) } } @@ -1477,7 +1488,8 @@ mod tests { .map(|read| (read * 4096, 4096, read * 4)) .collect(); let mut infos = super::table(&reads, RECORD); - let progress = ScanProgress::default(); + let cancel = AtomicBool::new(false); + let progress = WalkProgress::default(); let pool = rayon::ThreadPoolBuilder::new() .num_threads(3) .build() @@ -1489,7 +1501,7 @@ mod tests { RECORD, &reads, &mut infos, - false, + &cancel, &progress, ) }) @@ -1510,7 +1522,7 @@ mod tests { &texts[entry.chunk as usize][at..][..usize::from(entry.len)]; assert_eq!(text, format!("f{}", entry.child)); } - assert_eq!(progress.snapshot().files, 64); + assert_eq!(progress.files.load(Ordering::Relaxed), 64); } #[test] @@ -1575,7 +1587,7 @@ mod tests { fn table<'a>( rows: &[(u32, u32, u16, &str, Info)], options: &'a ScanOptions, - progress: &'a ScanProgress, + cancel: &'a AtomicBool, ) -> Table<'a> { let mut infos = vec![Info::default(); 64]; infos[ROOT as usize] = Info { @@ -1606,16 +1618,35 @@ mod tests { texts: vec![text], starts, options, - progress, + cancel, directories: AtomicUsize::new(0), } } - fn paths(node: &Node, prefix: &str, out: &mut Vec<(String, NodeKind)>) { + fn paths( + node: &BuiltNode, + prefix: &str, + include_hidden: bool, + out: &mut Vec<(String, NodeKind)>, + ) { for child in &node.children { - let path = format!("{prefix}{}", child.name); - out.push((path.clone(), child.kind)); - paths(child, &format!("{path}/"), out); + match child { + BuiltChild::Dir(dir) => { + if !include_hidden && dir.hidden { + continue; + } + let path = format!("{prefix}{}", dir.name); + out.push((path.clone(), NodeKind::Directory)); + paths(dir, &format!("{path}/"), include_hidden, out); + } + BuiltChild::Leaf(leaf) => { + if !include_hidden && leaf.hidden { + continue; + } + out.push((format!("{prefix}{}", leaf.name), leaf.kind)); + } + BuiltChild::Grafted { .. } => {} + } } } @@ -1698,7 +1729,7 @@ mod tests { "sub/linked.txt", "visible.txt", ]; - let progress = ScanProgress::default(); + let cancel = AtomicBool::new(false); for (include_hidden, max_depth, expected) in [(true, None, everything), (false, Some(1), shallow_visible)] { @@ -1707,15 +1738,16 @@ mod tests { max_depth, ..ScanOptions::default() }; - let Ok(root) = table(&rows, &options, &progress).directory( + let Ok(root) = table(&rows, &options, &cancel).directory( ROOT, "C:\\".into(), + false, 0, ) else { panic!("the table is not cut short"); }; let mut found = Vec::new(); - paths(&root, "", &mut found); + paths(&root, "", include_hidden, &mut found); found.sort_by(|left, right| left.0.cmp(&right.0)); let kind = |path: &str| match path { "link" => NodeKind::Symlink, @@ -1729,7 +1761,14 @@ mod tests { assert_eq!(found, expected, "include_hidden {include_hidden}"); // Only a file with a second name needs its identity kept. - let inode = |name: &str| root.child_named(name).unwrap().identity(); + let inode = |name: &str| { + root.children.iter().find_map(|child| match child { + BuiltChild::Leaf(leaf) if leaf.name == name => { + leaf.hardlink + } + _ => None, + }) + }; assert_eq!(inode("linked.txt"), Some((0, 31))); assert_eq!(inode("visible.txt"), None); } @@ -1749,9 +1788,9 @@ mod tests { (40, 41, 1, "again", dir), ]; let options = ScanOptions::default(); - let progress = ScanProgress::default(); - let table = table(&rows, &options, &progress); - assert!(table.directory(ROOT, "C:\\".into(), 0).is_err()); - assert!(!progress.is_cancelled()); + let cancel = AtomicBool::new(false); + let table = table(&rows, &options, &cancel); + assert!(table.directory(ROOT, "C:\\".into(), false, 0).is_err()); + assert!(!cancel.load(Ordering::Relaxed)); } } diff --git a/crates/disktree-scanner/src/mounts.rs b/crates/disktree-scanner/src/mounts.rs new file mode 100644 index 0000000..e639d3d --- /dev/null +++ b/crates/disktree-scanner/src/mounts.rs @@ -0,0 +1,400 @@ +//! Volume capacity, mount boundaries, and cache free-space guards. + +use std::io; +use std::path::{Path, PathBuf}; + +use rustc_hash::FxHashSet; + +use crate::types::{FallbackReason, SpaceInfo}; + +/// Read capacity of the volume containing `path`. +#[cfg(not(windows))] +pub fn space_info(path: &Path) -> io::Result { + let stat = rustix::fs::statvfs(path)?; + let block = if stat.f_frsize == 0 { + stat.f_bsize + } else { + stat.f_frsize + }; + Ok(SpaceInfo { + total: stat.f_blocks.saturating_mul(block), + free: stat.f_bfree.saturating_mul(block), + available: stat.f_bavail.saturating_mul(block), + }) +} + +#[cfg(windows)] +pub fn space_info(path: &Path) -> io::Result { + crate::windows::space_info(path) +} + +/// Check whether `dir` (or its nearest existing ancestor) has at least +/// `required_headroom` bytes available for cache DB storage. +pub fn check_cache_headroom( + path: &Path, + required_headroom: u64, +) -> Result<(), FallbackReason> { + if required_headroom == 0 { + return Ok(()); + } + let probe = nearest_existing_ancestor(path); + let Ok(info) = space_info(&probe) else { + // If statvfs isn't available on this target, let the DB open attempt + // determine writability. + return Ok(()); + }; + if info.available < required_headroom { + return Err(FallbackReason::LowDiskSpace { + available: info.available, + required: required_headroom, + }); + } + Ok(()) +} + +/// Nearest ancestor of `path` that currently exists on disk. +pub fn nearest_existing_ancestor(path: &Path) -> PathBuf { + let mut cur = path.to_path_buf(); + while !cur.exists() { + if !cur.pop() { + return PathBuf::from("/"); + } + } + cur +} + +/// Default cache database file path for the current user. +pub fn default_cache_db_path() -> Option { + #[cfg(target_os = "macos")] + { + let home = std::env::var_os("HOME")?; + return Some( + PathBuf::from(home).join("Library/Caches/disktree/scan-cache.redb"), + ); + } + #[cfg(windows)] + { + let base = std::env::var_os("LOCALAPPDATA")?; + return Some( + PathBuf::from(base).join("disktree/cache/scan-cache.redb"), + ); + } + #[cfg(not(any(target_os = "macos", windows)))] + { + if let Some(xdg) = std::env::var_os("XDG_CACHE_HOME") + && !xdg.is_empty() + { + return Some(PathBuf::from(xdg).join("disktree/scan-cache.redb")); + } + let home = std::env::var_os("HOME")?; + Some(PathBuf::from(home).join(".cache/disktree/scan-cache.redb")) + } +} + +/// Every nested mount strictly beneath `root`, including bind mounts and +/// same-device Btrfs subvolumes. Used by remote/streaming walks. +pub fn strict_mount_boundaries_for(root: &Path) -> Option> { + #[cfg(target_os = "linux")] + { + let table = std::fs::read_to_string("/proc/self/mounts").ok()?; + let canonical = + root.canonicalize().unwrap_or_else(|_| root.to_path_buf()); + Some(mount_boundaries_in(&table, &canonical)) + } + #[cfg(target_os = "macos")] + { + let output = std::process::Command::new("mount").output().ok()?; + if !output.status.success() { + return None; + } + let canonical = + root.canonicalize().unwrap_or_else(|_| root.to_path_buf()); + Some( + parse_macos_mounts(&String::from_utf8_lossy(&output.stdout)) + .into_iter() + .filter(|point| { + point != &canonical && point.starts_with(&canonical) + }) + .collect(), + ) + } + #[cfg(windows)] + { + let canonical = + root.canonicalize().unwrap_or_else(|_| root.to_path_buf()); + Some( + crate::windows::mount_points() + .into_iter() + .filter(|point| { + point != &canonical && point.starts_with(&canonical) + }) + .collect(), + ) + } + #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))] + { + let _ = root; + None + } +} + +/// Mount points a local `--one-filesystem` scan must not enter. +/// +/// Distinct Btrfs subvolumes on the same local device are included, while +/// duplicate views, snapshots, other filesystems and automounts stay out. +pub fn mount_boundaries_for(root: &Path) -> Option> { + #[cfg(target_os = "linux")] + { + let table = std::fs::read_to_string("/proc/self/mounts").ok()?; + let canonical = + root.canonicalize().unwrap_or_else(|_| root.to_path_buf()); + let boundaries = mount_boundaries_in(&table, &canonical); + // Without mountinfo, don't guess whether a mount is a distinct + // subvolume or a bind mount. + let Ok(info) = std::fs::read_to_string("/proc/self/mountinfo") else { + return Some(boundaries); + }; + let views: Vec<_> = info.lines().filter_map(MountView::parse).collect(); + Some(local_boundaries(boundaries, &views, &canonical)) + } + #[cfg(not(target_os = "linux"))] + { + strict_mount_boundaries_for(root) + } +} + +#[cfg(target_os = "macos")] +fn parse_macos_mounts(output: &str) -> Vec { + output + .lines() + .filter_map(|line| { + let (_, rest) = line.split_once(" on ")?; + let (point, _) = rest.rsplit_once(" (")?; + Some(PathBuf::from(point)) + }) + .collect() +} + +/// Parse mount boundaries strictly below `root` from a `/proc/self/mounts` +/// formatted table. +pub fn mount_boundaries_in(table: &str, root: &Path) -> FxHashSet { + let mut boundaries = FxHashSet::default(); + for line in table.lines() { + let mut fields = line.split_whitespace(); + let Some(_device) = fields.next() else { + continue; + }; + let Some(raw_point) = fields.next() else { + continue; + }; + let point = PathBuf::from(unescape_octal(raw_point)); + if point != root && point.starts_with(root) { + boundaries.insert(point); + } + } + boundaries +} + +/// Remove distinct same-device Btrfs subvolumes from strict boundaries. +/// Overlapping filesystem roots are left out to avoid counting a bind mount +/// or another view of the same data twice. +pub fn local_boundaries( + mut boundaries: std::collections::HashSet, + views: &[MountView], + root: &Path, +) -> std::collections::HashSet { + let Some(own) = views + .iter() + .filter(|view| root.starts_with(&view.point)) + .max_by_key(|view| view.point.components().count()) + else { + return boundaries; + }; + if own.fstype != "btrfs" || !own.source.starts_with("/dev/") { + return boundaries; + } + let mut candidates: Vec<_> = views + .iter() + .filter(|view| boundaries.contains(&view.point)) + .collect(); + candidates.sort_by_key(|view| { + ( + view.point.components().count(), + view.point.as_os_str().len(), + &view.point, + ) + }); + let mut kept = vec![own.fs_root.clone()]; + for view in candidates { + let unique = views + .iter() + .filter(|other| other.point == view.point) + .count() + == 1; + if unique + && view.fstype == "btrfs" + && view.source == own.source + && view.fs_root.is_absolute() + && !view.snapshot + && !kept.iter().any(|existing| { + view.fs_root.starts_with(existing) + || existing.starts_with(&view.fs_root) + }) + { + kept.push(view.fs_root.clone()); + boundaries.remove(&view.point); + } + } + boundaries +} + +/// A mounted view needed to distinguish Btrfs subvolumes from aliases. +#[derive(Clone, Debug)] +pub struct MountView { + pub point: PathBuf, + pub fs_root: PathBuf, + pub fstype: String, + pub source: String, + pub snapshot: bool, +} + +impl MountView { + fn parse(line: &str) -> Option { + let (left, right) = line.split_once(" - ")?; + let mut left = left.split_whitespace().skip(3); + let fs_root = PathBuf::from(unescape_octal(left.next()?)); + let point = PathBuf::from(unescape_octal(left.next()?)); + let mut right = right.split_whitespace(); + let fstype = right.next()?.to_owned(); + let source = unescape_octal(right.next()?); + let snapshot = + point.file_name().is_some_and(|name| name == ".snapshots") + || fs_root.to_string_lossy().contains("snapshots"); + Some(Self { + point, + fs_root, + fstype, + source, + snapshot, + }) + } +} + +/// Directories under `root` a scan must never enter, even with +/// `one_filesystem = false`: virtual kernel filesystems on Linux, and macOS's +/// duplicate Data volume mount + `/Network` automount. +pub fn never_scanned(root: &Path) -> FxHashSet { + let mut set = FxHashSet::default(); + #[cfg(target_os = "linux")] + { + for virtual_fs in ["/proc", "/sys", "/dev"] { + let path = PathBuf::from(virtual_fs); + if path != root && path.starts_with(root) { + set.insert(path); + } + } + } + #[cfg(target_os = "macos")] + { + for skip in ["/System/Volumes/Data", "/Network"] { + let path = PathBuf::from(skip); + if path != root && path.starts_with(root) { + set.insert(path); + } + } + } + #[cfg(not(any(target_os = "linux", target_os = "macos")))] + { + let _ = root; + } + set +} + +fn unescape_octal(raw: &str) -> String { + let bytes = raw.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut idx = 0; + while idx < bytes.len() { + if bytes[idx] == b'\\' + && idx + 3 < bytes.len() + && bytes[idx + 1..idx + 4] + .iter() + .all(|b| (b'0'..=b'7').contains(b)) + { + let octal = ((bytes[idx + 1] - b'0') << 6) + | ((bytes[idx + 2] - b'0') << 3) + | (bytes[idx + 3] - b'0'); + out.push(octal); + idx += 4; + } else { + out.push(bytes[idx]); + idx += 1; + } + } + String::from_utf8_lossy(&out).into_owned() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn btrfs_home_is_included_without_entering_network_or_aliases() { + let mounts = "\ +/dev/root / btrfs rw 0 0\n\ +/dev/root /home-copy btrfs rw 0 0\n\ +/dev/root /home btrfs rw 0 0\n\ +/dev/root /bind btrfs rw 0 0\n\ +/dev/root /.snapshots btrfs rw 0 0\n\ +/dev/other /external btrfs rw 0 0\n\ +server:/share /nas nfs rw 0 0\n\ +user@host:/ /ssh fuse.sshfs rw 0 0\n"; + let info = "\ +1 0 0:1 /@ / rw - btrfs /dev/root rw\n\ +2 1 0:1 /@home /home-copy rw - btrfs /dev/root rw\n\ +3 1 0:1 /@home /home rw - btrfs /dev/root rw\n\ +4 1 0:1 /@/data /bind rw - btrfs /dev/root rw\n\ +5 1 0:1 /@snapshots /.snapshots rw - btrfs /dev/root rw\n\ +6 1 0:2 /@data /external rw - btrfs /dev/other rw\n\ +7 1 0:3 / /nas rw - nfs server:/share rw\n\ +8 1 0:4 / /ssh rw - fuse.sshfs user@host:/ rw\n"; + let views: Vec<_> = info.lines().filter_map(MountView::parse).collect(); + let boundaries = local_boundaries( + mount_boundaries_in(mounts, Path::new("/")), + &views, + Path::new("/"), + ); + assert!(!boundaries.contains(Path::new("/home"))); + for path in [ + "/home-copy", + "/bind", + "/.snapshots", + "/external", + "/nas", + "/ssh", + ] { + assert!(boundaries.contains(Path::new(path)), "{path}"); + } + } + + #[test] + fn mount_boundaries_exclude_nested_and_bind_mounts() { + let table = "\ +/dev/nvme0n1p2 / ext4 rw 0 0 +/dev/nvme0n1p2 /home/tobi/bind\\040mount ext4 rw 0 0 +tmpfs /tmp tmpfs rw 0 0 +"; + let boundaries = mount_boundaries_in(table, Path::new("/home/tobi")); + assert!(boundaries.contains(Path::new("/home/tobi/bind mount"))); + assert!(!boundaries.contains(Path::new("/tmp"))); + } + + #[test] + fn headroom_guard_flags_impossible_requirement() { + let dir = tempfile::tempdir().expect("tempdir"); + if space_info(dir.path()).is_ok() { + let result = check_cache_headroom(dir.path(), u64::MAX); + assert!(matches!(result, Err(FallbackReason::LowDiskSpace { .. }))); + } + } +} diff --git a/crates/disktree-scanner/src/proto.rs b/crates/disktree-scanner/src/proto.rs new file mode 100644 index 0000000..1cd0a6f --- /dev/null +++ b/crates/disktree-scanner/src/proto.rs @@ -0,0 +1,627 @@ +//! Hand-written Protobuf schema (`prost::Message`), columnar `SubtreeChunk` +//! encoding/decoding, and LZ4 frame compression. +//! +//! Mirrors `proto/disktree_cache.proto` directly with zero `protoc` or +//! `build.rs` dependency. + +use std::collections::HashMap; +use std::hash::BuildHasher; +use std::io; +use std::path::PathBuf; + +use rustc_hash::FxHashMap; + +use crate::strings::{NameId, StringPool}; +use crate::tree::{ArenaNode, HardlinkEntry, NodeFlags, NodeId, TreeArena}; +use crate::types::SubtreeStatus; + +/// Current binary cache schema version. +pub const FORMAT_VERSION: u32 = 1; + +/// Frame codec tags prepended to stored chunks. +pub const CODEC_RAW: u8 = 0; +pub const CODEC_LZ4: u8 = 1; + +/// Directory coverage states stored in [`DirIndexEntry::coverage`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u32)] +pub enum Coverage { + /// Ancestor placeholder; directory itself has not been scanned. + Stub = 0, + /// Full recursive scan completed under its recorded options. + Complete = 1, + /// Scanned only down to `scanned_max_depth`. + Shallow = 2, + /// Stopped at a mount boundary. + MountBoundary = 3, + /// Directory could not be read. + ReadError = 4, +} + +impl Coverage { + pub const fn from_u32(value: u32) -> Self { + match value { + 1 => Self::Complete, + 2 => Self::Shallow, + 3 => Self::MountBoundary, + 4 => Self::ReadError, + _ => Self::Stub, + } + } +} + +#[derive(Clone, PartialEq, Eq, prost::Message)] +pub struct DbHeader { + #[prost(uint32, tag = "1")] + pub format_version: u32, + #[prost(uint64, tag = "2")] + pub created_at_unix: u64, + #[prost(uint32, tag = "3")] + pub codec: u32, +} + +#[derive(Clone, PartialEq, Eq, prost::Message)] +pub struct HostRecord { + #[prost(string, tag = "1")] + pub host_key: String, + #[prost(string, tag = "2")] + pub hostname: String, + #[prost(string, tag = "3")] + pub machine_id: String, + #[prost(string, tag = "4")] + pub platform: String, + #[prost(uint32, tag = "5")] + pub path_style: u32, + #[prost(uint64, tag = "6")] + pub updated_at_unix: u64, +} + +#[derive(Clone, PartialEq, Eq, prost::Message)] +pub struct DirIndexEntry { + #[prost(uint64, tag = "1")] + pub dir_id: u64, + #[prost(uint64, tag = "2")] + pub parent_id: u64, + #[prost(string, tag = "3")] + pub name: String, + #[prost(uint64, tag = "4")] + pub scanned_at_unix: u64, + #[prost(uint32, tag = "5")] + pub coverage: u32, + #[prost(uint32, tag = "6")] + pub scanned_max_depth: u32, + #[prost(uint32, tag = "7")] + pub options_mask: u32, + #[prost(uint64, tag = "8")] + pub mount_dev: u64, + #[prost(int64, tag = "9")] + pub dir_mtime: i64, + #[prost(uint64, tag = "10")] + pub chunk_id: u64, + #[prost(uint64, tag = "11")] + pub allocated_bytes: u64, + #[prost(uint64, tag = "12")] + pub apparent_bytes: u64, + #[prost(uint64, tag = "13")] + pub files: u64, + #[prost(uint32, tag = "14")] + pub dirs: u32, + #[prost(int64, tag = "15")] + pub newest_mtime: i64, +} + +#[derive(Clone, PartialEq, Eq, prost::Message)] +pub struct FrontCodedStrings { + #[prost(uint32, tag = "1")] + pub count: u32, + #[prost(bytes = "vec", tag = "2")] + pub encoded: Vec, +} + +#[derive(Clone, PartialEq, Eq, prost::Message)] +pub struct SubtreeChunk { + #[prost(uint64, tag = "1")] + pub chunk_id: u64, + #[prost(uint64, tag = "2")] + pub root_dir_id: u64, + #[prost(uint64, tag = "3")] + pub scanned_at_unix: u64, + #[prost(int64, tag = "4")] + pub base_mtime: i64, + #[prost(message, optional, tag = "5")] + pub strings: Option, + + #[prost(uint32, repeated, packed = "true", tag = "6")] + pub name_ids: Vec, + #[prost(uint32, repeated, packed = "true", tag = "7")] + pub child_counts: Vec, + #[prost(uint32, repeated, packed = "true", tag = "8")] + pub flags: Vec, + #[prost(uint64, repeated, packed = "true", tag = "9")] + pub allocated_bytes: Vec, + #[prost(sint64, repeated, packed = "true", tag = "10")] + pub apparent_deltas: Vec, + #[prost(sint64, repeated, packed = "true", tag = "11")] + pub mtime_deltas: Vec, + + #[prost(uint32, repeated, packed = "true", tag = "12")] + pub hardlink_node_idx: Vec, + #[prost(uint64, repeated, packed = "true", tag = "13")] + pub hardlink_devs: Vec, + #[prost(uint64, repeated, packed = "true", tag = "14")] + pub hardlink_inos: Vec, + + #[prost(uint64, repeated, packed = "true", tag = "15")] + pub external_dir_ids: Vec, +} + +/// Decoded chunk together with any external child shard links that must be +/// grafted into the returned arena. +#[derive(Debug)] +pub struct DecodedChunk { + pub arena: TreeArena, + pub scanned_at: u64, + /// `(node_id_in_arena, child_dir_id_in_db)` + pub external_links: Vec<(NodeId, u64)>, +} + +/// Encode a protobuf message into a 1-byte codec-tagged frame, using LZ4 when +/// it saves space. +pub fn encode_framed(msg: &M) -> Vec { + let raw = msg.encode_to_vec(); + if raw.len() >= 64 { + let compressed = lz4_flex::compress_prepend_size(&raw); + if compressed.len() < raw.len() { + let mut framed = Vec::with_capacity(1 + compressed.len()); + framed.push(CODEC_LZ4); + framed.extend_from_slice(&compressed); + return framed; + } + } + let mut framed = Vec::with_capacity(1 + raw.len()); + framed.push(CODEC_RAW); + framed.extend_from_slice(&raw); + framed +} + +/// Decode a codec-tagged protobuf frame produced by [`encode_framed`]. +pub fn decode_framed( + bytes: &[u8], +) -> io::Result { + let (&codec, payload) = bytes.split_first().ok_or_else(|| { + io::Error::new(io::ErrorKind::UnexpectedEof, "empty protobuf frame") + })?; + match codec { + CODEC_RAW => M::decode(payload) + .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err)), + CODEC_LZ4 => { + let raw = lz4_flex::decompress_size_prepended(payload).map_err( + |err| io::Error::new(io::ErrorKind::InvalidData, err), + )?; + M::decode(raw.as_slice()) + .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err)) + } + other => Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("unsupported protobuf frame codec {other}"), + )), + } +} + +/// Encode a subtree of `arena` rooted at `sub_root` into a columnar +/// [`SubtreeChunk`], stopping at any descendant listed in `external_shards`. +pub fn encode_subtree_chunk( + arena: &TreeArena, + sub_root: NodeId, + chunk_id: u64, + root_dir_id: u64, + scanned_at_unix: u64, + external_shards: &HashMap, +) -> SubtreeChunk { + // Index hardlinks by node for O(1) lookup during preorder walk. + let mut hardlink_by_node: FxHashMap> = + FxHashMap::default(); + for link in arena.hardlinks() { + hardlink_by_node + .entry(link.node) + .or_default() + .push((link.dev, link.ino)); + } + + let mut local_strings = StringPool::new(); + let mut name_ids = Vec::new(); + let mut child_counts = Vec::new(); + let mut flags = Vec::new(); + let mut allocated_bytes = Vec::new(); + let mut apparent_deltas = Vec::new(); + let mut mtime_deltas = Vec::new(); + let mut hardlink_node_idx = Vec::new(); + let mut hardlink_devs = Vec::new(); + let mut hardlink_inos = Vec::new(); + let mut external_dir_ids = Vec::new(); + + let base_mtime = arena.node(sub_root).modified; + let mut prev_mtime = base_mtime; + + let mut stack = vec![sub_root]; + while let Some(node_id) = stack.pop() { + let node = arena.node(node_id); + let preorder_idx = name_ids.len() as u32; + let local_name = local_strings.intern(arena.name(node_id)); + name_ids.push(local_name.0); + + let is_external = + node_id != sub_root && external_shards.contains_key(&node_id); + + let mut bits = node.flags.persistent_bits(); + if is_external { + bits |= NodeFlags::EXTERNAL_SHARD_REF; + flags.push(bits); + child_counts.push(0); + allocated_bytes.push(0); + apparent_deltas.push(0); + mtime_deltas.push(node.modified.saturating_sub(prev_mtime)); + prev_mtime = node.modified; + external_dir_ids.push(external_shards[&node_id]); + continue; + } + + flags.push(bits); + + if node.is_dir() { + let kids: Vec = arena.children(node_id).collect(); + child_counts.push(kids.len() as u32); + // Derived totals are recomputed on decode; store 0 for dirs to + // maximize compression and uphold Invariant #2. + allocated_bytes.push(0); + apparent_deltas.push(0); + mtime_deltas.push(node.modified.saturating_sub(prev_mtime)); + prev_mtime = node.modified; + for kid in kids.into_iter().rev() { + stack.push(kid); + } + } else { + child_counts.push(0); + allocated_bytes.push(node.allocated_bytes); + let delta = i128::from(node.apparent_bytes) + - i128::from(node.allocated_bytes); + let clamped = + delta.clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64; + apparent_deltas.push(clamped); + mtime_deltas.push(node.modified.saturating_sub(prev_mtime)); + prev_mtime = node.modified; + + if let Some(links) = hardlink_by_node.get(&node_id) { + for &(dev, ino) in links { + hardlink_node_idx.push(preorder_idx); + hardlink_devs.push(dev); + hardlink_inos.push(ino); + } + } + } + } + + // Prefix-trie front-code the local string dictionary and remap name IDs. + let (encoded_strings, remap) = local_strings.encode_front_coded(); + for id in &mut name_ids { + *id = remap[*id as usize].0; + } + + SubtreeChunk { + chunk_id, + root_dir_id, + scanned_at_unix, + base_mtime, + strings: Some(FrontCodedStrings { + count: local_strings.len() as u32, + encoded: encoded_strings, + }), + name_ids, + child_counts, + flags, + allocated_bytes, + apparent_deltas, + mtime_deltas, + hardlink_node_idx, + hardlink_devs, + hardlink_inos, + external_dir_ids, + } +} + +/// Decode a columnar [`SubtreeChunk`] back into a [`TreeArena`] and its +/// external child shard references. +pub fn decode_subtree_chunk( + chunk: &SubtreeChunk, + root_path: PathBuf, +) -> io::Result { + let count = chunk.name_ids.len(); + if count == 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "empty subtree chunk", + )); + } + if chunk.child_counts.len() != count + || chunk.flags.len() != count + || chunk.allocated_bytes.len() != count + || chunk.apparent_deltas.len() != count + || chunk.mtime_deltas.len() != count + { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "mismatched columnar lengths in subtree chunk", + )); + } + if chunk.hardlink_node_idx.len() != chunk.hardlink_devs.len() + || chunk.hardlink_node_idx.len() != chunk.hardlink_inos.len() + { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "mismatched hardlink arrays in subtree chunk", + )); + } + + let strings = match &chunk.strings { + Some(dict) => { + StringPool::decode_front_coded(dict.count, &dict.encoded)? + } + None => StringPool::new(), + }; + + let mut nodes = Vec::with_capacity(count); + let mut last_child: Vec> = vec![None; count]; + let mut external_links = Vec::with_capacity(chunk.external_dir_ids.len()); + let mut ext_cursor = 0usize; + let mut cur_mtime = chunk.base_mtime; + + // Stack of `(parent_node_id, remaining_children_expected)`. + let mut parent_stack: Vec<(NodeId, u32)> = Vec::new(); + + for idx in 0..count { + let name_raw = chunk.name_ids[idx]; + if (name_raw as usize) >= strings.len() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "name_id out of bounds in subtree chunk", + )); + } + + let parent = if idx == 0 { + None + } else { + let Some(&(parent_id, _)) = parent_stack.last() else { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "orphan node in subtree chunk preorder", + )); + }; + Some(parent_id) + }; + + if let Some((_, remaining)) = parent_stack.last_mut() { + *remaining -= 1; + if *remaining == 0 { + parent_stack.pop(); + } + } + + let raw_flags = chunk.flags[idx]; + let mut node_flags = NodeFlags(raw_flags); + let is_external = node_flags.has(NodeFlags::EXTERNAL_SHARD_REF); + node_flags.set(NodeFlags::EXTERNAL_SHARD_REF, false); + + cur_mtime = cur_mtime.saturating_add(chunk.mtime_deltas[idx]); + let alloc = chunk.allocated_bytes[idx]; + let apparent = if node_flags.kind().is_dir() { + 0 + } else { + let sum = + i128::from(alloc) + i128::from(chunk.apparent_deltas[idx]); + sum.max(0) as u64 + }; + + let is_file = node_flags.kind() == crate::types::NodeKind::File; + let is_dir = node_flags.kind().is_dir(); + + let id = NodeId::from_index(idx).ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidData, "node index overflow") + })?; + + let mut node = ArenaNode { + name: NameId(name_raw), + parent, + first_child: None, + next_sibling: None, + allocated_bytes: alloc, + apparent_bytes: apparent, + files: u64::from(is_file), + dirs: u32::from(is_dir), + flags: node_flags, + modified: cur_mtime, + scanned_at: if is_dir { chunk.scanned_at_unix } else { 0 }, + }; + if is_dir && chunk.scanned_at_unix > 0 { + node.set_status(SubtreeStatus::Fresh { + scanned_at: chunk.scanned_at_unix, + }); + } + nodes.push(node); + + if let Some(parent_id) = parent { + let p = parent_id.index(); + if let Some(prev) = last_child[p] { + nodes[prev.index()].next_sibling = Some(id); + } else { + nodes[p].first_child = Some(id); + } + last_child[p] = Some(id); + } + + if is_external { + let Some(&ext_dir_id) = chunk.external_dir_ids.get(ext_cursor) + else { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "missing external_dir_id for shard ref", + )); + }; + ext_cursor += 1; + external_links.push((id, ext_dir_id)); + } else { + let child_count = chunk.child_counts[idx]; + if child_count > 0 { + parent_stack.push((id, child_count)); + } + } + } + + if !parent_stack.is_empty() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "truncated children in subtree chunk", + )); + } + + let mut hardlinks = Vec::with_capacity(chunk.hardlink_node_idx.len()); + for ((&node_idx, &dev), &ino) in chunk + .hardlink_node_idx + .iter() + .zip(&chunk.hardlink_devs) + .zip(&chunk.hardlink_inos) + { + if (node_idx as usize) >= count { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "hardlink node index out of bounds", + )); + } + let node = NodeId::from_index(node_idx as usize).ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidData, "hardlink id overflow") + })?; + hardlinks.push(HardlinkEntry { node, dev, ino }); + } + + let arena = + TreeArena::from_parts(root_path, nodes, last_child, strings, hardlinks); + + Ok(DecodedChunk { + arena, + scanned_at: chunk.scanned_at_unix, + external_links, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::types::NodeKind; + + #[test] + fn subtree_chunk_roundtrips_columnar_data_and_hardlinks() { + let mut arena = TreeArena::new(PathBuf::from("/data"), "data"); + let sub = arena.add_child( + arena.root(), + "crates", + NodeKind::Directory, + 0, + 0, + 1_700_000_000, + NodeFlags::new(NodeKind::Directory), + ); + let f1 = arena.add_child( + sub, + "Cargo.toml", + NodeKind::File, + 4096, + 1234, + 1_700_000_100, + NodeFlags::new(NodeKind::File), + ); + let f2 = arena.add_child( + sub, + "Cargo.lock", + NodeKind::File, + 4096, + 1234, + 1_700_000_200, + NodeFlags::new(NodeKind::File), + ); + arena.record_hardlink(f1, 42, 777); + arena.record_hardlink(f2, 42, 777); + + let chunk = encode_subtree_chunk( + &arena, + arena.root(), + 1, + 10, + 1_700_001_000, + &FxHashMap::default(), + ); + let framed = encode_framed(&chunk); + let decoded_proto: SubtreeChunk = + decode_framed(&framed).expect("decode frame"); + let mut decoded = + decode_subtree_chunk(&decoded_proto, PathBuf::from("/data")) + .expect("decode chunk"); + decoded.arena.aggregate(true, true); + + assert_eq!(decoded.scanned_at, 1_700_001_000); + assert_eq!(decoded.arena.len(), 4); + assert_eq!( + decoded.arena.node(decoded.arena.root()).allocated_bytes, + 4096 + ); + assert_eq!( + decoded.arena.node(decoded.arena.root()).apparent_bytes, + 1234 + ); + assert_eq!(decoded.arena.node(decoded.arena.root()).files, 2); + assert_eq!(decoded.arena.hardlinks().len(), 2); + } + + #[test] + fn external_shard_refs_stop_traversal_and_decode_links() { + let mut arena = TreeArena::new(PathBuf::from("/root"), "root"); + let big = arena.add_child( + arena.root(), + "big", + NodeKind::Directory, + 0, + 0, + 100, + NodeFlags::new(NodeKind::Directory), + ); + let _inside = arena.add_child( + big, + "hidden_inside_shard.bin", + NodeKind::File, + 8192, + 8000, + 100, + NodeFlags::new(NodeKind::File), + ); + let _sibling = arena.add_child( + arena.root(), + "small.txt", + NodeKind::File, + 4096, + 12, + 100, + NodeFlags::new(NodeKind::File), + ); + + let mut ext = FxHashMap::default(); + ext.insert(big, 999); + + let chunk = + encode_subtree_chunk(&arena, arena.root(), 1, 1, 5000, &ext); + let decoded = decode_subtree_chunk(&chunk, PathBuf::from("/root")) + .expect("decode"); + // Only root, big (stub ref), and small.txt should be in this chunk. + assert_eq!(decoded.arena.len(), 3); + assert_eq!(decoded.external_links.len(), 1); + assert_eq!(decoded.external_links[0].1, 999); + assert_eq!(decoded.arena.name(decoded.external_links[0].0), "big"); + } +} diff --git a/crates/disktree-scanner/src/session.rs b/crates/disktree-scanner/src/session.rs new file mode 100644 index 0000000..2835088 --- /dev/null +++ b/crates/disktree-scanner/src/session.rs @@ -0,0 +1,1325 @@ +//! High-level [`Scanner`] and priority-interruptible SWR [`ScanSession`]. +//! +//! Coordinates the cache database, automatic fallback to in-memory/streaming, +//! stale-while-revalidate snapshots, fresh-subtree skipping, and two-lane +//! `Immediate` / `Background` priority preemption. + +use std::io; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{self, Receiver, Sender, TryRecvError}; +use std::sync::{Arc, Mutex, Weak}; +use std::thread; +use std::time::{Duration, Instant}; + +use rustc_hash::{FxHashMap, FxHashSet}; + +use crate::db::{CacheDb, InvalidateReport, normalize_path}; +use crate::mounts::default_cache_db_path; +use crate::stream::{StreamItem, stream_walk}; +use crate::tree::TreeArena; +use crate::types::{ + ActiveStorageMode, CachePolicy, CacheStats, FallbackReason, Freshness, + HostKey, Priority, ScanOptions, ScanStats, StorageMode, unix_now, +}; +use crate::walk::{ + DirStartHook, DirTallyHook, MapSkipOracle, PauseGate, ShardLoader, + SkipOracle, WalkConfig, WalkProgress, walk_parallel, +}; + +/// A tree snapshot emitted by a [`ScanSession`]. +#[derive(Clone, Debug)] +pub struct ScanSnapshot { + pub arena: Arc, + pub freshness: Freshness, + pub stats: ScanStats, + pub storage_mode: ActiveStorageMode, + pub fallback_reason: Option, +} + +/// Incremental events emitted by a [`ScanSession`]. +#[derive(Clone, Debug)] +pub enum ScanEvent { + /// Either an immediate cached (`Fresh`/`Stale`/`Partial`) snapshot or the + /// final `Live` snapshot once revalidation finishes. + Snapshot(ScanSnapshot), + /// A directory has started actively scanning (UI should show `Updating`). + SubtreeUpdating { path: PathBuf, priority: Priority }, + /// A targeted/prioritized subtree finished scanning and committed fresh + /// data; UI can splice and paint it `Fresh` immediately. + SubtreeRefreshed { + path: PathBuf, + arena: Arc, + scanned_at: u64, + priority: Priority, + }, + /// Periodic progress counters during a live walk. + Progress { + stats: ScanStats, + active_path: Option, + }, + /// Storage downgraded automatically (e.g. disk full or read-only). + StorageFallback { + from: ActiveStorageMode, + to: ActiveStorageMode, + reason: FallbackReason, + }, + /// Non-fatal scan error. + Error { message: String }, + /// Background revalidation completed (or cache hit needed no walk). + Finished, +} + +#[derive(Debug)] +struct RuntimeStorage { + db: Option>, + active_mode: ActiveStorageMode, + fallback_reason: Option, + /// In-memory cache used when running in `InMemory` mode (either requested + /// or after automatic fallback). + mem_cache: FxHashMap<(String, PathBuf), (Arc, u64, u32)>, +} + +/// Reusable scanner facade owning the cache DB handle and default policy. +#[derive(Clone, Debug)] +pub struct Scanner { + storage: Arc>, + default_policy: CachePolicy, +} + +impl Scanner { + /// Open a scanner with the default `StorageMode::Auto` and 15-minute TTL. + pub fn open_default() -> io::Result { + Self::new(StorageMode::Auto, CachePolicy::default()) + } + + /// Open a scanner with explicit [`StorageMode`] and [`CachePolicy`]. + pub fn new( + mode: StorageMode, + default_policy: CachePolicy, + ) -> io::Result { + let headroom = default_policy.min_free_headroom; + let runtime = match mode { + StorageMode::Auto => match default_cache_db_path() { + Some(path) => match CacheDb::open(path, headroom, false) { + Ok(db) => RuntimeStorage { + db: Some(Arc::new(db)), + active_mode: ActiveStorageMode::Persistent, + fallback_reason: None, + mem_cache: FxHashMap::default(), + }, + Err(reason) => RuntimeStorage { + db: None, + active_mode: ActiveStorageMode::InMemory, + fallback_reason: Some(reason), + mem_cache: FxHashMap::default(), + }, + }, + None => RuntimeStorage { + db: None, + active_mode: ActiveStorageMode::InMemory, + fallback_reason: Some( + FallbackReason::DatabaseUnavailable { + detail: "could not determine user cache directory" + .to_owned(), + }, + ), + mem_cache: FxHashMap::default(), + }, + }, + StorageMode::Persistent { path, strict } => { + match CacheDb::open(path, headroom, false) { + Ok(db) => RuntimeStorage { + db: Some(Arc::new(db)), + active_mode: ActiveStorageMode::Persistent, + fallback_reason: None, + mem_cache: FxHashMap::default(), + }, + Err(reason) if strict => { + return Err(io::Error::other(format!( + "failed to open cache DB in strict mode: {reason:?}" + ))); + } + Err(reason) => RuntimeStorage { + db: None, + active_mode: ActiveStorageMode::InMemory, + fallback_reason: Some(reason), + mem_cache: FxHashMap::default(), + }, + } + } + StorageMode::TempDb => match CacheDb::open_temp(headroom) { + Ok(db) => RuntimeStorage { + db: Some(Arc::new(db)), + active_mode: ActiveStorageMode::TempDb, + fallback_reason: None, + mem_cache: FxHashMap::default(), + }, + Err(reason) => RuntimeStorage { + db: None, + active_mode: ActiveStorageMode::InMemory, + fallback_reason: Some(reason), + mem_cache: FxHashMap::default(), + }, + }, + StorageMode::InMemory => RuntimeStorage { + db: None, + active_mode: ActiveStorageMode::InMemory, + fallback_reason: None, + mem_cache: FxHashMap::default(), + }, + StorageMode::Streaming => RuntimeStorage { + db: None, + active_mode: ActiveStorageMode::Streaming, + fallback_reason: None, + mem_cache: FxHashMap::default(), + }, + }; + + Ok(Self { + storage: Arc::new(Mutex::new(runtime)), + default_policy, + }) + } + + pub fn active_mode(&self) -> ActiveStorageMode { + self.storage + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .active_mode + } + + pub fn fallback_reason(&self) -> Option { + self.storage + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .fallback_reason + .clone() + } + + pub const fn default_policy(&self) -> &CachePolicy { + &self.default_policy + } + + /// Start an SWR [`ScanSession`] for local `root` using the scanner's + /// default [`CachePolicy`]. + pub fn open( + &self, + root: PathBuf, + options: ScanOptions, + ) -> io::Result { + self.open_with(HostKey::Local, root, options, self.default_policy) + } + + /// Start an SWR [`ScanSession`] with an explicit host namespace and policy. + pub fn open_with( + &self, + host: HostKey, + root: PathBuf, + options: ScanOptions, + policy: CachePolicy, + ) -> io::Result { + self.open_with_tally(host, root, options, policy, None) + } + + /// Start an SWR [`ScanSession`] with an optional per-directory tally hook + /// (for live treemap previews during cold walks). + pub fn open_with_tally( + &self, + host: HostKey, + root: PathBuf, + options: ScanOptions, + policy: CachePolicy, + on_dir_tally: Option, + ) -> io::Result { + let started = Instant::now(); + let canonical_root = root.canonicalize().unwrap_or(root); + let (event_tx, event_rx) = mpsc::channel(); + let (cmd_tx, cmd_rx) = mpsc::channel(); + let cancel = Arc::new(AtomicBool::new(false)); + let pause_gate = Arc::new(PauseGate::new()); + let progress = Arc::new(WalkProgress::default()); + let completed_immediate: Arc>> = + Arc::new(Mutex::new(FxHashMap::default())); + + let (db_opt, active_mode, fallback_reason) = { + let guard = self + .storage + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + ( + guard.db.clone(), + guard.active_mode, + guard.fallback_reason.clone(), + ) + }; + + // 1. Instant cache check (sub-10ms fast path). + let now = unix_now(); + let mut needs_walk = true; + if !policy.force_refresh && active_mode != ActiveStorageMode::Streaming + { + if let Some(cached) = self.try_load_cached( + db_opt.as_ref(), + &host, + &canonical_root, + &options, + now, + &policy, + &event_tx, + ) { + let root_node = cached.arena.node(cached.arena.root()); + let stats = ScanStats { + files: root_node.files, + dirs: u64::from(root_node.dirs), + allocated_bytes: root_node.allocated_bytes, + apparent_bytes: root_node.apparent_bytes, + errors: 0, + skipped_fresh_dirs: u64::from(root_node.dirs), + walked_dirs: 0, + duration_ms: started.elapsed().as_millis() as u64, + }; + let is_fresh = + matches!(cached.freshness, Freshness::Fresh { .. }); + + if is_fresh || policy.stale_while_revalidate { + let (cur_mode, cur_reason) = { + let guard = self + .storage + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + (guard.active_mode, guard.fallback_reason.clone()) + }; + let _ = event_tx.send(ScanEvent::Snapshot(ScanSnapshot { + arena: Arc::new(cached.arena), + freshness: cached.freshness, + stats, + storage_mode: cur_mode, + fallback_reason: cur_reason, + })); + } + + if is_fresh { + needs_walk = false; + let _ = event_tx.send(ScanEvent::Finished); + } + } + } else if let Some(reason) = fallback_reason { + // Surface initial fallback if caller opened in Auto and it already + // downgraded before the session began. + let _ = event_tx.send(ScanEvent::StorageFallback { + from: ActiveStorageMode::Persistent, + to: active_mode, + reason, + }); + } + + // 2. Spawn the immediate-priority command dispatcher (always available + // so `prioritize`/`revalidate` work both mid-scan and post-hit). + // Holds a weak storage ref so dropping the Scanner releases TempDb + // deterministically without racing the idle loop. + { + let storage = Arc::downgrade(&self.storage); + let host = host.clone(); + let cancel = Arc::clone(&cancel); + let pause_gate = Arc::clone(&pause_gate); + let completed_immediate = Arc::clone(&completed_immediate); + let event_tx = event_tx.clone(); + thread::Builder::new() + .name("disktree-priority".into()) + .spawn(move || { + run_priority_loop( + &cmd_rx, + &storage, + &host, + &options, + &cancel, + &pause_gate, + &completed_immediate, + &event_tx, + ); + })?; + } + + // 3. Spawn background revalidation walk if needed. + if needs_walk { + let storage = Arc::clone(&self.storage); + let host = host.clone(); + let walk_root = canonical_root.clone(); + let cancel = Arc::clone(&cancel); + let pause_gate = Arc::clone(&pause_gate); + let progress = Arc::clone(&progress); + let completed_immediate = Arc::clone(&completed_immediate); + + thread::Builder::new() + .name("disktree-bg-scan".into()) + .spawn(move || { + run_background_walk( + &storage, + &host, + &walk_root, + &options, + &policy, + &cancel, + &pause_gate, + &progress, + &completed_immediate, + on_dir_tally, + &event_tx, + ); + })?; + } + + Ok(ScanSession { + root: canonical_root, + host, + events: event_rx, + commands: cmd_tx, + cancel, + pause_gate, + progress, + storage: Arc::clone(&self.storage), + }) + } + + /// Blocking convenience query: returns the fresh snapshot (or immediate + /// stale snapshot if `accept_stale` is true and cached data exists). + pub fn scan_blocking( + &self, + root: &Path, + options: ScanOptions, + policy: CachePolicy, + accept_stale: bool, + ) -> io::Result { + let session = self.open_with( + HostKey::Local, + root.to_path_buf(), + options, + policy, + )?; + let mut latest: Option = None; + while let Ok(event) = session.recv() { + match event { + ScanEvent::Snapshot(snap) => { + if accept_stale + || matches!( + snap.freshness, + Freshness::Fresh { .. } | Freshness::Live { .. } + ) + { + session.cancel(); + return Ok(snap); + } + latest = Some(snap); + } + ScanEvent::Error { message } => { + if latest.is_none() { + return Err(io::Error::other(message)); + } + } + ScanEvent::Finished => break, + _ => {} + } + } + latest.ok_or_else(|| { + io::Error::other("scan completed without producing a snapshot") + }) + } + + /// Run a bounded-memory `O(depth)` streaming walk without retaining a tree + /// or touching the cache DB. + pub fn stream( + &self, + root: &Path, + options: &ScanOptions, + cancel: Option<&Arc>, + emit: F, + ) -> io::Result<()> + where + F: FnMut(StreamItem) -> io::Result<()>, + { + stream_walk(root, options, cancel, emit) + } + + /// Mark one or more paths dirty in the cache (e.g. after files were + /// deleted) so subsequent scans revalidate them immediately. + pub fn invalidate( + &self, + host: &HostKey, + paths: &[PathBuf], + ) -> io::Result { + let host_key = host.as_db_key(); + let db_opt = { + let mut guard = self + .storage + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + for path in paths { + let norm = PathBuf::from(normalize_path(path)); + guard.mem_cache.retain(|(h, cached_path), _| { + if h != &host_key { + return true; + } + !(cached_path.starts_with(&norm) + || norm.starts_with(cached_path)) + }); + } + guard.db.clone() + }; + + let Some(db) = db_opt else { + return Ok(InvalidateReport::default()); + }; + match db.invalidate(host, paths) { + Ok(report) => Ok(report), + Err(reason) => { + downgrade_storage(&self.storage, reason); + Ok(InvalidateReport::default()) + } + } + } + + /// Return diagnostic stats for the persistent/temp cache database. + pub fn cache_stats(&self) -> io::Result { + let db_opt = self + .storage + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .db + .clone(); + let Some(db) = db_opt else { + return Ok(CacheStats::default()); + }; + db.stats() + .map_err(|reason| io::Error::other(format!("{reason:?}"))) + } + + /// Clear all cached data from the DB and in-memory cache. + pub fn clear_cache(&self) -> io::Result<()> { + let db_opt = { + let mut guard = self + .storage + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + guard.mem_cache.clear(); + guard.db.clone() + }; + if let Some(db) = db_opt { + db.clear() + .map_err(|reason| io::Error::other(format!("{reason:?}")))?; + } + Ok(()) + } + + /// Prune cached chunks older than `max_age`. + pub fn prune_cache(&self, max_age: Duration) -> io::Result { + let db_opt = self + .storage + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .db + .clone(); + let Some(db) = db_opt else { + return Ok(0); + }; + db.prune_older_than(unix_now(), max_age.as_secs()) + .map_err(|reason| io::Error::other(format!("{reason:?}"))) + } + + #[allow(clippy::too_many_arguments, reason = "internal cache read helper")] + fn try_load_cached( + &self, + db_opt: Option<&Arc>, + host: &HostKey, + canonical_root: &Path, + options: &ScanOptions, + now: u64, + policy: &CachePolicy, + event_tx: &Sender, + ) -> Option { + if let Some(db) = db_opt { + match db.load_subtree(host, canonical_root, options, now, policy) { + Ok(found) => return found, + Err(reason) => { + let from = downgrade_storage(&self.storage, reason.clone()); + let _ = event_tx.send(ScanEvent::StorageFallback { + from, + to: ActiveStorageMode::InMemory, + reason, + }); + } + } + } + + // Fallback in-memory cache lookup. + let host_key = host.as_db_key(); + let entry = { + let guard = self + .storage + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + guard + .mem_cache + .get(&(host_key, canonical_root.to_path_buf())) + .cloned() + }; + let (arena, scanned_at, mask) = entry?; + if mask != options.cache_topology_mask() { + return None; + } + let mut cloned = (*arena).clone(); + cloned.aggregate(options.dedup_hardlinks, options.include_hidden); + cloned.sort_children(options.byte_metric()); + let ttl_secs = policy.ttl.as_secs(); + cloned.refresh_statuses(now, ttl_secs); + let freshness = if now.saturating_sub(scanned_at) <= ttl_secs { + Freshness::Fresh { + oldest_at: scanned_at, + newest_at: scanned_at, + } + } else { + Freshness::Stale { + oldest_at: scanned_at, + newest_at: scanned_at, + stale_dirs: cloned.node(cloned.root()).dirs, + } + }; + Some(crate::db::CachedSubtree { + arena: cloned, + freshness, + }) + } +} + +enum SessionCmd { + Revalidate { + paths: Vec, + priority: Priority, + }, +} + +/// Active handle to a running (or cache-served) scan session. +pub struct ScanSession { + root: PathBuf, + host: HostKey, + events: Receiver, + commands: Sender, + cancel: Arc, + pause_gate: Arc, + progress: Arc, + storage: Arc>, +} + +impl std::fmt::Debug for ScanSession { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ScanSession") + .field("root", &self.root) + .field("host", &self.host) + .finish_non_exhaustive() + } +} + +impl Drop for ScanSession { + fn drop(&mut self) { + self.cancel(); + } +} + +impl ScanSession { + pub fn root(&self) -> &Path { + &self.root + } + + /// Poll for the next [`ScanEvent`] without blocking (ideal for GUI/TUI + /// render loops). + pub fn try_recv(&self) -> Result { + self.events.try_recv() + } + + /// Wait for the next [`ScanEvent`]. + pub fn recv(&self) -> Result { + self.events.recv() + } + + /// Wait with a timeout for the next [`ScanEvent`]. + pub fn recv_timeout( + &self, + timeout: Duration, + ) -> Result { + self.events.recv_timeout(timeout) + } + + /// Live lock-free progress snapshot of any in-flight background walk. + pub fn progress_snapshot(&self, duration_ms: u64) -> ScanStats { + self.progress.snapshot(duration_ms) + } + + /// Shared atomic progress handle for live counters and error details. + pub fn progress(&self) -> Arc { + Arc::clone(&self.progress) + } + + /// Preempt background revalidation immediately to refresh `path` first, + /// then automatically resume background work right where it left off. + pub fn prioritize(&self, path: &Path) -> io::Result<()> { + self.revalidate(&[path.to_path_buf()], Priority::Immediate) + } + + /// Request targeted revalidation of specific subtrees regardless of TTL. + /// `Priority::Immediate` pauses background admission until these paths + /// complete, commits them fresh, and resumes background work afterwards. + pub fn revalidate( + &self, + paths: &[PathBuf], + priority: Priority, + ) -> io::Result<()> { + self.commands + .send(SessionCmd::Revalidate { + paths: paths.to_vec(), + priority, + }) + .map_err(|_| { + io::Error::other("priority dispatcher is no longer running") + }) + } + + /// Mark paths dirty in the cache immediately (e.g. right after deletion). + pub fn invalidate( + &self, + paths: &[PathBuf], + ) -> io::Result { + let host_key = self.host.as_db_key(); + let db_opt = { + let mut guard = self + .storage + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + for path in paths { + let norm = PathBuf::from(normalize_path(path)); + guard.mem_cache.retain(|(h, cached_path), _| { + if h != &host_key { + return true; + } + !(cached_path.starts_with(&norm) + || norm.starts_with(cached_path)) + }); + } + guard.db.clone() + }; + let Some(db) = db_opt else { + return Ok(InvalidateReport::default()); + }; + match db.invalidate(&self.host, paths) { + Ok(report) => Ok(report), + Err(reason) => { + downgrade_storage(&self.storage, reason); + Ok(InvalidateReport::default()) + } + } + } + + /// Cooperatively cancel in-flight background and immediate work. + pub fn cancel(&self) { + self.cancel.store(true, Ordering::Relaxed); + self.pause_gate.cancel(); + } +} + +#[allow(clippy::too_many_arguments, reason = "worker thread parameters")] +fn run_background_walk( + storage: &Arc>, + host: &HostKey, + walk_root: &Path, + options: &ScanOptions, + policy: &CachePolicy, + cancel: &Arc, + pause_gate: &Arc, + progress: &Arc, + completed_immediate: &Arc>>, + on_dir_tally: Option, + event_tx: &Sender, +) { + let now = unix_now(); + let ttl_secs = policy.ttl.as_secs(); + + let db_opt = storage + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .db + .clone(); + + // Preload fresh subtrees strictly beneath `walk_root` into a lock-free map. + let db_fresh = if policy.reuse_fresh_subtrees && !policy.force_refresh { + if let Some(db) = &db_opt { + match db.fresh_subtrees_below( + host, + walk_root, + options, + now, + ttl_secs, + &FxHashSet::default(), + ) { + Ok(map) => map, + Err(reason) => { + let from = downgrade_storage(storage, reason.clone()); + let _ = event_tx.send(ScanEvent::StorageFallback { + from, + to: ActiveStorageMode::InMemory, + reason, + }); + FxHashMap::default() + } + } + } else { + FxHashMap::default() + } + } else { + FxHashMap::default() + }; + + let loader: Option = db_opt.as_ref().map(|db| { + let db = Arc::clone(db); + let host = host.clone(); + let f: ShardLoader = Arc::new(move |dir_id: u64, path: &Path| { + db.load_shard_by_dir_id( + &host, + dir_id, + path.to_path_buf(), + now, + ttl_secs, + ) + .ok() + .flatten() + }); + f + }); + + let oracle: Arc = Arc::new(MapSkipOracle { + in_memory: Arc::clone(completed_immediate), + db_fresh, + loader, + }); + + // Notify progress ticker / directory updates lazily via hook. + let last_emit = Arc::new(Mutex::new(Instant::now())); + let hook_tx = event_tx.clone(); + let hook_progress = Arc::clone(progress); + let hook_started = Instant::now(); + let on_dir_start: DirStartHook = Arc::new(move |dir: &Path| { + if let Ok(mut last) = last_emit.try_lock() + && last.elapsed() >= Duration::from_millis(80) + { + *last = Instant::now(); + let _ = hook_tx.send(ScanEvent::Progress { + stats: hook_progress + .snapshot(hook_started.elapsed().as_millis() as u64), + active_path: Some(dir.to_path_buf()), + }); + } + }); + + let outcome = match walk_parallel( + walk_root, + WalkConfig { + options, + cancel: Arc::clone(cancel), + progress: Arc::clone(progress), + pause_gate: Some(Arc::clone(pause_gate)), + skip_oracle: Some(oracle), + on_dir_start: Some(on_dir_start), + on_dir_tally, + }, + ) { + Ok(outcome) => outcome, + Err(error) => { + let _ = event_tx.send(ScanEvent::Error { + message: error.to_string(), + }); + let _ = event_tx.send(ScanEvent::Finished); + return; + } + }; + + if outcome.cancelled { + let _ = event_tx.send(ScanEvent::Finished); + return; + } + + let arena = Arc::new(outcome.arena); + persist_arena(storage, host, &arena, options, outcome.scanned_at, event_tx); + + let (active_mode, fallback_reason) = { + let guard = storage + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + (guard.active_mode, guard.fallback_reason.clone()) + }; + + let _ = event_tx.send(ScanEvent::Snapshot(ScanSnapshot { + arena, + freshness: Freshness::Live { + scanned_at: outcome.scanned_at, + }, + stats: outcome.stats, + storage_mode: active_mode, + fallback_reason, + })); + let _ = event_tx.send(ScanEvent::Finished); +} + +#[allow(clippy::too_many_arguments, reason = "priority worker loop state")] +fn run_priority_loop( + cmd_rx: &Receiver, + storage: &Weak>, + host: &HostKey, + options: &ScanOptions, + cancel: &Arc, + pause_gate: &Arc, + completed_immediate: &Arc>>, + event_tx: &Sender, +) { + while let Ok(cmd) = cmd_rx.recv() { + if cancel.load(Ordering::Relaxed) { + break; + } + let Some(storage) = storage.upgrade() else { + break; + }; + let storage = &storage; + match cmd { + SessionCmd::Revalidate { paths, priority } => { + for raw_path in paths { + if cancel.load(Ordering::Relaxed) { + break; + } + let target = raw_path.canonicalize().unwrap_or(raw_path); + let preempted = priority == Priority::Immediate; + if preempted { + pause_gate.pause(); + } + + let _ = event_tx.send(ScanEvent::SubtreeUpdating { + path: target.clone(), + priority, + }); + + let sub_progress = Arc::new(WalkProgress::default()); + let walk_res = walk_parallel( + &target, + WalkConfig { + options, + cancel: Arc::clone(cancel), + progress: sub_progress, + pause_gate: None, + skip_oracle: None, + on_dir_start: None, + on_dir_tally: None, + }, + ); + + match walk_res { + Ok(outcome) if !outcome.cancelled => { + let arena = Arc::new(outcome.arena); + persist_arena( + storage, + host, + &arena, + options, + outcome.scanned_at, + event_tx, + ); + completed_immediate + .lock() + .unwrap_or_else( + std::sync::PoisonError::into_inner, + ) + .insert(target.clone(), (*arena).clone()); + + let _ = + event_tx.send(ScanEvent::SubtreeRefreshed { + path: target, + arena, + scanned_at: outcome.scanned_at, + priority, + }); + } + Ok(_) => {} + Err(err) => { + let _ = event_tx.send(ScanEvent::Error { + message: format!("{}: {err}", target.display()), + }); + } + } + + if preempted { + pause_gate.resume(); + } + } + } + } + } +} + +fn persist_arena( + storage: &Arc>, + host: &HostKey, + arena: &Arc, + options: &ScanOptions, + scanned_at: u64, + event_tx: &Sender, +) { + let db_opt = { + let mut guard = storage + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + guard.mem_cache.insert( + (host.as_db_key(), arena.root_path().to_path_buf()), + (Arc::clone(arena), scanned_at, options.cache_topology_mask()), + ); + guard.db.clone() + }; + + if let Some(db) = db_opt + && let Err(reason) = db.store_subtree(host, arena, options, scanned_at) + { + let from = downgrade_storage(storage, reason.clone()); + let _ = event_tx.send(ScanEvent::StorageFallback { + from, + to: ActiveStorageMode::InMemory, + reason, + }); + } +} + +fn downgrade_storage( + storage: &Arc>, + reason: FallbackReason, +) -> ActiveStorageMode { + let mut guard = storage + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let from = guard.active_mode; + guard.db = None; + guard.active_mode = ActiveStorageMode::InMemory; + guard.fallback_reason = Some(reason); + from +} + +#[cfg(all(test, feature = "cache-db"))] +mod tests { + use super::*; + use std::fs; + + #[test] + fn repeated_scan_hits_fresh_cache_and_partial_widen_skips_fresh_subtree() { + let temp = tempfile::tempdir().expect("tempdir"); + let db_path = temp.path().join("cache.redb"); + let tree_root = temp.path().join("fs"); + let sub_a = tree_root.join("a"); + let sub_b = tree_root.join("b"); + fs::create_dir_all(&sub_a).expect("mkdir a"); + fs::create_dir_all(&sub_b).expect("mkdir b"); + fs::write(sub_a.join("file_a.bin"), vec![1u8; 4096]).expect("write a"); + fs::write(sub_b.join("file_b.bin"), vec![2u8; 8192]).expect("write b"); + + let scanner = Scanner::new( + StorageMode::Persistent { + path: db_path, + strict: true, + }, + CachePolicy { + min_free_headroom: 0, + ..CachePolicy::default() + }, + ) + .expect("scanner"); + + // 1. Scan only `a` first. + let snap_a = scanner + .scan_blocking( + &sub_a, + ScanOptions::default(), + CachePolicy { + min_free_headroom: 0, + ..CachePolicy::default() + }, + false, + ) + .expect("scan a"); + assert!(matches!(snap_a.freshness, Freshness::Live { .. })); + assert_eq!(snap_a.stats.apparent_bytes, 4096); + + // 2. Re-scanning `a` within 15 minutes hits cache with 0 walked dirs. + let hit_a = scanner + .scan_blocking( + &sub_a, + ScanOptions::default(), + CachePolicy { + min_free_headroom: 0, + ..CachePolicy::default() + }, + false, + ) + .expect("hit a"); + assert!(matches!(hit_a.freshness, Freshness::Fresh { .. })); + assert_eq!(hit_a.stats.walked_dirs, 0); + assert_eq!(hit_a.stats.apparent_bytes, 4096); + + // 3. Widening to `tree_root` skips `a` (reused from cache) and only + // walks `tree_root` + `b`! + let wide = scanner + .scan_blocking( + &tree_root, + ScanOptions::default(), + CachePolicy { + min_free_headroom: 0, + ..CachePolicy::default() + }, + false, + ) + .expect("wide"); + assert!(matches!(wide.freshness, Freshness::Live { .. })); + assert_eq!(wide.stats.apparent_bytes, 4096 + 8192); + assert!( + wide.stats.skipped_fresh_dirs >= 1, + "expected `a` to be skipped from cache, stats: {:?}", + wide.stats + ); + } + + #[test] + fn stale_while_revalidate_emits_stale_first_then_fresh() { + let temp = tempfile::tempdir().expect("tempdir"); + let db_path = temp.path().join("swr.redb"); + let root = temp.path().join("data"); + fs::create_dir_all(&root).expect("mkdir"); + fs::write(root.join("v1.txt"), b"hello").expect("write"); + + let scanner = Scanner::new( + StorageMode::Persistent { + path: db_path, + strict: true, + }, + CachePolicy { + min_free_headroom: 0, + ..CachePolicy::default() + }, + ) + .expect("scanner"); + + // Warm cache. + let _ = scanner + .scan_blocking( + &root, + ScanOptions::default(), + CachePolicy { + min_free_headroom: 0, + ..CachePolicy::default() + }, + false, + ) + .expect("warm"); + + // Mutate disk after caching. + fs::write(root.join("v2.txt"), b"world!").expect("write v2"); + + // Sleep 1s and query with TTL = 0s so cached entry is strictly stale. + thread::sleep(Duration::from_secs(1)); + let session = scanner + .open_with( + HostKey::Local, + root, + ScanOptions::default(), + CachePolicy { + ttl: Duration::ZERO, + stale_while_revalidate: true, + reuse_fresh_subtrees: false, + min_free_headroom: 0, + ..CachePolicy::default() + }, + ) + .expect("open swr"); + + let mut snapshots = Vec::new(); + while let Ok(ev) = session.recv() { + match ev { + ScanEvent::Snapshot(snap) => snapshots.push(snap), + ScanEvent::Finished => break, + _ => {} + } + } + assert_eq!(snapshots.len(), 2, "expected stale then live snapshot"); + assert!(matches!(snapshots[0].freshness, Freshness::Stale { .. })); + assert_eq!(snapshots[0].stats.apparent_bytes, 5); + assert!(matches!(snapshots[1].freshness, Freshness::Live { .. })); + assert_eq!(snapshots[1].stats.apparent_bytes, 11); + } + + #[test] + fn targeted_prioritize_refreshes_subtree_and_emits_events() { + let temp = tempfile::tempdir().expect("tempdir"); + let db_path = temp.path().join("prio.redb"); + let root = temp.path().join("root"); + let focus = root.join("focus"); + fs::create_dir_all(&focus).expect("mkdir"); + fs::write(focus.join("a.bin"), vec![0u8; 100]).expect("write"); + + let scanner = Scanner::new( + StorageMode::Persistent { + path: db_path, + strict: true, + }, + CachePolicy { + min_free_headroom: 0, + ..CachePolicy::default() + }, + ) + .expect("scanner"); + + let _ = scanner + .scan_blocking( + &root, + ScanOptions::default(), + CachePolicy { + min_free_headroom: 0, + ..CachePolicy::default() + }, + false, + ) + .expect("warm"); + + // Add new file inside `focus` and request immediate prioritization. + fs::write(focus.join("b.bin"), vec![0u8; 250]).expect("write b"); + + let session = scanner.open(root, ScanOptions::default()).expect("open"); + // Drain initial fresh snapshot + finished. + let mut saw_initial = false; + while let Ok(ev) = session.recv_timeout(Duration::from_secs(2)) { + if matches!(ev, ScanEvent::Snapshot(_)) { + saw_initial = true; + } + if matches!(ev, ScanEvent::Finished) { + break; + } + } + assert!(saw_initial); + + session.prioritize(&focus).expect("prioritize"); + + let mut saw_updating = false; + let mut refreshed_bytes = None; + while let Ok(ev) = session.recv_timeout(Duration::from_secs(5)) { + match ev { + ScanEvent::SubtreeUpdating { priority, .. } => { + assert_eq!(priority, Priority::Immediate); + saw_updating = true; + } + ScanEvent::SubtreeRefreshed { + arena, priority, .. + } => { + assert_eq!(priority, Priority::Immediate); + refreshed_bytes = + Some(arena.node(arena.root()).apparent_bytes); + break; + } + _ => {} + } + } + assert!(saw_updating); + assert_eq!(refreshed_bytes, Some(350)); + } + + #[test] + fn automatic_fallback_when_disk_headroom_unmet_or_unwritable() { + let temp = tempfile::tempdir().expect("tempdir"); + let root = temp.path().join("data"); + fs::create_dir_all(&root).expect("mkdir"); + fs::write(root.join("x.txt"), b"ok").expect("write"); + + // 1. Trigger headroom fallback with impossible requirement. + let scanner = Scanner::new( + StorageMode::Persistent { + path: temp.path().join("too-tight.redb"), + strict: false, + }, + CachePolicy { + min_free_headroom: u64::MAX, + ..CachePolicy::default() + }, + ) + .expect("scanner falls back cleanly"); + assert_eq!(scanner.active_mode(), ActiveStorageMode::InMemory); + assert!(matches!( + scanner.fallback_reason(), + Some(FallbackReason::LowDiskSpace { .. }) + )); + + let snap = scanner + .scan_blocking( + &root, + ScanOptions::default(), + CachePolicy::default(), + false, + ) + .expect("scan succeeds in memory"); + assert_eq!(snap.storage_mode, ActiveStorageMode::InMemory); + assert_eq!(snap.stats.apparent_bytes, 2); + + // 2. Trigger unwritable path fallback (DB path inside a regular file). + let blocker = temp.path().join("not-a-dir"); + fs::write(&blocker, b"file").expect("write blocker"); + let scanner2 = Scanner::new( + StorageMode::Persistent { + path: blocker.join("cache.redb"), + strict: false, + }, + CachePolicy { + min_free_headroom: 0, + ..CachePolicy::default() + }, + ) + .expect("scanner2 falls back cleanly"); + assert_eq!(scanner2.active_mode(), ActiveStorageMode::InMemory); + assert!(scanner2.fallback_reason().is_some()); + } + + #[test] + fn invalidate_forces_fresh_rescan_of_deleted_files() { + let temp = tempfile::tempdir().expect("tempdir"); + let db_path = temp.path().join("inv.redb"); + let root = temp.path().join("root"); + let gone = root.join("gone"); + fs::create_dir_all(&gone).expect("mkdir"); + fs::write(gone.join("big.bin"), vec![9u8; 4096]).expect("write"); + + let policy = CachePolicy { + min_free_headroom: 0, + ..CachePolicy::default() + }; + let scanner = Scanner::new( + StorageMode::Persistent { + path: db_path, + strict: true, + }, + policy, + ) + .expect("scanner"); + + let first = scanner + .scan_blocking(&root, ScanOptions::default(), policy, false) + .expect("first"); + assert_eq!(first.stats.apparent_bytes, 4096); + + // Delete `gone` externally and call `invalidate`. + fs::remove_dir_all(&gone).expect("remove"); + scanner + .invalidate(&HostKey::Local, &[gone]) + .expect("invalidate"); + + // Next scan sees 0 bytes immediately (does not serve stale 4096). + let second = scanner + .scan_blocking(&root, ScanOptions::default(), policy, false) + .expect("second"); + assert_eq!(second.stats.apparent_bytes, 0); + } +} diff --git a/crates/disktree-scanner/src/stream.rs b/crates/disktree-scanner/src/stream.rs new file mode 100644 index 0000000..9054eda --- /dev/null +++ b/crates/disktree-scanner/src/stream.rs @@ -0,0 +1,435 @@ +//! Bounded-memory `O(depth)` streaming filesystem walker. +//! +//! Used by `StorageMode::Streaming` (e.g. `disktree-cli --stream --ndjson`, +//! constrained containers, and the `disktree-scan` SSH helper). Never retains +//! a full tree in memory and never touches the cache DB. + +use std::fs::{self, Metadata, ReadDir}; +use std::io; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +use rustc_hash::{FxHashMap, FxHashSet}; +use serde::{Deserialize, Serialize}; + +use crate::mounts::{never_scanned, strict_mount_boundaries_for}; +use crate::types::{NodeKind, ScanOptions}; + +/// Fine-grained options for [`stream_walk_with_config`]. +#[derive(Clone, Debug)] +pub struct StreamConfig { + /// Additional paths excluded before `stat`/`read_dir`. + pub excluded: FxHashSet, + /// Deduplicate hardlinks inside the walker. When `false`, hardlink + /// identities are emitted on each [`StreamItem::Entry`] without keeping + /// a per-file link table in memory (used by SSH `client_dedup`). + pub dedup_in_walker: bool, + /// Optional cap on the in-walker hardlink table before failing explicitly. + pub max_pending_links: Option, + /// Skip entries whose filename is not valid UTF-8 and mark the parent + /// directory with `read_error` (prevents lossy remote paths). + pub skip_lossy_names: bool, +} + +impl Default for StreamConfig { + fn default() -> Self { + Self { + excluded: FxHashSet::default(), + dedup_in_walker: true, + max_pending_links: None, + skip_lossy_names: false, + } + } +} + +/// One item yielded by [`stream_walk`]. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "event", rename_all = "snake_case")] +pub enum StreamItem { + /// Entering a directory (preorder). + EnterDir { + path: PathBuf, + name: String, + depth: usize, + read_error: bool, + }, + /// A leaf entry (file, symlink, or special node) inside the current dir. + Entry { + path: PathBuf, + name: String, + kind: NodeKind, + allocated_bytes: u64, + apparent_bytes: u64, + modified: i64, + hidden: bool, + lossy_name: bool, + hardlink: Option<(u64, u64)>, + }, + /// Leaving a directory after all of its children have been emitted + /// (postorder). + LeaveDir { + path: PathBuf, + name: String, + depth: usize, + read_error: bool, + direct_children: u64, + }, + /// A non-fatal error reading a path. + Error { path: PathBuf, message: String }, +} + +struct Frame { + path: PathBuf, + name: String, + entries: Option, + read_error: bool, + direct_children: u64, +} + +/// Walk `root` iteratively with `O(depth)` memory, passing every [`StreamItem`] +/// to `emit`. Returning `Err` from `emit` aborts the walk immediately. +pub fn stream_walk( + root: &Path, + options: &ScanOptions, + cancel: Option<&Arc>, + emit: F, +) -> io::Result<()> +where + F: FnMut(StreamItem) -> io::Result<()>, +{ + let mut excluded: FxHashSet = never_scanned(root); + if options.one_filesystem + && let Some(bounds) = strict_mount_boundaries_for(root) + { + excluded.extend(bounds); + } + let config = StreamConfig { + excluded, + ..StreamConfig::default() + }; + stream_walk_with_config(root, options, &config, cancel, emit) +} + +/// [`stream_walk`] with caller-supplied exclusions, hardlink policy, and +/// lossy-name handling (used by the headless SSH helper). +pub fn stream_walk_with_config( + root: &Path, + options: &ScanOptions, + config: &StreamConfig, + cancel: Option<&Arc>, + mut emit: F, +) -> io::Result<()> +where + F: FnMut(StreamItem) -> io::Result<()>, +{ + let root_meta = fs::metadata(root)?; + let root_dev = device_of(&root_meta); + let excluded = &config.excluded; + + let root_name = root.file_name().map_or_else( + || root.to_string_lossy().into_owned(), + |n| n.to_string_lossy().into_owned(), + ); + + let root_entries = fs::read_dir(root); + let root_err = root_entries.is_err(); + if let Err(err) = &root_entries { + emit(StreamItem::Error { + path: root.to_path_buf(), + message: err.to_string(), + })?; + } + emit(StreamItem::EnterDir { + path: root.to_path_buf(), + name: root_name.clone(), + depth: 0, + read_error: root_err, + })?; + + let mut frames = vec![Frame { + path: root.to_path_buf(), + name: root_name, + entries: root_entries.ok(), + read_error: root_err, + direct_children: 0, + }]; + let mut visited_dirs: FxHashSet<(u64, u64)> = FxHashSet::default(); + if let Some(id) = inode_of(&root_meta) { + visited_dirs.insert(id); + } + // Track remaining hardlink count for bounded-memory deduplication. + let mut seen_links: FxHashMap<(u64, u64), u64> = FxHashMap::default(); + + while !frames.is_empty() { + if cancel.is_some_and(|flag| flag.load(Ordering::Relaxed)) { + return Ok(()); + } + + let current_depth = frames.len(); + let frame = frames.last_mut().expect("non-empty frames"); + let next_entry = frame.entries.as_mut().and_then(Iterator::next); + let Some(entry_res) = next_entry else { + let done = frames.pop().expect("frame checked above"); + let depth = frames.len(); + emit(StreamItem::LeaveDir { + path: done.path, + name: done.name, + depth, + read_error: done.read_error, + direct_children: done.direct_children, + })?; + continue; + }; + + let entry = match entry_res { + Ok(entry) => entry, + Err(err) => { + frame.read_error = true; + emit(StreamItem::Error { + path: frame.path.clone(), + message: err.to_string(), + })?; + continue; + } + }; + + let raw_name = entry.file_name(); + let lossy_name = raw_name.to_str().is_none(); + if lossy_name && config.skip_lossy_names { + frame.read_error = true; + continue; + } + let name = raw_name.to_string_lossy().into_owned(); + let hidden = name.starts_with('.'); + if !options.include_hidden && hidden { + continue; + } + + let path = entry.path(); + if excluded.contains(&path) { + continue; + } + + let sym_meta = match fs::symlink_metadata(&path) { + Ok(m) => m, + Err(err) => { + frame.read_error = true; + emit(StreamItem::Error { + path, + message: err.to_string(), + })?; + continue; + } + }; + + let is_symlink = sym_meta.file_type().is_symlink(); + let meta = if is_symlink && options.follow_links { + match fs::metadata(&path) { + Ok(target) => target, + Err(err) => { + if err.kind() != io::ErrorKind::NotFound { + emit(StreamItem::Error { + path, + message: err.to_string(), + })?; + } + continue; + } + } + } else { + sym_meta + }; + + if options.one_filesystem && device_of(&meta) != root_dev { + continue; + } + + if meta.is_dir() { + if options.follow_links + && let Some(id) = inode_of(&meta) + && !visited_dirs.insert(id) + { + continue; + } + let next_depth = current_depth; + if options.max_depth.is_some_and(|limit| next_depth > limit) { + continue; + } + frame.direct_children += 1; + let sub_entries = fs::read_dir(&path); + let sub_err = sub_entries.is_err(); + if let Err(err) = &sub_entries { + emit(StreamItem::Error { + path: path.clone(), + message: err.to_string(), + })?; + } + emit(StreamItem::EnterDir { + path: path.clone(), + name: name.clone(), + depth: next_depth, + read_error: sub_err, + })?; + frames.push(Frame { + path, + name, + entries: sub_entries.ok(), + read_error: sub_err, + direct_children: 0, + }); + continue; + } + + let kind = if meta.file_type().is_symlink() { + NodeKind::Symlink + } else if meta.is_file() { + NodeKind::File + } else { + NodeKind::Other + }; + + let (mut alloc, mut apparent) = if kind == NodeKind::Other { + (0, 0) + } else { + measure_both(&meta) + }; + + let hardlink = if (options.follow_links || nlink_of(&meta) > 1) + && meta.is_file() + { + inode_of(&meta) + } else { + None + }; + + if options.dedup_hardlinks + && config.dedup_in_walker + && let Some(id) = hardlink + { + if let Some(remaining) = seen_links.get_mut(&id) { + alloc = 0; + apparent = 0; + *remaining = remaining.saturating_sub(1); + if *remaining == 0 { + seen_links.remove(&id); + } + } else { + if let Some(limit) = config.max_pending_links + && seen_links.len() >= limit + { + return Err(io::Error::other(format!( + "remote hardlink tracking limit reached at {}; scan a smaller root", + path.display() + ))); + } + let extra = nlink_of(&meta).saturating_sub(1).max(1); + seen_links.insert(id, extra); + } + } + + frame.direct_children += 1; + emit(StreamItem::Entry { + path, + name, + kind, + allocated_bytes: alloc, + apparent_bytes: apparent, + modified: modified_seconds(&meta), + hidden, + lossy_name, + hardlink, + })?; + } + + Ok(()) +} + +/// Measure `(allocated_bytes, apparent_bytes)` in a single `Metadata` pass. +#[cfg(unix)] +pub(crate) fn measure_both(meta: &Metadata) -> (u64, u64) { + use std::os::unix::fs::MetadataExt as _; + (meta.blocks().saturating_mul(512), meta.len()) +} + +#[cfg(not(unix))] +pub(crate) fn measure_both(meta: &Metadata) -> (u64, u64) { + let len = meta.len(); + (len, len) +} + +#[cfg(unix)] +pub(crate) fn device_of(meta: &Metadata) -> u64 { + use std::os::unix::fs::MetadataExt as _; + meta.dev() +} + +#[cfg(not(unix))] +pub(crate) const fn device_of(_meta: &Metadata) -> u64 { + 0 +} + +#[cfg(unix)] +pub(crate) fn inode_of(meta: &Metadata) -> Option<(u64, u64)> { + use std::os::unix::fs::MetadataExt as _; + let ino = meta.ino(); + (ino != 0).then(|| (meta.dev(), ino)) +} + +#[cfg(not(unix))] +pub(crate) const fn inode_of(_meta: &Metadata) -> Option<(u64, u64)> { + None +} + +#[cfg(unix)] +pub(crate) fn nlink_of(meta: &Metadata) -> u64 { + use std::os::unix::fs::MetadataExt as _; + meta.nlink() +} + +#[cfg(not(unix))] +pub(crate) const fn nlink_of(_meta: &Metadata) -> u64 { + 1 +} + +pub(crate) fn modified_seconds(meta: &Metadata) -> i64 { + meta.modified() + .ok() + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map_or(0, |d| d.as_secs().cast_signed()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn streaming_walk_dedups_hardlinks_and_emits_balanced_dirs() { + let dir = tempfile::tempdir().expect("tempdir"); + let a = dir.path().join("a.bin"); + fs::write(&a, vec![42u8; 8192]).expect("write"); + fs::hard_link(&a, dir.path().join("b.bin")).expect("hardlink"); + fs::create_dir(dir.path().join("sub")).expect("mkdir"); + fs::write(dir.path().join("sub/c.txt"), b"hello").expect("write"); + + let mut enters = 0usize; + let mut leaves = 0usize; + let mut total_apparent = 0u64; + stream_walk(dir.path(), &ScanOptions::default(), None, |item| { + match item { + StreamItem::EnterDir { .. } => enters += 1, + StreamItem::LeaveDir { .. } => leaves += 1, + StreamItem::Entry { apparent_bytes, .. } => { + total_apparent += apparent_bytes; + } + StreamItem::Error { .. } => {} + } + Ok(()) + }) + .expect("stream"); + + assert_eq!(enters, 2); + assert_eq!(leaves, 2); + assert_eq!(total_apparent, 8192 + 5); + } +} diff --git a/crates/disktree-scanner/src/strings.rs b/crates/disktree-scanner/src/strings.rs new file mode 100644 index 0000000..5ffa276 --- /dev/null +++ b/crates/disktree-scanner/src/strings.rs @@ -0,0 +1,363 @@ +//! Compact string interning (`StringPool`) and prefix-trie linearized +//! front-coding (`FrontCodedStrings`). +//! +//! Filesystems repeat basenames millions of times (`index.js`, `Cargo.toml`, +//! `.git`, `mod.rs`) and share long common prefixes. Interning into a single +//! contiguous buffer eliminates per-node heap allocations in RAM, and +//! front-coding the lexicographically sorted dictionary achieves prefix-trie +//! compression on disk with O(N) single-pass decoding. + +use std::hash::{BuildHasher as _, Hasher as _}; +use std::io; + +use rustc_hash::{FxBuildHasher, FxHashMap}; + +/// Dense 4-byte index into a [`StringPool`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct NameId(pub u32); + +impl NameId { + pub const fn index(self) -> usize { + self.0 as usize + } +} + +/// Contiguous, deduplicated string pool with zero per-string heap allocations. +/// +/// Strings live back-to-back in `data`; `offsets` has length `len() + 1`, so +/// entry `i` is `&data[offsets[i]..offsets[i + 1]]`. Lookup uses 64-bit `FxHash` +/// buckets without storing a second copy of any string. +#[derive(Clone, Debug)] +pub struct StringPool { + data: String, + offsets: Vec, + /// Primary hash -> first `NameId` with that hash. + index: FxHashMap, + /// Rare hash-collision overflow list. + collisions: Vec<(u64, NameId)>, +} + +impl Default for StringPool { + fn default() -> Self { + Self::new() + } +} + +impl StringPool { + pub fn new() -> Self { + Self { + data: String::new(), + offsets: vec![0], + index: FxHashMap::default(), + collisions: Vec::new(), + } + } + + pub fn with_capacity(strings: usize, bytes: usize) -> Self { + let mut offsets = Vec::with_capacity(strings + 1); + offsets.push(0); + Self { + data: String::with_capacity(bytes), + offsets, + index: FxHashMap::with_capacity_and_hasher(strings, FxBuildHasher), + collisions: Vec::new(), + } + } + + /// Number of unique interned strings. + pub const fn len(&self) -> usize { + self.offsets.len().saturating_sub(1) + } + + pub const fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Total UTF-8 bytes stored in the contiguous backing buffer. + pub const fn byte_len(&self) -> usize { + self.data.len() + } + + /// Intern `value`, returning its existing [`NameId`] or inserting it once. + pub fn intern(&mut self, value: &str) -> NameId { + let hash = Self::hash_str(value); + if let Some(&existing) = self.index.get(&hash) { + if self.get(existing) == value { + return existing; + } + for &(collision_hash, id) in &self.collisions { + if collision_hash == hash && self.get(id) == value { + return id; + } + } + let id = self.push_raw(value); + self.collisions.push((hash, id)); + return id; + } + let id = self.push_raw(value); + self.index.insert(hash, id); + id + } + + /// Append a string known to be unique. + fn push_raw(&mut self, value: &str) -> NameId { + let id = NameId(self.len() as u32); + self.data.push_str(value); + self.offsets.push(self.data.len() as u32); + id + } + + /// Look up the string for `id`. Returns `""` if out of bounds. + pub fn get(&self, id: NameId) -> &str { + let idx = id.index(); + let Some(&start) = self.offsets.get(idx) else { + return ""; + }; + let Some(&end) = self.offsets.get(idx + 1) else { + return ""; + }; + &self.data[start as usize..end as usize] + } + + /// Iterate over every interned string in ID order. + pub fn iter(&self) -> impl Iterator { + (0..self.len()).map(|idx| { + let id = NameId(idx as u32); + (id, self.get(id)) + }) + } + + /// Encode this pool as a lexicographically sorted, front-coded byte blob + /// (the linearized form of a prefix trie) and return `(encoded, remap)`, + /// where `remap[old_id] = new_sorted_id`. + pub fn encode_front_coded(&self) -> (Vec, Vec) { + let count = self.len(); + if count == 0 { + return (Vec::new(), Vec::new()); + } + + let mut order: Vec = (0..count as u32).collect(); + order.sort_unstable_by(|&a, &b| { + self.get(NameId(a)) + .as_bytes() + .cmp(self.get(NameId(b)).as_bytes()) + }); + + let mut remap = vec![NameId(0); count]; + let mut encoded = Vec::with_capacity(self.data.len() / 2 + count * 2); + let mut prev: &[u8] = &[]; + + for (new_idx, &old_idx) in order.iter().enumerate() { + remap[old_idx as usize] = NameId(new_idx as u32); + let current = self.get(NameId(old_idx)).as_bytes(); + let prefix_len = shared_prefix_len(prev, current); + let suffix = ¤t[prefix_len..]; + write_varint(prefix_len as u64, &mut encoded); + write_varint(suffix.len() as u64, &mut encoded); + encoded.extend_from_slice(suffix); + prev = current; + } + + (encoded, remap) + } + + /// Decode a front-coded dictionary produced by [`Self::encode_front_coded`] + /// in a single linear pass directly into a fresh [`StringPool`]. + pub fn decode_front_coded(count: u32, encoded: &[u8]) -> io::Result { + let count = count as usize; + if count == 0 { + return Ok(Self::new()); + } + + let mut pool = + Self::with_capacity(count, encoded.len().saturating_mul(2)); + let mut cursor = 0usize; + let mut prev_start = 0usize; + let mut prev_len = 0usize; + let mut prefix_scratch = Vec::new(); + + for _ in 0..count { + let prefix_len = read_varint(encoded, &mut cursor)? as usize; + let suffix_len = read_varint(encoded, &mut cursor)? as usize; + if prefix_len > prev_len { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "front-coded string prefix exceeds previous string", + )); + } + let suffix_end = + cursor.checked_add(suffix_len).ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "front-coded string length overflow", + ) + })?; + let suffix = encoded.get(cursor..suffix_end).ok_or_else(|| { + io::Error::new( + io::ErrorKind::UnexpectedEof, + "truncated front-coded string dictionary", + ) + })?; + cursor = suffix_end; + + let suffix_str = std::str::from_utf8(suffix).map_err(|error| { + io::Error::new(io::ErrorKind::InvalidData, error) + })?; + + let new_start = pool.data.len(); + if prefix_len > 0 { + let prefix_end = prev_start + prefix_len; + if !pool.data.is_char_boundary(prefix_end) { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "front-coded prefix splits a UTF-8 character", + )); + } + prefix_scratch.clear(); + prefix_scratch.extend_from_slice( + &pool.data.as_bytes()[prev_start..prefix_end], + ); + let prefix_str = + std::str::from_utf8(&prefix_scratch).map_err(|error| { + io::Error::new(io::ErrorKind::InvalidData, error) + })?; + pool.data.push_str(prefix_str); + } + pool.data.push_str(suffix_str); + + let new_len = pool.data.len() - new_start; + let id = NameId(pool.len() as u32); + pool.offsets.push(pool.data.len() as u32); + let hash = Self::hash_str(&pool.data[new_start..]); + if let std::collections::hash_map::Entry::Vacant(e) = + pool.index.entry(hash) + { + e.insert(id); + } else { + pool.collisions.push((hash, id)); + } + + prev_start = new_start; + prev_len = new_len; + } + + Ok(pool) + } + + fn hash_str(value: &str) -> u64 { + let mut hasher = FxBuildHasher.build_hasher(); + hasher.write(value.as_bytes()); + hasher.finish() + } +} + +/// Longest common prefix in valid UTF-8 characters (so front-coding never +/// splits a multi-byte UTF-8 sequence). +fn shared_prefix_len(a: &[u8], b: &[u8]) -> usize { + let mut len = a + .iter() + .zip(b.iter()) + .take_while(|(left, right)| left == right) + .count(); + while len > 0 && (a[len - 1] & 0b1100_0000) == 0b1000_0000 { + len -= 1; + } + if len > 0 && len < a.len() && (a[len] & 0b1100_0000) == 0b1000_0000 { + while len > 0 && (a[len - 1] & 0b1100_0000) == 0b1000_0000 { + len -= 1; + } + len = len.saturating_sub(1); + } + len +} + +fn write_varint(mut value: u64, out: &mut Vec) { + loop { + let byte = (value & 0x7F) as u8; + value >>= 7; + if value == 0 { + out.push(byte); + break; + } + out.push(byte | 0x80); + } +} + +fn read_varint(bytes: &[u8], cursor: &mut usize) -> io::Result { + let mut result = 0u64; + let mut shift = 0u32; + loop { + let Some(&byte) = bytes.get(*cursor) else { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "truncated varint in string dictionary", + )); + }; + *cursor += 1; + result |= u64::from(byte & 0x7F) << shift; + if byte & 0x80 == 0 { + return Ok(result); + } + shift += 7; + if shift >= 64 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "varint overflow in string dictionary", + )); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn interning_deduplicates_and_preserves_order() { + let mut pool = StringPool::new(); + let a = pool.intern("Cargo.toml"); + let b = pool.intern("src"); + let a2 = pool.intern("Cargo.toml"); + assert_eq!(a, a2); + assert_ne!(a, b); + assert_eq!(pool.len(), 2); + assert_eq!(pool.get(a), "Cargo.toml"); + assert_eq!(pool.get(b), "src"); + } + + #[test] + fn front_coding_roundtrips_and_compresses_shared_prefixes() { + let mut pool = StringPool::new(); + let names = [ + "libstdc++.so.6.0.33", + "libstdc++.so.6", + "libstdc++.so", + "libssl.so.3", + "libssl.a", + "Cargo.toml", + "Cargo.lock", + "café-élan", + "café-école", + "日本語-ファイル1", + "日本語-ファイル2", + ]; + let ids: Vec = names.iter().map(|n| pool.intern(n)).collect(); + + let (encoded, remap) = pool.encode_front_coded(); + assert!( + encoded.len() < pool.byte_len(), + "expected front-coding to save space: {} vs {}", + encoded.len(), + pool.byte_len() + ); + + let decoded = + StringPool::decode_front_coded(pool.len() as u32, &encoded) + .expect("decode"); + assert_eq!(decoded.len(), pool.len()); + for (name, old_id) in names.iter().zip(ids) { + let new_id = remap[old_id.index()]; + assert_eq!(decoded.get(new_id), *name); + } + } +} diff --git a/crates/disktree-scanner/src/tree.rs b/crates/disktree-scanner/src/tree.rs new file mode 100644 index 0000000..b083c2f --- /dev/null +++ b/crates/disktree-scanner/src/tree.rs @@ -0,0 +1,894 @@ +//! Compact arena-backed filesystem tree. +//! +//! Every node is a flat 64-byte [`ArenaNode`] stored in a contiguous `Vec`, +//! with zero per-node heap allocations: names live in [`StringPool`] and +//! multi-link hardlink identities live in a sparse side table (so single-link +//! files pay 0 bytes for inode tracking). + +use std::num::NonZeroU32; +use std::path::{Path, PathBuf}; + +use rustc_hash::FxHashSet; + +use crate::strings::{NameId, StringPool}; +use crate::types::{Metric, NodeKind, SubtreeStatus}; + +/// Dense 1-based node handle. Using `NonZeroU32` gives `Option` +/// niche optimization so every parent/child/sibling pointer is 4 bytes. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct NodeId(NonZeroU32); + +impl NodeId { + pub const ROOT: Self = Self(NonZeroU32::MIN); + + pub(crate) fn from_index(index: usize) -> Option { + let one_based = u32::try_from(index.checked_add(1)?).ok()?; + NonZeroU32::new(one_based).map(Self) + } + + pub const fn index(self) -> usize { + (self.0.get() - 1) as usize + } +} + +/// Bit-packed node flags (4 bytes). +/// +/// Layout: +/// - bits 0..2: `NodeKind` +/// - bit 2: `read_error` +/// - bit 3: `mount_boundary` +/// - bit 4: `lossy_name` (non-UTF-8 name replaced with U+FFFD) +/// - bit 5: `hidden` (leading dot or OS hidden attribute) +/// - bit 6: `has_hardlink` (present in `TreeArena::hardlinks`) +/// - bit 7: `external_shard_ref` (serialization marker for child shards) +/// - bits 8..10: `SubtreeStatus` tag +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct NodeFlags(pub u32); + +impl NodeFlags { + pub const READ_ERROR: u32 = 1 << 2; + pub const MOUNT_BOUNDARY: u32 = 1 << 3; + pub const LOSSY_NAME: u32 = 1 << 4; + pub const HIDDEN: u32 = 1 << 5; + pub const HAS_HARDLINK: u32 = 1 << 6; + pub const EXTERNAL_SHARD_REF: u32 = 1 << 7; + const STATUS_SHIFT: u32 = 8; + const STATUS_MASK: u32 = 0b11 << Self::STATUS_SHIFT; + /// Set by `aggregate()` on duplicate hardlink leaves so their bytes are + /// charged once without destroying their true file size across shard reloads. + pub const DEDUPED_LINK: u32 = 1 << 10; + + pub const fn new(kind: NodeKind) -> Self { + Self(kind.to_bits()) + } + + pub const fn kind(self) -> NodeKind { + NodeKind::from_bits(self.0) + } + + pub const fn set(&mut self, bit: u32, value: bool) { + if value { + self.0 |= bit; + } else { + self.0 &= !bit; + } + } + + pub const fn has(self, bit: u32) -> bool { + (self.0 & bit) != 0 + } + + pub const fn status_tag(self) -> u32 { + (self.0 & Self::STATUS_MASK) >> Self::STATUS_SHIFT + } + + pub const fn set_status_tag(&mut self, tag: u32) { + self.0 = (self.0 & !Self::STATUS_MASK) + | ((tag & 0b11) << Self::STATUS_SHIFT); + } + + /// Flags stripped of transient serialization/aggregation bits. + pub const fn persistent_bits(self) -> u32 { + self.0 + & !(Self::EXTERNAL_SHARD_REF + | Self::STATUS_MASK + | Self::DEDUPED_LINK) + } +} + +/// One filesystem entry in a [`TreeArena`]. +/// +/// Kept to a single 64-byte cache line with zero heap allocations per node. +/// Leaf `allocated_bytes` and `apparent_bytes` are the sole size inputs; +/// directory totals are derived by [`TreeArena::aggregate`]. +#[derive(Clone, Copy, Debug)] +pub struct ArenaNode { + pub name: NameId, + pub parent: Option, + pub first_child: Option, + pub next_sibling: Option, + pub allocated_bytes: u64, + pub apparent_bytes: u64, + pub files: u64, + pub dirs: u32, + pub flags: NodeFlags, + pub modified: i64, + pub scanned_at: u64, +} + +impl ArenaNode { + pub const fn is_dir(&self) -> bool { + self.flags.kind().is_dir() + } + + pub const fn kind(&self) -> NodeKind { + self.flags.kind() + } + + pub const fn read_error(&self) -> bool { + self.flags.has(NodeFlags::READ_ERROR) + } + + pub const fn lossy_name(&self) -> bool { + self.flags.has(NodeFlags::LOSSY_NAME) + } + + pub const fn hidden(&self) -> bool { + self.flags.has(NodeFlags::HIDDEN) + } + + pub const fn status(&self) -> SubtreeStatus { + SubtreeStatus::from_tag(self.flags.status_tag(), self.scanned_at) + } + + pub const fn set_status(&mut self, status: SubtreeStatus) { + self.flags.set_status_tag(status.tag()); + match status { + SubtreeStatus::Fresh { scanned_at } + | SubtreeStatus::Stale { scanned_at } => { + self.scanned_at = scanned_at; + } + SubtreeStatus::Updating { + previous_scanned_at, + } => { + self.scanned_at = match previous_scanned_at { + Some(ts) => ts, + None => 0, + }; + } + SubtreeStatus::Unscanned => { + self.scanned_at = 0; + } + } + } + + /// Allocated bytes charged to this node (0 for a deduplicated hardlink + /// leaf whose inode was already charged elsewhere). + pub const fn effective_allocated_bytes(&self) -> u64 { + if !self.is_dir() && self.flags.has(NodeFlags::DEDUPED_LINK) { + 0 + } else { + self.allocated_bytes + } + } + + /// Apparent bytes charged to this node (0 for a deduplicated hardlink leaf). + pub const fn effective_apparent_bytes(&self) -> u64 { + if !self.is_dir() && self.flags.has(NodeFlags::DEDUPED_LINK) { + 0 + } else { + self.apparent_bytes + } + } + + pub const fn value(&self, metric: Metric) -> u64 { + match metric { + Metric::Bytes => self.effective_allocated_bytes(), + Metric::ApparentBytes => self.effective_apparent_bytes(), + Metric::Files => self.files, + } + } +} + +/// Sparse hardlink record: only populated for files with `nlink > 1` (or +/// followed symlinks), so single-link files pay zero bytes. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct HardlinkEntry { + pub node: NodeId, + pub dev: u64, + pub ino: u64, +} + +/// Compact arena holding a scanned or cached filesystem subtree. +#[derive(Clone, Debug)] +pub struct TreeArena { + pub root_path: PathBuf, + nodes: Vec, + /// Tracks last child per node during construction for O(1) append. + last_child: Vec>, + strings: StringPool, + hardlinks: Vec, +} + +impl TreeArena { + /// Create a new arena with a single directory root node. + pub fn new(root_path: PathBuf, root_name: &str) -> Self { + let mut strings = StringPool::new(); + let name = strings.intern(root_name); + let root = ArenaNode { + name, + parent: None, + first_child: None, + next_sibling: None, + allocated_bytes: 0, + apparent_bytes: 0, + files: 0, + dirs: 1, + flags: NodeFlags::new(NodeKind::Directory), + modified: 0, + scanned_at: 0, + }; + Self { + root_path, + nodes: vec![root], + last_child: vec![None], + strings, + hardlinks: Vec::new(), + } + } + + /// Create an arena with pre-allocated capacity. + pub fn with_capacity( + root_path: PathBuf, + root_name: &str, + expected_nodes: usize, + ) -> Self { + let mut strings = + StringPool::with_capacity(expected_nodes / 2, expected_nodes * 8); + let name = strings.intern(root_name); + let mut nodes = Vec::with_capacity(expected_nodes.max(1)); + let mut last_child = Vec::with_capacity(expected_nodes.max(1)); + nodes.push(ArenaNode { + name, + parent: None, + first_child: None, + next_sibling: None, + allocated_bytes: 0, + apparent_bytes: 0, + files: 0, + dirs: 1, + flags: NodeFlags::new(NodeKind::Directory), + modified: 0, + scanned_at: 0, + }); + last_child.push(None); + Self { + root_path, + nodes, + last_child, + strings, + hardlinks: Vec::new(), + } + } + + /// Build directly from decoded parts (used by Protobuf chunk decoding). + pub(crate) const fn from_parts( + root_path: PathBuf, + nodes: Vec, + last_child: Vec>, + strings: StringPool, + hardlinks: Vec, + ) -> Self { + Self { + root_path, + nodes, + last_child, + strings, + hardlinks, + } + } + + pub const fn root(&self) -> NodeId { + NodeId::ROOT + } + + pub const fn len(&self) -> usize { + self.nodes.len() + } + + pub const fn is_empty(&self) -> bool { + self.nodes.is_empty() + } + + pub fn node(&self, id: NodeId) -> &ArenaNode { + &self.nodes[id.index()] + } + + pub fn node_mut(&mut self, id: NodeId) -> &mut ArenaNode { + &mut self.nodes[id.index()] + } + + pub fn nodes(&self) -> &[ArenaNode] { + &self.nodes + } + + pub const fn strings(&self) -> &StringPool { + &self.strings + } + + pub fn hardlinks(&self) -> &[HardlinkEntry] { + &self.hardlinks + } + + pub fn name(&self, id: NodeId) -> &str { + self.strings.get(self.nodes[id.index()].name) + } + + /// Add a child entry under `parent` and return its [`NodeId`]. + #[allow(clippy::too_many_arguments, reason = "flat leaf constructor")] + pub fn add_child( + &mut self, + parent: NodeId, + name: &str, + kind: NodeKind, + allocated_bytes: u64, + apparent_bytes: u64, + modified: i64, + flags: NodeFlags, + ) -> NodeId { + let name_id = self.strings.intern(name); + let id = NodeId::from_index(self.nodes.len()) + .expect("arena node count fits in u32"); + let is_file = kind == NodeKind::File; + let is_dir = kind == NodeKind::Directory; + self.nodes.push(ArenaNode { + name: name_id, + parent: Some(parent), + first_child: None, + next_sibling: None, + allocated_bytes, + apparent_bytes, + files: u64::from(is_file), + dirs: u32::from(is_dir), + flags, + modified, + scanned_at: 0, + }); + self.last_child.push(None); + self.link_child(parent, id); + id + } + + pub fn record_hardlink(&mut self, node: NodeId, dev: u64, ino: u64) { + self.nodes[node.index()] + .flags + .set(NodeFlags::HAS_HARDLINK, true); + self.hardlinks.push(HardlinkEntry { node, dev, ino }); + } + + pub(crate) fn link_child(&mut self, parent: NodeId, child: NodeId) { + let p = parent.index(); + if let Some(prev) = self.last_child[p] { + self.nodes[prev.index()].next_sibling = Some(child); + } else { + self.nodes[p].first_child = Some(child); + } + self.last_child[p] = Some(child); + } + + /// Iterate over direct children of `parent`. + pub fn children(&self, parent: NodeId) -> ChildrenIter<'_> { + ChildrenIter { + nodes: &self.nodes, + next: self.nodes[parent.index()].first_child, + } + } + + /// Graft an entire `child` arena under `parent`, renaming the grafted + /// root to `child_name` (if `Some`). Preserves hardlinks, flags, and + /// per-directory freshness timestamps. + pub fn graft_subtree( + &mut self, + parent: NodeId, + child: &Self, + child_name: Option<&str>, + ) -> NodeId { + let mut id_map = vec![NodeId::ROOT; child.nodes.len()]; + let mut stack = vec![(child.root(), parent, true)]; + let mut kids = Vec::new(); + + while let Some((src_id, dst_parent, is_graft_root)) = stack.pop() { + let src = child.node(src_id); + let name_str = if is_graft_root { + child_name.unwrap_or_else(|| child.name(src_id)) + } else { + child.name(src_id) + }; + let name_id = self.strings.intern(name_str); + let dst_id = NodeId::from_index(self.nodes.len()) + .expect("arena node count fits in u32"); + let mut copy = *src; + copy.name = name_id; + copy.parent = Some(dst_parent); + copy.first_child = None; + copy.next_sibling = None; + self.nodes.push(copy); + self.last_child.push(None); + self.link_child(dst_parent, dst_id); + id_map[src_id.index()] = dst_id; + + kids.clear(); + kids.extend(child.children(src_id)); + for &kid in kids.iter().rev() { + stack.push((kid, dst_id, false)); + } + } + + for link in &child.hardlinks { + let mapped = id_map[link.node.index()]; + self.hardlinks.push(HardlinkEntry { + node: mapped, + dev: link.dev, + ino: link.ino, + }); + } + + id_map[child.root().index()] + } + + /// Replace the children and metadata of an existing node `target` with + /// the contents of `replacement`. + pub fn replace_node_contents( + &mut self, + target: NodeId, + replacement: &Self, + ) { + let src_root = replacement.node(replacement.root()); + { + let dst = &mut self.nodes[target.index()]; + dst.first_child = None; + dst.allocated_bytes = src_root.allocated_bytes; + dst.apparent_bytes = src_root.apparent_bytes; + dst.files = src_root.files; + dst.dirs = src_root.dirs; + dst.flags = src_root.flags; + dst.modified = src_root.modified; + dst.scanned_at = src_root.scanned_at; + } + self.last_child[target.index()] = None; + + let mut id_map: Vec> = + vec![None; replacement.nodes.len()]; + id_map[replacement.root().index()] = Some(target); + + let mut stack: Vec<(NodeId, NodeId)> = replacement + .children(replacement.root()) + .collect::>() + .into_iter() + .rev() + .map(|kid| (kid, target)) + .collect(); + let mut kids = Vec::new(); + + while let Some((src_id, dst_parent)) = stack.pop() { + let src = replacement.node(src_id); + let name_id = self.strings.intern(replacement.name(src_id)); + let dst_id = NodeId::from_index(self.nodes.len()) + .expect("arena node count fits in u32"); + let mut copy = *src; + copy.name = name_id; + copy.parent = Some(dst_parent); + copy.first_child = None; + copy.next_sibling = None; + self.nodes.push(copy); + self.last_child.push(None); + self.link_child(dst_parent, dst_id); + id_map[src_id.index()] = Some(dst_id); + + kids.clear(); + kids.extend(replacement.children(src_id)); + for &kid in kids.iter().rev() { + stack.push((kid, dst_id)); + } + } + + for link in &replacement.hardlinks { + if let Some(mapped) = id_map[link.node.index()] { + self.hardlinks.push(HardlinkEntry { + node: mapped, + dev: link.dev, + ino: link.ino, + }); + } + } + } + + /// Extract the subtree rooted at `sub_root` into a standalone + /// [`TreeArena`]. + #[must_use] + pub fn extract_subtree(&self, sub_root: NodeId) -> Self { + let sub_path = self.path_of(sub_root); + let sub_name = self.name(sub_root); + let mut out = Self::new(sub_path, sub_name); + let src_root = self.node(sub_root); + out.nodes[0].allocated_bytes = src_root.allocated_bytes; + out.nodes[0].apparent_bytes = src_root.apparent_bytes; + out.nodes[0].files = src_root.files; + out.nodes[0].dirs = src_root.dirs; + out.nodes[0].flags = src_root.flags; + out.nodes[0].modified = src_root.modified; + out.nodes[0].scanned_at = src_root.scanned_at; + + let mut id_map: Vec> = vec![None; self.nodes.len()]; + id_map[sub_root.index()] = Some(out.root()); + + let mut stack: Vec<(NodeId, NodeId)> = self + .children(sub_root) + .collect::>() + .into_iter() + .rev() + .map(|kid| (kid, out.root())) + .collect(); + let mut kids = Vec::new(); + + while let Some((src_id, dst_parent)) = stack.pop() { + let src = self.node(src_id); + let name_id = out.strings.intern(self.name(src_id)); + let dst_id = NodeId::from_index(out.nodes.len()) + .expect("arena node count fits in u32"); + let mut copy = *src; + copy.name = name_id; + copy.parent = Some(dst_parent); + copy.first_child = None; + copy.next_sibling = None; + out.nodes.push(copy); + out.last_child.push(None); + out.link_child(dst_parent, dst_id); + id_map[src_id.index()] = Some(dst_id); + + kids.clear(); + kids.extend(self.children(src_id)); + for &kid in kids.iter().rev() { + stack.push((kid, dst_id)); + } + } + + for link in &self.hardlinks { + if let Some(mapped) = id_map[link.node.index()] { + out.hardlinks.push(HardlinkEntry { + node: mapped, + dev: link.dev, + ino: link.ino, + }); + } + } + + out + } + + /// Reconstruct the absolute path of `id` by walking parent pointers. + pub fn path_of(&self, id: NodeId) -> PathBuf { + let mut parts: Vec = Vec::new(); + let mut current = id; + while let Some(parent) = self.nodes[current.index()].parent { + parts.push(self.nodes[current.index()].name); + current = parent; + } + let mut path = self.root_path.clone(); + for name_id in parts.into_iter().rev() { + path.push(self.strings.get(name_id)); + } + path + } + + /// Locate a descendant by relative path components from the arena root. + pub fn find_relative<'a>( + &self, + components: impl IntoIterator, + ) -> Option { + let mut current = self.root(); + for component in components { + let next = self + .children(current) + .find(|&child| self.name(child) == component)?; + current = next; + } + Some(current) + } + + /// Derive every directory's `allocated_bytes`, `apparent_bytes`, `files`, + /// `dirs`, and `modified` bottom-up from leaf entries, deduplicating + /// hardlinks if requested, and optionally filtering hidden entries from + /// totals when `include_hidden` is false. + pub fn aggregate(&mut self, dedup_hardlinks: bool, include_hidden: bool) { + let mut order = Vec::with_capacity(self.nodes.len()); + let mut reachable = vec![false; self.nodes.len()]; + let mut stack = vec![self.root()]; + while let Some(id) = stack.pop() { + reachable[id.index()] = true; + order.push(id); + for child in self.children(id) { + stack.push(child); + } + } + + let mut duplicate_nodes = FxHashSet::default(); + if dedup_hardlinks && !self.hardlinks.is_empty() { + let mut seen = FxHashSet::with_capacity_and_hasher( + self.hardlinks.len(), + rustc_hash::FxBuildHasher, + ); + for link in &self.hardlinks { + if !reachable[link.node.index()] { + continue; + } + if !include_hidden && self.is_under_hidden(link.node) { + continue; + } + if !seen.insert((link.dev, link.ino)) { + duplicate_nodes.insert(link.node); + } + } + } + + for &id in order.iter().rev() { + if !self.nodes[id.index()].is_dir() { + let is_dup = duplicate_nodes.contains(&id); + self.nodes[id.index()] + .flags + .set(NodeFlags::DEDUPED_LINK, is_dup); + continue; + } + + let mut alloc = 0u64; + let mut apparent = 0u64; + let mut files = 0u64; + let mut dirs = 1u32; + let mut newest = self.nodes[id.index()].modified; + + let mut child_opt = self.nodes[id.index()].first_child; + while let Some(child_id) = child_opt { + let child = self.nodes[child_id.index()]; + child_opt = child.next_sibling; + if !include_hidden && child.hidden() { + continue; + } + alloc = alloc.saturating_add(child.effective_allocated_bytes()); + apparent = + apparent.saturating_add(child.effective_apparent_bytes()); + files = files.saturating_add(child.files); + dirs = dirs.saturating_add(child.dirs); + if child.modified > newest { + newest = child.modified; + } + } + + let node = &mut self.nodes[id.index()]; + node.allocated_bytes = alloc; + node.apparent_bytes = apparent; + node.files = files; + node.dirs = dirs; + node.modified = newest; + } + } + + /// Sort every directory's sibling chain descending by `metric` (tie-break + /// by name ascending for deterministic output). + pub fn sort_children(&mut self, metric: Metric) { + let mut kids = Vec::new(); + for idx in 0..self.nodes.len() { + if !self.nodes[idx].is_dir() { + continue; + } + let Some(first) = self.nodes[idx].first_child else { + continue; + }; + if self.nodes[first.index()].next_sibling.is_none() { + continue; + } + kids.clear(); + let mut cur = Some(first); + while let Some(kid) = cur { + kids.push(kid); + cur = self.nodes[kid.index()].next_sibling; + } + kids.sort_unstable_by(|&a, &b| { + let na = &self.nodes[a.index()]; + let nb = &self.nodes[b.index()]; + nb.value(metric).cmp(&na.value(metric)).then_with(|| { + self.strings.get(na.name).cmp(self.strings.get(nb.name)) + }) + }); + self.nodes[idx].first_child = kids.first().copied(); + self.last_child[idx] = kids.last().copied(); + for pair in kids.windows(2) { + self.nodes[pair[0].index()].next_sibling = Some(pair[1]); + } + if let Some(&last) = kids.last() { + self.nodes[last.index()].next_sibling = None; + } + } + } + + /// Apply a status tag to every directory in the arena based on `now` and + /// `ttl_secs`. + pub fn refresh_statuses(&mut self, now: u64, ttl_secs: u64) { + for node in &mut self.nodes { + if !node.is_dir() { + continue; + } + if node.scanned_at == 0 { + node.set_status(SubtreeStatus::Unscanned); + } else if now.saturating_sub(node.scanned_at) <= ttl_secs { + node.set_status(SubtreeStatus::Fresh { + scanned_at: node.scanned_at, + }); + } else { + node.set_status(SubtreeStatus::Stale { + scanned_at: node.scanned_at, + }); + } + } + } + + /// Count how many nodes live at or beneath every node in the arena. + #[cfg(feature = "cache-db")] + pub(crate) fn subtree_counts(&self) -> Vec { + let mut order = Vec::with_capacity(self.nodes.len()); + let mut stack = vec![self.root()]; + while let Some(id) = stack.pop() { + order.push(id); + for child in self.children(id) { + stack.push(child); + } + } + let mut counts = vec![1u32; self.nodes.len()]; + for &id in order.iter().rev() { + if let Some(parent) = self.nodes[id.index()].parent { + counts[parent.index()] = + counts[parent.index()].saturating_add(counts[id.index()]); + } + } + counts + } + + /// Direct leaf bytes inside `dir` (or this file's own bytes). + pub fn own_bytes(&self, id: NodeId, apparent: bool) -> u64 { + let node = self.node(id); + if !node.is_dir() { + return if apparent { + node.effective_apparent_bytes() + } else { + node.effective_allocated_bytes() + }; + } + self.children(id) + .filter(|&child| !self.node(child).is_dir()) + .fold(0u64, |sum, child| { + let c = self.node(child); + let val = if apparent { + c.effective_apparent_bytes() + } else { + c.effective_allocated_bytes() + }; + sum.saturating_add(val) + }) + } + + fn is_under_hidden(&self, mut id: NodeId) -> bool { + loop { + let node = self.nodes[id.index()]; + if node.parent.is_none() { + return false; + } + if node.hidden() { + return true; + } + let Some(parent) = node.parent else { + return false; + }; + id = parent; + } + } + + /// Canonicalized root path for this arena. + pub fn root_path(&self) -> &Path { + &self.root_path + } +} + +/// Zero-allocation iterator over a directory's direct children. +#[derive(Clone, Debug)] +pub struct ChildrenIter<'a> { + nodes: &'a [ArenaNode], + next: Option, +} + +impl Iterator for ChildrenIter<'_> { + type Item = NodeId; + + fn next(&mut self) -> Option { + let current = self.next?; + self.next = self.nodes[current.index()].next_sibling; + Some(current) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn arena_node_stays_compact() { + // Keep each node to a single 64-byte cache line. + assert_eq!(std::mem::size_of::(), 64); + } + + #[test] + fn aggregate_and_dedup_hardlinks_across_grafted_subtrees() { + let mut sub = TreeArena::new(PathBuf::from("/root/sub"), "sub"); + let f1 = sub.add_child( + sub.root(), + "shared.bin", + NodeKind::File, + 4096, + 100, + 10, + NodeFlags::new(NodeKind::File), + ); + sub.record_hardlink(f1, 1, 999); + sub.aggregate(true, true); + assert_eq!(sub.node(sub.root()).allocated_bytes, 4096); + + let mut root = TreeArena::new(PathBuf::from("/root"), "root"); + let f2 = root.add_child( + root.root(), + "alias.bin", + NodeKind::File, + 4096, + 100, + 20, + NodeFlags::new(NodeKind::File), + ); + root.record_hardlink(f2, 1, 999); + root.graft_subtree(root.root(), &sub, None); + + root.aggregate(true, true); + assert_eq!(root.node(root.root()).allocated_bytes, 4096); + assert_eq!(root.node(root.root()).apparent_bytes, 100); + assert_eq!(root.node(root.root()).files, 2); + assert_eq!(root.node(root.root()).dirs, 2); + } + + #[test] + fn extract_and_path_reconstruction_work() { + let mut arena = TreeArena::new(PathBuf::from("/home/tobi"), "tobi"); + let src = arena.add_child( + arena.root(), + "src", + NodeKind::Directory, + 0, + 0, + 0, + NodeFlags::new(NodeKind::Directory), + ); + let file = arena.add_child( + src, + "main.rs", + NodeKind::File, + 4096, + 250, + 123, + NodeFlags::new(NodeKind::File), + ); + assert_eq!( + arena.path_of(file), + PathBuf::from("/home/tobi/src/main.rs") + ); + + let extracted = arena.extract_subtree(src); + assert_eq!(extracted.root_path(), Path::new("/home/tobi/src")); + let found = extracted.find_relative(["main.rs"]).expect("found"); + assert_eq!(extracted.node(found).apparent_bytes, 250); + } +} diff --git a/crates/disktree-scanner/src/types.rs b/crates/disktree-scanner/src/types.rs new file mode 100644 index 0000000..240a8a3 --- /dev/null +++ b/crates/disktree-scanner/src/types.rs @@ -0,0 +1,442 @@ +//! Core configuration, status, freshness, and identity types for +//! `disktree-scanner`. + +use std::path::PathBuf; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use serde::{Deserialize, Serialize}; + +/// Default cache freshness window: 15 minutes. +pub const DEFAULT_CACHE_TTL: Duration = Duration::from_mins(15); + +/// Minimum available bytes required on the cache volume before opening or +/// growing the persistent cache database. +pub const DEFAULT_MIN_FREE_HEADROOM: u64 = 64 * 1024 * 1024; + +/// Default maximum cache database size before LRU eviction kicks in (256 MiB). +pub const DEFAULT_MAX_DB_BYTES: u64 = 256 * 1024 * 1024; + +/// What a node represents on disk. +#[derive( + Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, +)] +#[serde(rename_all = "snake_case")] +pub enum NodeKind { + #[default] + Directory, + File, + Symlink, + /// Sockets, fifos, and device nodes: addressable, zero space. + Other, +} + +impl NodeKind { + pub const fn is_dir(self) -> bool { + matches!(self, Self::Directory) + } + + pub const fn to_bits(self) -> u32 { + match self { + Self::Directory => 0, + Self::File => 1, + Self::Symlink => 2, + Self::Other => 3, + } + } + + pub const fn from_bits(bits: u32) -> Self { + match bits & 0b11 { + 0 => Self::Directory, + 1 => Self::File, + 2 => Self::Symlink, + _ => Self::Other, + } + } +} + +/// How children are ranked or weighted in queries and views. +#[derive( + Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, +)] +#[serde(rename_all = "snake_case")] +pub enum Metric { + /// Allocated disk space (`st_blocks * 512` / filesystem allocation). + #[default] + Bytes, + /// Logical file length (`st_size`). + ApparentBytes, + /// Total file count at or beneath the node. + Files, +} + +/// Scheduling priority for revalidation work. +#[derive( + Clone, + Copy, + Debug, + Default, + PartialEq, + Eq, + PartialOrd, + Ord, + Hash, + Serialize, + Deserialize, +)] +#[serde(rename_all = "snake_case")] +pub enum Priority { + /// Ongoing SWR refresh of the broader tree. + #[default] + Background, + /// User-focused folder (clicked tile / explicit `r` refresh): preempts + /// new background admissions until complete, then resumes background work. + Immediate, +} + +/// Per-directory freshness & active update status exposed to UIs and CLI. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(tag = "state", rename_all = "snake_case")] +pub enum SubtreeStatus { + /// Within TTL or just revalidated. + Fresh { scanned_at: u64 }, + /// Served from cache older than TTL; queued for revalidation. + Stale { scanned_at: u64 }, + /// Actively being scanned by workers right now. + Updating { previous_scanned_at: Option }, + /// Ancestor stub or unvisited directory. + Unscanned, +} + +impl SubtreeStatus { + pub const fn tag(self) -> u32 { + match self { + Self::Fresh { .. } => 0, + Self::Stale { .. } => 1, + Self::Updating { .. } => 2, + Self::Unscanned => 3, + } + } + + pub const fn from_tag(tag: u32, scanned_at: u64) -> Self { + match tag & 0b11 { + 0 => Self::Fresh { scanned_at }, + 1 => Self::Stale { scanned_at }, + 2 => Self::Updating { + previous_scanned_at: if scanned_at == 0 { + None + } else { + Some(scanned_at) + }, + }, + _ => Self::Unscanned, + } + } +} + +/// Whole-snapshot freshness summary. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "status", rename_all = "snake_case")] +pub enum Freshness { + /// Entire requested subtree came from fresh cache (<= TTL). + Fresh { oldest_at: u64, newest_at: u64 }, + /// Entire requested subtree came from cache, with some/all dirs older + /// than TTL. + Stale { + oldest_at: u64, + newest_at: u64, + stale_dirs: u32, + }, + /// Only part of the requested subtree was cached (e.g. widened from a + /// previously scanned child). + Partial { + cached_dirs: u32, + missing_dirs: u32, + oldest_at: Option, + newest_at: Option, + }, + /// Freshly completed live scan (all requested subtrees up to date). + Live { scanned_at: u64 }, +} + +/// How the scanner stores or streams scan data. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "mode", rename_all = "snake_case")] +pub enum StorageMode { + /// Use the default persistent cache DB; automatically fall back to + /// `InMemory` if the cache volume is unwritable, read-only, or low on + /// free space. + #[default] + Auto, + /// Use an explicit cache DB path; falls back to `InMemory` on I/O errors + /// unless `strict` is true. + Persistent { path: PathBuf, strict: bool }, + /// Create a temporary cache DB in the OS temp directory (cleaned up on + /// drop); falls back to `InMemory` on I/O errors. + TempDb, + /// Pure in-memory compact arena; never touches disk for caching. + InMemory, + /// Bounded-memory O(depth) streaming mode; never retains a full tree or + /// writes a cache DB. + Streaming, +} + +/// The effective storage mode in use after fallback resolution. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ActiveStorageMode { + Persistent, + TempDb, + InMemory, + Streaming, +} + +/// Why the scanner automatically downgraded from a disk-backed cache DB. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "reason", rename_all = "snake_case")] +pub enum FallbackReason { + /// Cache volume had less than the required free-space headroom. + LowDiskSpace { available: u64, required: u64 }, + /// Kernel returned `ENOSPC` / `StorageFull`. + DiskFull, + /// Cache directory lives on a read-only filesystem (`EROFS`). + ReadOnlyFilesystem, + /// Permission denied opening or creating the cache directory/file. + PermissionDenied, + /// Database backend unavailable, corrupt, or compiled without `cache-db`. + DatabaseUnavailable { detail: String }, +} + +/// Freshness and revalidation policy. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct CachePolicy { + /// Maximum age before a cached directory is considered stale (default 15m). + pub ttl: Duration, + /// Return stale/partial cached snapshots immediately while revalidating + /// in the background. + pub stale_while_revalidate: bool, + /// Optional upper bound past which cached entries are ignored even for SWR. + pub max_stale: Option, + /// During a walk, skip nested subtrees that are still fresh (<= TTL). + pub reuse_fresh_subtrees: bool, + /// Ignore fresh cache hits and force a live walk of the requested root + /// (still persists fresh results if storage is writable). + pub force_refresh: bool, + /// Minimum free bytes required on the cache volume before opening/writing + /// the cache DB (default 64 MiB). + pub min_free_headroom: u64, + /// Soft cap on cache DB size before LRU eviction (default 256 MiB). + pub max_db_bytes: u64, +} + +impl Default for CachePolicy { + fn default() -> Self { + Self { + ttl: DEFAULT_CACHE_TTL, + stale_while_revalidate: true, + max_stale: None, + reuse_fresh_subtrees: true, + force_refresh: false, + min_free_headroom: DEFAULT_MIN_FREE_HEADROOM, + max_db_bytes: DEFAULT_MAX_DB_BYTES, + } + } +} + +/// How a scan traverses and measures the filesystem. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ScanOptions { + /// Rank/report apparent size (`st_size`) instead of allocated blocks. + /// Both metrics are recorded during every walk so toggling this never + /// invalidates cached entries. + pub apparent_size: bool, + /// Follow symlinks. Off by default. + pub follow_links: bool, + /// Include dotfiles and hidden entries in returned views. Walks record + /// hidden entries with a flag so toggling this does not invalidate cache. + pub include_hidden: bool, + /// Stop at mount boundaries (including bind mounts and subvolumes). + pub one_filesystem: bool, + /// Optional maximum directory depth below the scan root. + pub max_depth: Option, + /// Deduplicate hardlinked files (`nlink > 1`) so bytes are counted once. + pub dedup_hardlinks: bool, + /// Optional explicit worker count; `None` uses available parallelism. + pub threads: Option, +} + +impl Default for ScanOptions { + fn default() -> Self { + Self { + apparent_size: false, + follow_links: false, + include_hidden: true, + one_filesystem: true, + max_depth: None, + dedup_hardlinks: true, + threads: None, + } + } +} + +impl ScanOptions { + /// Bitmask of traversal-shaping flags that affect what is stored in cache. + /// + /// `apparent_size`, `include_hidden`, and `dedup_hardlinks` are excluded + /// because both byte metrics, the hidden flag, and multi-link identities + /// are always stored and applied at query/aggregation time. + pub const fn cache_topology_mask(&self) -> u32 { + let mut mask = 0u32; + if self.follow_links { + mask |= 1 << 0; + } + if self.one_filesystem { + mask |= 1 << 1; + } + mask + } + + /// Preferred metric for sorting/display given `apparent_size`. + pub const fn byte_metric(&self) -> Metric { + if self.apparent_size { + Metric::ApparentBytes + } else { + Metric::Bytes + } + } +} + +/// Machine identity used to namespace cache entries so hosts are never mixed. +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct HostIdentity { + pub hostname: String, + pub machine_id: Option, +} + +impl HostIdentity { + /// Capture the local machine's identity, if readable. + pub fn current() -> Option { + let hostname = if cfg!(target_os = "linux") { + std::fs::read_to_string("/proc/sys/kernel/hostname").ok()? + } else { + String::from_utf8( + std::process::Command::new("hostname").output().ok()?.stdout, + ) + .ok()? + }; + let hostname = hostname.trim().to_owned(); + if hostname.is_empty() + || !hostname + .chars() + .all(|c| c.is_ascii_alphanumeric() || ".-_".contains(c)) + { + return None; + } + let machine_id = std::fs::read_to_string("/etc/machine-id") + .ok() + .map(|id| id.trim().to_owned()) + .filter(|id| { + id.len() == 32 && id.bytes().all(|c| c.is_ascii_hexdigit()) + }); + Some(Self { + hostname, + machine_id, + }) + } + + /// Canonical cache namespace key derived from host identity, never an + /// SSH alias. + pub fn cache_key(&self) -> String { + match &self.machine_id { + Some(id) => format!("remote:{}:{id}", self.hostname), + None => format!("remote:{}", self.hostname), + } + } +} + +/// Host namespace in the cache DB. +#[derive( + Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, +)] +pub enum HostKey { + #[default] + Local, + Remote(HostIdentity), +} + +impl HostKey { + pub fn as_db_key(&self) -> String { + match self { + Self::Local => "local".to_owned(), + Self::Remote(identity) => identity.cache_key(), + } + } +} + +/// Capacity of the volume a path lives on. +#[derive( + Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, +)] +pub struct SpaceInfo { + pub total: u64, + pub free: u64, + pub available: u64, +} + +impl SpaceInfo { + pub const fn used(&self) -> u64 { + self.total.saturating_sub(self.free) + } + + pub fn used_fraction(&self) -> f32 { + if self.total == 0 { + 0.0 + } else { + (self.used() as f64 / self.total as f64) as f32 + } + } + + /// Free space after `bytes` are removed, saturating at the volume size and + /// never counting the same byte twice. + #[must_use] + pub fn after_removing(&self, bytes: u64) -> Self { + let available = self.available.saturating_add(bytes).min(self.total); + let free = self.free.saturating_add(bytes).min(self.total); + Self { + total: self.total, + free, + available, + } + } +} + +/// Summary counters for a scan or cache query. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ScanStats { + pub files: u64, + pub dirs: u64, + pub allocated_bytes: u64, + pub apparent_bytes: u64, + pub errors: u64, + /// Number of directories reused directly from cache without walking disk. + pub skipped_fresh_dirs: u64, + /// Number of directories walked on disk. + pub walked_dirs: u64, + pub duration_ms: u64, +} + +/// Diagnostic stats for the cache database. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct CacheStats { + pub db_path: Option, + pub db_bytes: u64, + pub hosts: u64, + pub indexed_dirs: u64, + pub chunks: u64, +} + +/// Current Unix timestamp in seconds. +pub fn unix_now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |duration| duration.as_secs()) +} diff --git a/crates/disktree-scanner/src/walk.rs b/crates/disktree-scanner/src/walk.rs new file mode 100644 index 0000000..8987f09 --- /dev/null +++ b/crates/disktree-scanner/src/walk.rs @@ -0,0 +1,1098 @@ +//! Parallel Rayon filesystem walker with cache-skip grafting and +//! priority-interruptible pausing. +//! +//! Follows `disktree`'s core invariants: +//! - One `rayon::scope` per scan root so stack depth is O(1). +//! - `+1` completion sentinel on every directory so no directory is assembled +//! before both its direct scan and every child task finish (Invariant #3). +//! - Both `allocated_bytes` and `apparent_bytes` captured in a single metadata +//! pass (Invariant #1), and hidden entries flagged rather than dropped from +//! raw storage so `-a` and `-H` toggle instantly without rescanning. +//! - Lock-free `CacheSkipOracle` checks fresh subtrees before touching disk, +//! and `PauseGate` parks background workers cleanly whenever a user-focused +//! `Priority::Immediate` subtree preempts the refresh. + +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, Mutex}; +use std::time::Instant; + +use rayon::Scope; +use rustc_hash::{FxHashMap, FxHashSet}; + +use crate::mounts::{mount_boundaries_for, never_scanned}; +use crate::stream::{ + device_of, inode_of, measure_both, modified_seconds, nlink_of, +}; +use crate::tree::{NodeFlags, NodeId, TreeArena}; +use crate::types::{NodeKind, ScanOptions, ScanStats, SubtreeStatus, unix_now}; + +/// Callback invoked right as a directory begins walking. +pub type DirStartHook = Arc; + +/// Callback invoked once per walked directory with its direct file totals: +/// `(dir_path, allocated_bytes, apparent_bytes, files)`. +pub type DirTallyHook = Arc; + +/// Callback loading a cached shard by `dir_id` and path. +pub type ShardLoader = + Arc Option + Send + Sync>; + +/// Maximum number of per-path error strings retained on [`WalkProgress`]. +const MAX_ERROR_DETAIL: usize = 50; + +/// Cooperative pause gate that lets `Priority::Immediate` scans preempt +/// background directory workers cleanly between syscalls and resume them once +/// immediate work finishes. +#[derive(Debug, Default)] +pub struct PauseGate { + state: Mutex, + cv: Condvar, +} + +#[derive(Debug, Default)] +struct PauseState { + immediate_active: usize, + cancelled: bool, +} + +impl PauseGate { + pub fn new() -> Self { + Self::default() + } + + /// Pause background workers while an immediate subtree task runs. + pub fn pause(&self) { + let mut guard = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + guard.immediate_active += 1; + } + + /// Release one immediate hold; wakes background workers when count hits 0. + pub fn resume(&self) { + let mut guard = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + guard.immediate_active = guard.immediate_active.saturating_sub(1); + if guard.immediate_active == 0 { + self.cv.notify_all(); + } + } + + /// Mark cancelled and wake any parked workers immediately. + pub fn cancel(&self) { + { + let mut guard = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + guard.cancelled = true; + } + self.cv.notify_all(); + } + + /// Wait while any immediate task is active (returns early on cancellation). + pub fn wait_if_paused(&self, cancel: &AtomicBool) { + if cancel.load(Ordering::Relaxed) { + return; + } + let mut guard = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + while guard.immediate_active > 0 + && !guard.cancelled + && !cancel.load(Ordering::Relaxed) + { + guard = self + .cv + .wait(guard) + .unwrap_or_else(std::sync::PoisonError::into_inner); + } + drop(guard); + } +} + +/// Callback oracle consulted before entering a subdirectory to reuse an +/// already-fresh cached (or freshly prioritized) subtree without touching disk. +pub trait SkipOracle: Send + Sync { + /// If `path` is already fresh and compatible, return its ready + /// [`TreeArena`] to graft directly into the walk. + fn try_reuse(&self, path: &Path) -> Option; +} + +/// Live atomic counters published while a walk is in progress. +#[derive(Debug, Default)] +pub struct WalkProgress { + pub files: AtomicU64, + pub dirs: AtomicU64, + pub allocated_bytes: AtomicU64, + pub apparent_bytes: AtomicU64, + pub errors: AtomicU64, + pub skipped_fresh_dirs: AtomicU64, + pub walked_dirs: AtomicU64, + pub active_path: Mutex>, + pub messages: Mutex>, +} + +impl WalkProgress { + pub fn record_error(&self, path: &Path, error: &io::Error) { + self.errors.fetch_add(1, Ordering::Relaxed); + let mut messages = self + .messages + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if messages.len() < MAX_ERROR_DETAIL { + messages.push(format!("{}: {error}", path.display())); + } + drop(messages); + } + + pub fn messages(&self) -> Vec { + self.messages + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + } + + pub fn snapshot(&self, duration_ms: u64) -> ScanStats { + ScanStats { + files: self.files.load(Ordering::Relaxed), + dirs: self.dirs.load(Ordering::Relaxed), + allocated_bytes: self.allocated_bytes.load(Ordering::Relaxed), + apparent_bytes: self.apparent_bytes.load(Ordering::Relaxed), + errors: self.errors.load(Ordering::Relaxed), + skipped_fresh_dirs: self.skipped_fresh_dirs.load(Ordering::Relaxed), + walked_dirs: self.walked_dirs.load(Ordering::Relaxed), + duration_ms, + } + } +} + +/// Parameters controlling a single parallel walk. +pub struct WalkConfig<'a> { + pub options: &'a ScanOptions, + pub cancel: Arc, + pub progress: Arc, + pub pause_gate: Option>, + pub skip_oracle: Option>, + /// Optional hook invoked right as a directory begins walking (for live + /// `SubtreeStatus::Updating` indicators). + pub on_dir_start: Option, + /// Optional hook invoked after a directory's direct files are tallied (for + /// live treemap previews during cold scans). + pub on_dir_tally: Option, +} + +impl std::fmt::Debug for WalkConfig<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("WalkConfig") + .field("options", self.options) + .field("has_pause_gate", &self.pause_gate.is_some()) + .field("has_skip_oracle", &self.skip_oracle.is_some()) + .finish_non_exhaustive() + } +} + +/// Result of a completed parallel walk. +#[derive(Debug)] +pub struct WalkOutcome { + pub arena: TreeArena, + pub stats: ScanStats, + pub scanned_at: u64, + pub cancelled: bool, +} + +/// Walk `root` in parallel, grafting any fresh subtrees returned by +/// `config.skip_oracle`, and returning the aggregated, sorted [`TreeArena`]. +pub fn walk_parallel( + root: &Path, + config: WalkConfig<'_>, +) -> io::Result { + let started = Instant::now(); + let canonical_root = + root.canonicalize().unwrap_or_else(|_| root.to_path_buf()); + let root_meta = fs::metadata(&canonical_root)?; + if !root_meta.is_dir() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("{} is not a directory", root.display()), + )); + } + let root_dev = device_of(&root_meta); + + let never = never_scanned(&canonical_root); + let foreign_mounts = if config.options.one_filesystem { + mount_boundaries_for(&canonical_root) + } else { + None + }; + + let mut visited_dirs = FxHashSet::default(); + if let Some(id) = inode_of(&root_meta) { + visited_dirs.insert(id); + } + + let root_name = canonical_root.file_name().map_or_else( + || canonical_root.to_string_lossy().into_owned(), + |n| n.to_string_lossy().into_owned(), + ); + + #[cfg(windows)] + let volume = if !config.options.follow_links { + crate::windows::walk_volume(&canonical_root) + } else { + None + }; + + let ctx = Arc::new(WalkContext { + options: *config.options, + root_dev, + foreign_mounts, + never_scanned: never, + visited_dirs: Mutex::new(visited_dirs), + cancel: config.cancel, + progress: config.progress, + pause_gate: config.pause_gate, + skip_oracle: config.skip_oracle, + on_dir_start: config.on_dir_start, + on_dir_tally: config.on_dir_tally, + #[cfg(windows)] + volume, + finished_root: Mutex::new(None), + }); + + let root_pending = Arc::new(PendingDir::new( + root_name, + canonical_root.clone(), + None, + 0, + modified_seconds(&root_meta), + false, + false, + )); + + let run_walk = || -> io::Result<()> { + #[cfg(windows)] + if ctx.skip_oracle.is_none() { + if let Some(result) = crate::mft::scan( + root, + &canonical_root, + &ctx.options, + &ctx.cancel, + &ctx.progress, + ) { + let built = result?; + *ctx.finished_root + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = + Some(built); + return Ok(()); + } + } + rayon::scope(|scope| { + let ctx = Arc::clone(&ctx); + let root_pending = Arc::clone(&root_pending); + scope.spawn(move |s| { + scan_dir(s, &ctx, &root_pending); + }); + }); + Ok(()) + }; + + if let Some(threads) = config.options.threads { + let pool = rayon::ThreadPoolBuilder::new() + .num_threads(threads.max(1)) + .build() + .map_err(io::Error::other)?; + pool.install(run_walk)?; + } else { + run_walk()?; + } + + let scanned_at = unix_now(); + let cancelled = ctx.cancel.load(Ordering::Relaxed); + let built = ctx + .finished_root + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take() + .unwrap_or_else(|| BuiltNode::empty_dir(&canonical_root, "")); + + let mut arena = materialize_arena(canonical_root, built, scanned_at); + arena.aggregate( + config.options.dedup_hardlinks, + config.options.include_hidden, + ); + arena.sort_children(config.options.byte_metric()); + + let root_node = arena.node(arena.root()); + let mut stats = ctx.progress.snapshot(started.elapsed().as_millis() as u64); + stats.files = root_node.files; + stats.dirs = u64::from(root_node.dirs); + stats.allocated_bytes = root_node.allocated_bytes; + stats.apparent_bytes = root_node.apparent_bytes; + + Ok(WalkOutcome { + arena, + stats, + scanned_at, + cancelled, + }) +} + +struct WalkContext { + options: ScanOptions, + root_dev: u64, + foreign_mounts: Option>, + never_scanned: FxHashSet, + visited_dirs: Mutex>, + cancel: Arc, + progress: Arc, + pause_gate: Option>, + skip_oracle: Option>, + on_dir_start: Option, + on_dir_tally: Option, + #[cfg(windows)] + volume: Option, + finished_root: Mutex>, +} + +/// Intermediate directory accumulator using the `+1` completion sentinel +/// (Invariant #3): never built until its own listing AND every child task finish. +struct PendingDir { + name: String, + path: PathBuf, + parent: Option>, + depth: usize, + modified: i64, + hidden: bool, + lossy_name: bool, + read_error: AtomicBool, + /// Starts at `1` (the `+1` sentinel for this directory's own scan). + pending: AtomicUsize, + children: Mutex>, +} + +impl PendingDir { + const fn new( + name: String, + path: PathBuf, + parent: Option>, + depth: usize, + modified: i64, + hidden: bool, + lossy_name: bool, + ) -> Self { + Self { + name, + path, + parent, + depth, + modified, + hidden, + lossy_name, + read_error: AtomicBool::new(false), + pending: AtomicUsize::new(1), + children: Mutex::new(Vec::new()), + } + } +} + +pub(crate) enum BuiltChild { + Leaf(LeafRecord), + Dir(BuiltNode), + Grafted { + name: String, + arena: TreeArena, + hidden: bool, + lossy_name: bool, + }, +} + +pub(crate) struct LeafRecord { + pub name: String, + pub kind: NodeKind, + pub allocated_bytes: u64, + pub apparent_bytes: u64, + pub modified: i64, + pub hidden: bool, + pub lossy_name: bool, + pub hardlink: Option<(u64, u64)>, +} + +pub(crate) struct BuiltNode { + pub name: String, + pub modified: i64, + pub read_error: bool, + pub hidden: bool, + pub lossy_name: bool, + pub children: Vec, +} + +impl BuiltNode { + fn empty_dir(path: &Path, fallback_name: &str) -> Self { + let name = path.file_name().map_or_else( + || fallback_name.to_owned(), + |n| n.to_string_lossy().into_owned(), + ); + Self { + name, + modified: 0, + read_error: false, + hidden: false, + lossy_name: false, + children: Vec::new(), + } + } +} + +struct DirFacts { + device: u64, + modified: i64, + evicted: bool, + inode: Option<(u64, u64)>, +} + +struct LeafFacts { + allocated_bytes: u64, + apparent_bytes: u64, + modified: i64, + hardlink: Option<(u64, u64)>, +} + +trait Listed { + fn file_name_parts(&self) -> (String, bool); + fn entry_path(&self, dir: &Path) -> PathBuf; + fn is_hidden(&self, name: &str) -> bool { + name.starts_with('.') + } + fn kind(&self) -> io::Result; + fn dir_facts(&self) -> io::Result; + fn leaf_facts(&self, follow_links: bool) -> io::Result; +} + +#[cfg(not(any(target_os = "macos", windows)))] +impl Listed for fs::DirEntry { + fn file_name_parts(&self) -> (String, bool) { + let raw = self.file_name(); + let lossy = raw.to_str().is_none(); + (raw.to_string_lossy().into_owned(), lossy) + } + + fn entry_path(&self, _dir: &Path) -> PathBuf { + self.path() + } + + fn kind(&self) -> io::Result { + let ft = self.file_type()?; + Ok(if ft.is_symlink() { + NodeKind::Symlink + } else if ft.is_dir() { + NodeKind::Directory + } else if ft.is_file() { + NodeKind::File + } else { + NodeKind::Other + }) + } + + fn dir_facts(&self) -> io::Result { + let meta = self.metadata()?; + Ok(DirFacts { + device: device_of(&meta), + modified: modified_seconds(&meta), + evicted: false, + inode: inode_of(&meta), + }) + } + + fn leaf_facts(&self, follow_links: bool) -> io::Result { + let meta = self.metadata()?; + let (allocated_bytes, apparent_bytes) = measure_both(&meta); + let hardlink = if follow_links || nlink_of(&meta) > 1 { + inode_of(&meta) + } else { + None + }; + Ok(LeafFacts { + allocated_bytes, + apparent_bytes, + modified: modified_seconds(&meta), + hardlink, + }) + } +} + +#[cfg(target_os = "macos")] +impl Listed for crate::macos::Entry { + fn file_name_parts(&self) -> (String, bool) { + let lossy = self.file_name().to_str().is_none(); + (self.name().to_owned(), lossy) + } + + fn entry_path(&self, dir: &Path) -> PathBuf { + self.path(dir) + } + + fn kind(&self) -> io::Result { + Ok(match self.kind() { + crate::macos::Kind::Link => NodeKind::Symlink, + crate::macos::Kind::Directory => NodeKind::Directory, + crate::macos::Kind::File => NodeKind::File, + crate::macos::Kind::Other => NodeKind::Other, + }) + } + + fn dir_facts(&self) -> io::Result { + Ok(DirFacts { + device: self.device(), + modified: self.modified(), + evicted: self.evicted(), + inode: Some(self.identity()), + }) + } + + fn leaf_facts(&self, follow_links: bool) -> io::Result { + Ok(LeafFacts { + allocated_bytes: self.allocated(), + apparent_bytes: self.apparent(), + modified: self.modified(), + hardlink: (follow_links || self.shared()).then(|| self.identity()), + }) + } +} + +#[cfg(windows)] +impl Listed for crate::windows::Entry { + fn file_name_parts(&self) -> (String, bool) { + (self.name().to_owned(), false) + } + + fn entry_path(&self, dir: &Path) -> PathBuf { + self.path(dir) + } + + fn is_hidden(&self, name: &str) -> bool { + name.starts_with('.') || self.hidden() + } + + fn kind(&self) -> io::Result { + Ok(match self.kind() { + crate::windows::Kind::Link => NodeKind::Symlink, + crate::windows::Kind::Directory => NodeKind::Directory, + crate::windows::Kind::File => NodeKind::File, + }) + } + + fn dir_facts(&self) -> io::Result { + Ok(DirFacts { + device: 0, + modified: self.modified(), + evicted: self.evicted(), + inode: self.identity(), + }) + } + + fn leaf_facts(&self, _follow_links: bool) -> io::Result { + Ok(LeafFacts { + allocated_bytes: self.allocated(), + apparent_bytes: self.apparent(), + modified: self.modified(), + hardlink: self.identity(), + }) + } +} + +#[cfg(target_os = "macos")] +fn read_dir_entries( + path: &Path, + _ctx: &WalkContext, +) -> io::Result { + crate::macos::read_dir(path) +} + +#[cfg(windows)] +fn read_dir_entries( + path: &Path, + ctx: &WalkContext, +) -> io::Result { + crate::windows::read_dir(path, ctx.volume) +} + +#[cfg(not(any(target_os = "macos", windows)))] +fn read_dir_entries( + path: &Path, + _ctx: &WalkContext, +) -> io::Result { + fs::read_dir(path) +} + +fn scan_dir(scope: &Scope<'_>, ctx: &Arc, dir: &Arc) { + if let Some(gate) = &ctx.pause_gate { + gate.wait_if_paused(&ctx.cancel); + } + + if ctx.cancel.load(Ordering::Relaxed) { + complete_one(ctx, dir); + return; + } + + ctx.progress.walked_dirs.fetch_add(1, Ordering::Relaxed); + ctx.progress.dirs.fetch_add(1, Ordering::Relaxed); + if let Ok(mut active) = ctx.progress.active_path.try_lock() { + *active = Some(dir.path.clone()); + } + if let Some(hook) = &ctx.on_dir_start { + hook(&dir.path); + } + + let entries = match read_dir_entries(&dir.path, ctx) { + Ok(entries) => entries, + Err(error) => { + dir.read_error.store(true, Ordering::Relaxed); + ctx.progress.record_error(&dir.path, &error); + complete_one(ctx, dir); + return; + } + }; + + let mut local_children: Vec = Vec::new(); + let mut subdirs: Vec> = Vec::new(); + let mut local_files = 0u64; + let mut local_alloc = 0u64; + let mut local_apparent = 0u64; + + for entry_res in entries { + if ctx.cancel.load(Ordering::Relaxed) { + break; + } + let entry = match entry_res { + Ok(entry) => entry, + Err(error) => { + dir.read_error.store(true, Ordering::Relaxed); + ctx.progress.record_error(&dir.path, &error); + continue; + } + }; + + let (name, lossy_name) = entry.file_name_parts(); + let hidden = entry.is_hidden(&name); + let path = entry.entry_path(&dir.path); + + let Ok(kind) = entry.kind() else { + ctx.progress.errors.fetch_add(1, Ordering::Relaxed); + continue; + }; + + if kind == NodeKind::Symlink { + if !ctx.options.follow_links { + if let Ok(meta) = fs::symlink_metadata(&path) { + let (alloc, apparent) = measure_both(&meta); + local_alloc = local_alloc.saturating_add(alloc); + local_apparent = local_apparent.saturating_add(apparent); + local_children.push(BuiltChild::Leaf(LeafRecord { + name, + kind: NodeKind::Symlink, + allocated_bytes: alloc, + apparent_bytes: apparent, + modified: modified_seconds(&meta), + hidden, + lossy_name, + hardlink: None, + })); + } else { + ctx.progress.errors.fetch_add(1, Ordering::Relaxed); + } + continue; + } + + let Ok(meta) = fs::metadata(&path) else { + continue; + }; + if meta.is_dir() { + if ctx.never_scanned.contains(&path) { + continue; + } + if ctx.options.one_filesystem + && ctx + .foreign_mounts + .as_ref() + .is_some_and(|m| m.contains(&path)) + { + continue; + } + if ctx.options.one_filesystem + && ctx.foreign_mounts.is_none() + && device_of(&meta) != ctx.root_dev + { + continue; + } + if let Some(id) = inode_of(&meta) + && !ctx + .visited_dirs + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .insert(id) + { + continue; + } + if ctx + .options + .max_depth + .is_some_and(|limit| dir.depth + 1 > limit) + { + continue; + } + subdirs.push(Arc::new(PendingDir::new( + name, + path, + Some(Arc::clone(dir)), + dir.depth + 1, + modified_seconds(&meta), + hidden, + lossy_name, + ))); + continue; + } + + let (alloc, apparent) = measure_both(&meta); + local_files += u64::from(meta.is_file()); + local_alloc = local_alloc.saturating_add(alloc); + local_apparent = local_apparent.saturating_add(apparent); + local_children.push(BuiltChild::Leaf(LeafRecord { + name, + kind: if meta.is_file() { + NodeKind::File + } else { + NodeKind::Other + }, + allocated_bytes: alloc, + apparent_bytes: apparent, + modified: modified_seconds(&meta), + hidden, + lossy_name, + hardlink: inode_of(&meta), + })); + continue; + } + + if kind == NodeKind::Directory { + if ctx.never_scanned.contains(&path) { + continue; + } + if ctx.options.one_filesystem + && ctx + .foreign_mounts + .as_ref() + .is_some_and(|m| m.contains(&path)) + { + continue; + } + + // Consult the cache-skip oracle BEFORE reading directory metadata + // or opening the directory. + if let Some(oracle) = &ctx.skip_oracle + && let Some(reused) = oracle.try_reuse(&path) + { + let reused_root = reused.node(reused.root()); + ctx.progress + .skipped_fresh_dirs + .fetch_add(u64::from(reused_root.dirs), Ordering::Relaxed); + ctx.progress + .dirs + .fetch_add(u64::from(reused_root.dirs), Ordering::Relaxed); + ctx.progress + .files + .fetch_add(reused_root.files, Ordering::Relaxed); + ctx.progress + .allocated_bytes + .fetch_add(reused_root.allocated_bytes, Ordering::Relaxed); + ctx.progress + .apparent_bytes + .fetch_add(reused_root.apparent_bytes, Ordering::Relaxed); + if let Some(hook) = &ctx.on_dir_tally { + hook( + &path, + reused_root.allocated_bytes, + reused_root.apparent_bytes, + reused_root.files, + ); + } + local_children.push(BuiltChild::Grafted { + name, + arena: reused, + hidden, + lossy_name, + }); + continue; + } + + let Ok(facts) = entry.dir_facts() else { + ctx.progress.errors.fetch_add(1, Ordering::Relaxed); + continue; + }; + if facts.evicted { + continue; + } + if ctx.options.one_filesystem + && ctx.foreign_mounts.is_none() + && facts.device != ctx.root_dev + { + continue; + } + if ctx.options.follow_links + && let Some(id) = facts.inode + && !ctx + .visited_dirs + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .insert(id) + { + continue; + } + if ctx + .options + .max_depth + .is_some_and(|limit| dir.depth + 1 > limit) + { + continue; + } + subdirs.push(Arc::new(PendingDir::new( + name, + path, + Some(Arc::clone(dir)), + dir.depth + 1, + facts.modified, + hidden, + lossy_name, + ))); + continue; + } + + // Leaf file or special node. + let Ok(facts) = entry.leaf_facts(ctx.options.follow_links) else { + ctx.progress.errors.fetch_add(1, Ordering::Relaxed); + continue; + }; + let (alloc, apparent) = if kind == NodeKind::Other { + (0, 0) + } else { + (facts.allocated_bytes, facts.apparent_bytes) + }; + if kind == NodeKind::File { + local_files += 1; + } + local_alloc = local_alloc.saturating_add(alloc); + local_apparent = local_apparent.saturating_add(apparent); + local_children.push(BuiltChild::Leaf(LeafRecord { + name, + kind, + allocated_bytes: alloc, + apparent_bytes: apparent, + modified: facts.modified, + hidden, + lossy_name, + hardlink: (kind == NodeKind::File) + .then_some(facts.hardlink) + .flatten(), + })); + } + + if local_files > 0 || local_alloc > 0 || local_apparent > 0 { + ctx.progress.files.fetch_add(local_files, Ordering::Relaxed); + ctx.progress + .allocated_bytes + .fetch_add(local_alloc, Ordering::Relaxed); + ctx.progress + .apparent_bytes + .fetch_add(local_apparent, Ordering::Relaxed); + if let Some(hook) = &ctx.on_dir_tally { + hook(&dir.path, local_alloc, local_apparent, local_files); + } + } + + if !local_children.is_empty() { + dir.children + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .extend(local_children); + } + + // Add every subdirectory to `pending` BEFORE spawning so the `+1` sentinel + // guarantees `dir` cannot complete prematurely. + if !subdirs.is_empty() { + dir.pending.fetch_add(subdirs.len(), Ordering::AcqRel); + for sub in subdirs { + let ctx = Arc::clone(ctx); + scope.spawn(move |s| { + scan_dir(s, &ctx, &sub); + }); + } + } + + // Release this directory's own `+1` sentinel. + complete_one(ctx, dir); +} + +fn complete_one(ctx: &WalkContext, start: &Arc) { + let mut current = Arc::clone(start); + loop { + if current.pending.fetch_sub(1, Ordering::AcqRel) != 1 { + return; + } + let children = std::mem::take( + &mut *current + .children + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner), + ); + let built = BuiltNode { + name: current.name.clone(), + modified: current.modified, + read_error: current.read_error.load(Ordering::Relaxed), + hidden: current.hidden, + lossy_name: current.lossy_name, + children, + }; + if let Some(parent) = current.parent.as_ref().map(Arc::clone) { + parent + .children + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .push(BuiltChild::Dir(built)); + current = parent; + } else { + *ctx.finished_root + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = + Some(built); + return; + } + } +} + +/// Convert the completed parallel tree into a flat [`TreeArena`] in one +/// iterative pass. +fn materialize_arena( + root_path: PathBuf, + root: BuiltNode, + scanned_at: u64, +) -> TreeArena { + let mut arena = TreeArena::new(root_path, &root.name); + { + let r = arena.node_mut(arena.root()); + r.modified = root.modified; + r.flags.set(NodeFlags::READ_ERROR, root.read_error); + r.flags.set(NodeFlags::HIDDEN, root.hidden); + r.flags.set(NodeFlags::LOSSY_NAME, root.lossy_name); + r.set_status(SubtreeStatus::Fresh { scanned_at }); + } + + let mut stack: Vec<(NodeId, Vec)> = + vec![(arena.root(), root.children)]; + + while let Some((parent_id, children)) = stack.pop() { + for child in children { + match child { + BuiltChild::Leaf(leaf) => { + let mut flags = NodeFlags::new(leaf.kind); + flags.set(NodeFlags::HIDDEN, leaf.hidden); + flags.set(NodeFlags::LOSSY_NAME, leaf.lossy_name); + let id = arena.add_child( + parent_id, + &leaf.name, + leaf.kind, + leaf.allocated_bytes, + leaf.apparent_bytes, + leaf.modified, + flags, + ); + if let Some((dev, ino)) = leaf.hardlink { + arena.record_hardlink(id, dev, ino); + } + } + BuiltChild::Dir(dir) => { + let mut flags = NodeFlags::new(NodeKind::Directory); + flags.set(NodeFlags::READ_ERROR, dir.read_error); + flags.set(NodeFlags::HIDDEN, dir.hidden); + flags.set(NodeFlags::LOSSY_NAME, dir.lossy_name); + let id = arena.add_child( + parent_id, + &dir.name, + NodeKind::Directory, + 0, + 0, + dir.modified, + flags, + ); + arena + .node_mut(id) + .set_status(SubtreeStatus::Fresh { scanned_at }); + if !dir.children.is_empty() { + stack.push((id, dir.children)); + } + } + BuiltChild::Grafted { + name, + arena: sub_arena, + hidden, + lossy_name, + } => { + let grafted_id = + arena.graft_subtree(parent_id, &sub_arena, Some(&name)); + let node = arena.node_mut(grafted_id); + node.flags.set(NodeFlags::HIDDEN, hidden); + node.flags.set(NodeFlags::LOSSY_NAME, lossy_name); + } + } + } + } + + arena +} + +/// Simple map-backed [`SkipOracle`] combining fresh DB shards and recently +/// completed immediate priority revalidations. +pub struct MapSkipOracle { + /// Already-materialized subtrees (e.g. finished `Priority::Immediate` + /// scans that the resumed background scan must not re-walk). + pub in_memory: Arc>>, + /// Fresh DB shard `dir_id`s preloaded before the walk began. + pub db_fresh: FxHashMap, + /// Loader callback for `db_fresh` hits. + pub loader: Option, +} + +impl std::fmt::Debug for MapSkipOracle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("MapSkipOracle") + .field("db_fresh_len", &self.db_fresh.len()) + .field("has_loader", &self.loader.is_some()) + .finish_non_exhaustive() + } +} + +impl SkipOracle for MapSkipOracle { + fn try_reuse(&self, path: &Path) -> Option { + if let Some(arena) = self + .in_memory + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .get(path) + { + return Some(arena.clone()); + } + if let Some(&dir_id) = self.db_fresh.get(path) + && let Some(loader) = &self.loader + { + return loader(dir_id, path); + } + None + } +} diff --git a/crates/disktree-core/src/windows.rs b/crates/disktree-scanner/src/windows.rs similarity index 99% rename from crates/disktree-core/src/windows.rs rename to crates/disktree-scanner/src/windows.rs index 53b8564..daced99 100644 --- a/crates/disktree-core/src/windows.rs +++ b/crates/disktree-scanner/src/windows.rs @@ -40,7 +40,7 @@ use windows_sys::Win32::Storage::FileSystem::{ GetVolumePathNamesForVolumeNameW, SYNCHRONIZE, }; -use crate::space::SpaceInfo; +use crate::types::SpaceInfo; /// Bytes the file system fills per call: some hundreds of entries. const BUFFER_BYTES: usize = 64 * 1024; diff --git a/crates/disktree-scanner/tests/integration.rs b/crates/disktree-scanner/tests/integration.rs new file mode 100644 index 0000000..1a20666 --- /dev/null +++ b/crates/disktree-scanner/tests/integration.rs @@ -0,0 +1,406 @@ +//! Integration tests for `disktree-scanner`: caching, SWR, zero-rescan flag +//! toggles, cross-shard hardlinks, host isolation, space efficiency, priority +//! preemption, and automatic storage fallback. + +#![cfg(feature = "cache-db")] + +use std::fs; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::thread; +use std::time::Duration; + +use disktree_scanner::{ + ActiveStorageMode, CachePolicy, Freshness, HostIdentity, HostKey, + PauseGate, ScanOptions, Scanner, StorageMode, +}; + +fn zero_headroom_policy() -> CachePolicy { + CachePolicy { + min_free_headroom: 0, + ..CachePolicy::default() + } +} + +#[test] +fn toggling_apparent_size_and_hidden_hits_same_cache_without_rescan() { + let temp = tempfile::tempdir().expect("tempdir"); + let db_path = temp.path().join("toggle.redb"); + let root = temp.path().join("tree"); + fs::create_dir_all(&root).expect("mkdir"); + fs::write(root.join("visible.txt"), vec![1u8; 500]).expect("write"); + fs::write(root.join(".secret.txt"), vec![2u8; 300]).expect("write hidden"); + + let scanner = Scanner::new( + StorageMode::Persistent { + path: db_path, + strict: true, + }, + zero_headroom_policy(), + ) + .expect("scanner"); + + // Initial scan: allocated bytes, include_hidden = true. + let initial = scanner + .scan_blocking( + &root, + ScanOptions::default(), + zero_headroom_policy(), + false, + ) + .expect("initial"); + assert!(matches!(initial.freshness, Freshness::Live { .. })); + assert_eq!(initial.stats.apparent_bytes, 800); + assert_eq!(initial.stats.files, 2); + + // Toggle apparent_size = true -> instant fresh cache hit, 0 walked dirs. + let apparent = scanner + .scan_blocking( + &root, + ScanOptions { + apparent_size: true, + ..ScanOptions::default() + }, + zero_headroom_policy(), + false, + ) + .expect("apparent"); + assert!(matches!(apparent.freshness, Freshness::Fresh { .. })); + assert_eq!(apparent.stats.walked_dirs, 0); + assert_eq!(apparent.stats.apparent_bytes, 800); + + // Toggle include_hidden = false -> instant fresh cache hit, 0 walked dirs, + // and `.secret.txt` is filtered out of aggregated totals! + let no_hidden = scanner + .scan_blocking( + &root, + ScanOptions { + include_hidden: false, + ..ScanOptions::default() + }, + zero_headroom_policy(), + false, + ) + .expect("no_hidden"); + assert!(matches!(no_hidden.freshness, Freshness::Fresh { .. })); + assert_eq!(no_hidden.stats.walked_dirs, 0); + assert_eq!(no_hidden.stats.apparent_bytes, 500); + assert_eq!(no_hidden.stats.files, 1); +} + +#[test] +fn cross_shard_hardlinks_dedup_when_one_subtree_is_reused_from_cache() { + let temp = tempfile::tempdir().expect("tempdir"); + let db_path = temp.path().join("hl.redb"); + let root = temp.path().join("root"); + let dir_a = root.join("a"); + let dir_b = root.join("b"); + fs::create_dir_all(&dir_a).expect("mkdir a"); + fs::create_dir_all(&dir_b).expect("mkdir b"); + + let original = dir_a.join("shared.bin"); + fs::write(&original, vec![7u8; 8192]).expect("write"); + fs::hard_link(&original, dir_b.join("alias.bin")).expect("hardlink"); + + let scanner = Scanner::new( + StorageMode::Persistent { + path: db_path, + strict: true, + }, + zero_headroom_policy(), + ) + .expect("scanner"); + + // 1. Scan only `a` so `a` is cached with its sparse hardlink identity. + let snap_a = scanner + .scan_blocking( + &dir_a, + ScanOptions::default(), + zero_headroom_policy(), + false, + ) + .expect("scan a"); + assert_eq!(snap_a.stats.apparent_bytes, 8192); + + // 2. Widen to `root`: `a` is reused from cache while `b` is freshly walked. + // Hardlink dedup must still charge `shared.bin`/`alias.bin` once! + let snap_root = scanner + .scan_blocking( + &root, + ScanOptions::default(), + zero_headroom_policy(), + false, + ) + .expect("scan root"); + assert!(snap_root.stats.skipped_fresh_dirs >= 1); + assert_eq!(snap_root.stats.apparent_bytes, 8192); + assert_eq!(snap_root.stats.files, 2); + + // 3. Reloading the full cached tree must preserve the exact same byte + // totals regardless of shard assembly order! + let cached_root = scanner + .scan_blocking( + &root, + ScanOptions::default(), + zero_headroom_policy(), + false, + ) + .expect("cached root"); + assert!(matches!(cached_root.freshness, Freshness::Fresh { .. })); + assert_eq!( + cached_root.stats.allocated_bytes, + snap_root.stats.allocated_bytes + ); + assert_eq!( + cached_root.stats.apparent_bytes, + snap_root.stats.apparent_bytes + ); +} + +#[test] +fn remote_host_namespaces_are_isolated_from_local_cache() { + let temp = tempfile::tempdir().expect("tempdir"); + let db_path = temp.path().join("hosts.redb"); + let root = temp.path().join("data"); + fs::create_dir_all(&root).expect("mkdir"); + fs::write(root.join("f.bin"), vec![1u8; 256]).expect("write"); + + let scanner = Scanner::new( + StorageMode::Persistent { + path: db_path, + strict: true, + }, + zero_headroom_policy(), + ) + .expect("scanner"); + + // Populate local namespace. + let _ = scanner + .scan_blocking( + &root, + ScanOptions::default(), + zero_headroom_policy(), + false, + ) + .expect("local"); + + // Querying the same path under a remote HostIdentity must NOT hit Local! + let remote = HostKey::Remote(HostIdentity { + hostname: "prod-01".to_owned(), + machine_id: Some("0123456789abcdef0123456789abcdef".to_owned()), + }); + let session = scanner + .open_with(remote, root, ScanOptions::default(), zero_headroom_policy()) + .expect("open remote"); + let first = session.recv().expect("first event"); + // Should NOT be a cached `Fresh` snapshot from Local. + if let disktree_scanner::ScanEvent::Snapshot(snap) = first { + assert!(!matches!(snap.freshness, Freshness::Fresh { .. })); + } +} + +#[test] +fn corrupt_db_file_falls_back_gracefully_to_in_memory() { + let temp = tempfile::tempdir().expect("tempdir"); + let db_path = temp.path().join("corrupt.redb"); + fs::write(&db_path, b"this is definitely not a valid redb file") + .expect("write garbage"); + + let root = temp.path().join("data"); + fs::create_dir_all(&root).expect("mkdir"); + fs::write(root.join("ok.txt"), b"still works").expect("write"); + + let scanner = Scanner::new( + StorageMode::Persistent { + path: db_path, + strict: false, + }, + zero_headroom_policy(), + ) + .expect("graceful fallback"); + assert_eq!(scanner.active_mode(), ActiveStorageMode::InMemory); + assert!(scanner.fallback_reason().is_some()); + + let snap = scanner + .scan_blocking( + &root, + ScanOptions::default(), + zero_headroom_policy(), + false, + ) + .expect("scan works in memory"); + assert_eq!(snap.stats.apparent_bytes, 11); +} + +#[cfg(unix)] +#[test] +fn read_only_cache_directory_falls_back_to_in_memory() { + use std::os::unix::fs::PermissionsExt as _; + + let temp = tempfile::tempdir().expect("tempdir"); + let ro_dir = temp.path().join("ro"); + fs::create_dir_all(&ro_dir).expect("mkdir ro"); + fs::set_permissions(&ro_dir, fs::Permissions::from_mode(0o555)) + .expect("chmod 555"); + + let root = temp.path().join("data"); + fs::create_dir_all(&root).expect("mkdir data"); + fs::write(root.join("a.txt"), b"abc").expect("write"); + + let is_unwritable = fs::File::create(ro_dir.join(".probe")).is_err(); + + let scanner = Scanner::new( + StorageMode::Persistent { + path: ro_dir.join("cache.redb"), + strict: false, + }, + zero_headroom_policy(), + ) + .expect("fallback on ro dir"); + + // Restore perms so TempDir cleanup succeeds cleanly. + let _ = fs::set_permissions(&ro_dir, fs::Permissions::from_mode(0o755)); + + if is_unwritable { + assert_eq!(scanner.active_mode(), ActiveStorageMode::InMemory); + assert!(scanner.fallback_reason().is_some()); + } + + let snap = scanner + .scan_blocking( + &root, + ScanOptions::default(), + zero_headroom_policy(), + false, + ) + .expect("scan succeeds"); + assert_eq!(snap.stats.apparent_bytes, 3); +} + +#[test] +fn temp_db_mode_works_and_cleans_up_on_drop() { + let temp = tempfile::tempdir().expect("tempdir"); + let root = temp.path().join("data"); + fs::create_dir_all(&root).expect("mkdir"); + fs::write(root.join("hello.txt"), b"tempdb").expect("write"); + + let db_path: Option; + { + let scanner = Scanner::new(StorageMode::TempDb, zero_headroom_policy()) + .expect("tempdb"); + assert_eq!(scanner.active_mode(), ActiveStorageMode::TempDb); + let snap = scanner + .scan_blocking( + &root, + ScanOptions::default(), + zero_headroom_policy(), + false, + ) + .expect("scan"); + assert_eq!(snap.stats.apparent_bytes, 6); + let stats = scanner.cache_stats().expect("stats"); + assert!(stats.chunks >= 1); + db_path = stats.db_path; + assert!(db_path.as_ref().is_some_and(|p| p.exists())); + } + + // Temp DB file should be removed once Scanner is dropped. + if let Some(path) = db_path { + assert!(!path.exists(), "temp db should be cleaned up on drop"); + } +} + +#[test] +fn prefix_trie_and_columnar_protobuf_compresses_repeated_names_efficiently() { + let temp = tempfile::tempdir().expect("tempdir"); + let db_path = temp.path().join("compact.redb"); + let root = temp.path().join("repo"); + + // Create 60 directories x 50 repeated filenames = 3,000 files. + for d in 0..60 { + let dir = root.join(format!("package-{d:03}/src/components")); + fs::create_dir_all(&dir).expect("mkdir"); + for f in 0..50 { + let name = match f % 5 { + 0 => format!("index-{f:02}.ts"), + 1 => format!("component-{f:02}.tsx"), + 2 => format!("component-{f:02}.test.tsx"), + 3 => format!("styles-module-{f:02}.css"), + _ => format!("package-metadata-{f:02}.json"), + }; + fs::write(dir.join(name), b"x").expect("write"); + } + } + + let scanner = Scanner::new( + StorageMode::Persistent { + path: db_path, + strict: true, + }, + zero_headroom_policy(), + ) + .expect("scanner"); + + let first = scanner + .scan_blocking( + &root, + ScanOptions::default(), + zero_headroom_policy(), + false, + ) + .expect("scan"); + assert_eq!(first.stats.files, 3_000); + + // Second scan must hit cache with 0 disk walks. + let second = scanner + .scan_blocking( + &root, + ScanOptions::default(), + zero_headroom_policy(), + false, + ) + .expect("cached scan"); + assert!(matches!(second.freshness, Freshness::Fresh { .. })); + assert_eq!(second.stats.files, 3_000); + assert_eq!(second.stats.walked_dirs, 0); + + let stats = scanner.cache_stats().expect("stats"); + assert!(stats.chunks >= 1); + assert!(stats.indexed_dirs >= 1); + + // Clear and prune sanity checks. + assert_eq!( + scanner.prune_cache(Duration::from_hours(1)).expect("prune"), + 0 + ); + scanner.clear_cache().expect("clear"); + assert_eq!(scanner.cache_stats().expect("stats").chunks, 0); +} + +#[test] +fn pause_gate_blocks_background_until_immediate_resumes() { + let gate = Arc::new(PauseGate::new()); + let cancel = Arc::new(AtomicBool::new(false)); + let passed = Arc::new(AtomicUsize::new(0)); + + gate.pause(); + let g = Arc::clone(&gate); + let c = Arc::clone(&cancel); + let p = Arc::clone(&passed); + let handle = thread::spawn(move || { + g.wait_if_paused(&c); + p.fetch_add(1, Ordering::SeqCst); + }); + + thread::sleep(Duration::from_millis(30)); + assert_eq!( + passed.load(Ordering::SeqCst), + 0, + "worker must remain paused" + ); + + gate.resume(); + handle.join().expect("join"); + assert_eq!(passed.load(Ordering::SeqCst), 1, "worker must resume"); +}