refactor: switch workspace all-in on disktree-scanner and remove legacy scanners

This commit is contained in:
Tobi Lutke
2026-11-25 15:23:00 -05:00
parent 2f5b1a4b92
commit e85f8a749b
42 changed files with 12163 additions and 2984 deletions
+12 -8
View File
@@ -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` |
Generated
+441 -25
View File
@@ -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",
+9 -1
View File
@@ -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"
+17 -13
View File
@@ -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
+1
View File
@@ -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"
+24 -96
View File
@@ -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<Args> {
let mut root: Option<PathBuf> = 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());
}
}
+1 -15
View File
@@ -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);
+353 -90
View File
@@ -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<Arc<TreeArena>>,
pub freshness: Option<Freshness>,
pub tree: Option<Arc<Node>>,
pub scan: Option<ScanHandle>,
pub scan_epoch: u64,
/// Metric of a background refresh, or `None` for a normal scan.
pub refresh_metric: Option<Metric>,
pub progress: ScanSnapshot,
pub scan_error: Option<String>,
@@ -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<PathBuf>,
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<PathBuf> = 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());
+115 -23
View File
@@ -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());
});
+38 -9
View File
@@ -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()
+27
View File
@@ -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"
+275
View File
@@ -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<Command>,
/// Directory to inspect (defaults to current working directory).
pub path: Option<PathBuf>,
/// 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<PathBuf>,
/// 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<PathBuf>,
/// 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<usize>,
/// Maximum number of children emitted per directory in JSON/text output.
#[arg(long)]
pub top: Option<usize>,
/// 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<usize>,
}
#[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<PathBuf>,
/// 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<Duration, String> {
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::<u64>() {
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());
}
}
+57
View File
@@ -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
}
+199
View File
@@ -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<HostIdentity>,
pub root: String,
pub metric: Metric,
pub apparent_size: bool,
pub include_hidden: bool,
pub freshness: JsonFreshness,
pub storage: JsonStorage,
pub space: Option<SpaceInfo>,
pub stats: ScanStats,
pub tree: JsonNode,
}
#[derive(Serialize)]
pub struct JsonFreshness {
pub status: &'static str,
pub scanned_at: Option<u64>,
pub age_seconds: Option<u64>,
pub stale_dirs: Option<u32>,
}
#[derive(Serialize)]
pub struct JsonStorage {
pub mode: ActiveStorageMode,
pub fallback_reason: Option<FallbackReason>,
}
#[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<Self>,
}
/// 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<usize>,
top_n: Option<usize>,
space: Option<SpaceInfo>,
) -> 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<usize>,
top_n: Option<usize>,
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<NodeId> = 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<W: Write>(
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<W: Write, T: Serialize>(
out: &mut W,
value: &T,
) -> io::Result<()> {
serde_json::to_writer(&mut *out, value).map_err(io::Error::other)?;
writeln!(out)
}
+300
View File
@@ -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()
}
File diff suppressed because it is too large Load Diff
+148
View File
@@ -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<Value> = 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"));
}
+5 -8
View File
@@ -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"] }
@@ -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::<usize>().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
);
}
+1 -6
View File
@@ -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;
+124 -142
View File
@@ -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<ReadDir>,
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::<std::time::Instant>;
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::<Instant>;
let maybe_heartbeat = |dir: &Path,
heartbeat: &mut Option<Instant>,
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(
+1 -1
View File
@@ -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),
File diff suppressed because it is too large Load Diff
-733
View File
@@ -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<f64>,
}
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<T> {
state: Mutex<Queue<T>>,
}
struct Queue<T> {
pending: Vec<T>,
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<T> Admission<T> {
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<T>> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(crate) fn start(&self) -> Vec<T> {
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<T>) -> Vec<T> {
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<T>) -> Vec<T> {
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<f64>,
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<f64>) -> 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<f64>,
cap: usize,
high: u8,
low: u8,
pub(crate) pressured: bool,
}
impl Governor {
pub(crate) const fn new(cap: usize, ceiling: Option<f64>) -> 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<f64>,
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<bool>, Condvar)>,
worker: Option<JoinHandle<()>>,
}
impl ControllerGuard {
pub(crate) fn spawn<T: Send + 'static>(
options: ScanThreads,
admission: Arc<Admission<T>>,
progress: Arc<ScanProgress>,
) -> io::Result<Option<Self>> {
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<T>(
options: ScanThreads,
admission: &Admission<T>,
progress: &ScanProgress,
stop: &(Mutex<bool>, 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<T>(
options: ScanThreads,
admission: &Admission<T>,
progress: &ScanProgress,
stop: &(Mutex<bool>, Condvar),
interval: Duration,
mut sample_cpu: impl FnMut() -> Option<f64>,
) {
// 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<f64> {
#[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<usize>,
admission: &Arc<Admission<usize>>,
releases: &Arc<Mutex<Vec<Option<mpsc::Receiver<()>>>>>,
started: &mpsc::Sender<usize>,
completed: &mpsc::Sender<usize>,
) {
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);
}
}
+121 -70
View File
@@ -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<SpaceInfo> {
crate::windows::space_info(path)
}
/// Read the space on the volume containing `path`.
#[cfg(not(windows))]
pub fn space_info(path: &Path) -> io::Result<SpaceInfo> {
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<PathBuf> {
.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<PathBuf> {
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<Vec<PathBuf>> {
#[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<Vec<PathBuf>> {
#[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(
+1 -1
View File
@@ -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"] }
+38
View File
@@ -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"
@@ -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];
}
File diff suppressed because it is too large Load Diff
+38
View File
@@ -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,
};
@@ -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<io::Result<Node>> {
cancel: &AtomicBool,
progress: &WalkProgress,
) -> Option<io::Result<BuiltNode>> {
// 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<Vec<Parsed>> {
let threads = rayon::current_num_threads().max(1);
let mut stretches: Vec<Vec<&mut [Info]>> =
@@ -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<String>,
starts: Vec<u32>,
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<str>,
name: String,
hidden: bool,
depth: usize,
) -> Result<Node, Stop> {
) -> Result<BuiltNode, Stop> {
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<Option<Node>, Stop> {
) -> Result<Option<BuiltChild>, 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));
}
}
+400
View File
@@ -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<SpaceInfo> {
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<SpaceInfo> {
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<PathBuf> {
#[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<FxHashSet<PathBuf>> {
#[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<FxHashSet<PathBuf>> {
#[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<PathBuf> {
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<PathBuf> {
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<S: std::hash::BuildHasher>(
mut boundaries: std::collections::HashSet<PathBuf, S>,
views: &[MountView],
root: &Path,
) -> std::collections::HashSet<PathBuf, S> {
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<Self> {
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<PathBuf> {
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 { .. })));
}
}
}
+627
View File
@@ -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<u8>,
}
#[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<FrontCodedStrings>,
#[prost(uint32, repeated, packed = "true", tag = "6")]
pub name_ids: Vec<u32>,
#[prost(uint32, repeated, packed = "true", tag = "7")]
pub child_counts: Vec<u32>,
#[prost(uint32, repeated, packed = "true", tag = "8")]
pub flags: Vec<u32>,
#[prost(uint64, repeated, packed = "true", tag = "9")]
pub allocated_bytes: Vec<u64>,
#[prost(sint64, repeated, packed = "true", tag = "10")]
pub apparent_deltas: Vec<i64>,
#[prost(sint64, repeated, packed = "true", tag = "11")]
pub mtime_deltas: Vec<i64>,
#[prost(uint32, repeated, packed = "true", tag = "12")]
pub hardlink_node_idx: Vec<u32>,
#[prost(uint64, repeated, packed = "true", tag = "13")]
pub hardlink_devs: Vec<u64>,
#[prost(uint64, repeated, packed = "true", tag = "14")]
pub hardlink_inos: Vec<u64>,
#[prost(uint64, repeated, packed = "true", tag = "15")]
pub external_dir_ids: Vec<u64>,
}
/// 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<M: prost::Message>(msg: &M) -> Vec<u8> {
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<M: prost::Message + Default>(
bytes: &[u8],
) -> io::Result<M> {
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<S: BuildHasher>(
arena: &TreeArena,
sub_root: NodeId,
chunk_id: u64,
root_dir_id: u64,
scanned_at_unix: u64,
external_shards: &HashMap<NodeId, u64, S>,
) -> SubtreeChunk {
// Index hardlinks by node for O(1) lookup during preorder walk.
let mut hardlink_by_node: FxHashMap<NodeId, Vec<(u64, u64)>> =
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<NodeId> = 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<DecodedChunk> {
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<Option<NodeId>> = 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");
}
}
File diff suppressed because it is too large Load Diff
+435
View File
@@ -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<PathBuf>,
/// 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<usize>,
/// 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<ReadDir>,
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<F>(
root: &Path,
options: &ScanOptions,
cancel: Option<&Arc<AtomicBool>>,
emit: F,
) -> io::Result<()>
where
F: FnMut(StreamItem) -> io::Result<()>,
{
let mut excluded: FxHashSet<PathBuf> = 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<F>(
root: &Path,
options: &ScanOptions,
config: &StreamConfig,
cancel: Option<&Arc<AtomicBool>>,
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);
}
}
+363
View File
@@ -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<u32>,
/// Primary hash -> first `NameId` with that hash.
index: FxHashMap<u64, NameId>,
/// 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<Item = (NameId, &str)> {
(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<u8>, Vec<NameId>) {
let count = self.len();
if count == 0 {
return (Vec::new(), Vec::new());
}
let mut order: Vec<u32> = (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 = &current[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<Self> {
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<u8>) {
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<u64> {
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<NameId> = 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);
}
}
}
+894
View File
@@ -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<NodeId>`
/// 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<Self> {
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<NodeId>,
pub first_child: Option<NodeId>,
pub next_sibling: Option<NodeId>,
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<ArenaNode>,
/// Tracks last child per node during construction for O(1) append.
last_child: Vec<Option<NodeId>>,
strings: StringPool,
hardlinks: Vec<HardlinkEntry>,
}
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<ArenaNode>,
last_child: Vec<Option<NodeId>>,
strings: StringPool,
hardlinks: Vec<HardlinkEntry>,
) -> 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<Option<NodeId>> =
vec![None; replacement.nodes.len()];
id_map[replacement.root().index()] = Some(target);
let mut stack: Vec<(NodeId, NodeId)> = replacement
.children(replacement.root())
.collect::<Vec<_>>()
.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<Option<NodeId>> = vec![None; self.nodes.len()];
id_map[sub_root.index()] = Some(out.root());
let mut stack: Vec<(NodeId, NodeId)> = self
.children(sub_root)
.collect::<Vec<_>>()
.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<NameId> = 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<Item = &'a str>,
) -> Option<NodeId> {
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<u32> {
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<NodeId>,
}
impl Iterator for ChildrenIter<'_> {
type Item = NodeId;
fn next(&mut self) -> Option<Self::Item> {
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::<ArenaNode>(), 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);
}
}
+442
View File
@@ -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<u64> },
/// 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<u64>,
newest_at: Option<u64>,
},
/// 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<Duration>,
/// 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<usize>,
/// 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<usize>,
}
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<String>,
}
impl HostIdentity {
/// Capture the local machine's identity, if readable.
pub fn current() -> Option<Self> {
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<PathBuf>,
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())
}
File diff suppressed because it is too large Load Diff
@@ -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;
@@ -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<PathBuf>;
{
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");
}