mirror of
https://github.com/tobi/disktree.git
synced 2026-11-28 08:00:53 +00:00
feat(scanner): prioritize unscanned directories ahead of stale ones (oldest first) and splice immediate refreshes
This commit is contained in:
@@ -1658,6 +1658,43 @@ impl Disktree {
|
||||
cx.notify();
|
||||
return true;
|
||||
}
|
||||
ScanUpdate::SubtreeRefreshed { path, arena: sub } => {
|
||||
if let Some(current_arena) = self.arena.as_mut() {
|
||||
let root = current_arena.root_path().to_path_buf();
|
||||
let updated = if path == root {
|
||||
Some((*sub).clone())
|
||||
} else if let Ok(rel) = path.strip_prefix(&root) {
|
||||
let parts: Vec<String> = rel
|
||||
.components()
|
||||
.map(|c| {
|
||||
c.as_os_str().to_string_lossy().into_owned()
|
||||
})
|
||||
.collect();
|
||||
let mut next = (**current_arena).clone();
|
||||
if let Some(target_id) =
|
||||
next.find_relative(parts.iter().map(String::as_str))
|
||||
{
|
||||
next.replace_node_contents(target_id, &sub);
|
||||
next.aggregate(
|
||||
self.options.dedup_hardlinks,
|
||||
self.options.include_hidden,
|
||||
);
|
||||
Some(next)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(next) = updated {
|
||||
let next = Arc::new(next);
|
||||
self.arena = Some(Arc::clone(&next));
|
||||
self.reproject_arena(&next, cx);
|
||||
}
|
||||
}
|
||||
cx.notify();
|
||||
return true;
|
||||
}
|
||||
ScanUpdate::Live { arena, node }
|
||||
if self.refresh_metric.is_some() =>
|
||||
{
|
||||
|
||||
@@ -211,6 +211,12 @@ pub enum ScanUpdate {
|
||||
node: Node,
|
||||
freshness: Freshness,
|
||||
},
|
||||
/// A prioritized subtree finished scanning while background revalidation
|
||||
/// continues on the rest of the root.
|
||||
SubtreeRefreshed {
|
||||
path: PathBuf,
|
||||
arena: Arc<TreeArena>,
|
||||
},
|
||||
/// Completed live scan (all subtrees up to date and persisted to cache).
|
||||
Live { arena: Arc<TreeArena>, node: Node },
|
||||
/// Non-fatal or fatal scan error.
|
||||
@@ -439,10 +445,15 @@ impl ScanHandle {
|
||||
self.progress.finish();
|
||||
return Some(ScanUpdate::Finished);
|
||||
}
|
||||
Ok(ScanEvent::SubtreeRefreshed { path, arena, .. }) => {
|
||||
return Some(ScanUpdate::SubtreeRefreshed {
|
||||
path,
|
||||
arena,
|
||||
});
|
||||
}
|
||||
Ok(
|
||||
ScanEvent::Progress { .. }
|
||||
| ScanEvent::SubtreeUpdating { .. }
|
||||
| ScanEvent::SubtreeRefreshed { .. }
|
||||
| ScanEvent::StorageFallback { .. },
|
||||
) => {}
|
||||
Err(std::sync::mpsc::TryRecvError::Empty) => return None,
|
||||
@@ -485,7 +496,9 @@ impl ScanHandle {
|
||||
freshness: Freshness::Fresh { .. },
|
||||
..
|
||||
} => Some(Ok(node)),
|
||||
ScanUpdate::Cached { .. } => None,
|
||||
ScanUpdate::Cached { .. } | ScanUpdate::SubtreeRefreshed { .. } => {
|
||||
None
|
||||
}
|
||||
ScanUpdate::Error(err) => Some(Err(err)),
|
||||
ScanUpdate::Finished => Some(Err(io::Error::other(
|
||||
"the scan finished without producing a tree",
|
||||
|
||||
@@ -75,6 +75,17 @@ pub struct CachedSubtree {
|
||||
pub freshness: Freshness,
|
||||
}
|
||||
|
||||
/// Partition of cached subdirectories below a scan root into fresh (skip) and
|
||||
/// stale (defer behind unscanned/missing directories, oldest first).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct SubtreeCatalog {
|
||||
/// Fresh cached shards (`path -> dir_id`), safe to graft without walking.
|
||||
pub fresh: FxHashMap<PathBuf, u64>,
|
||||
/// Stale cached shards (`path -> scanned_at_unix`), refreshed after
|
||||
/// unscanned directories.
|
||||
pub stale: FxHashMap<PathBuf, u64>,
|
||||
}
|
||||
|
||||
/// Summary of an invalidation operation.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct InvalidateReport {
|
||||
@@ -632,8 +643,11 @@ impl CacheDb {
|
||||
|
||||
/// Preload the map of fresh cached shard paths strictly beneath `root_path`
|
||||
/// so a live walk can skip them with a lock-free O(1) lookup.
|
||||
/// Classify all cached shards strictly beneath `root_path` into fresh
|
||||
/// (<= TTL, skip via [`Self::load_shard_by_dir_id`]) and stale (> TTL,
|
||||
/// defer behind unscanned directories and refresh oldest-first).
|
||||
#[cfg(feature = "cache-db")]
|
||||
pub fn fresh_subtrees_below(
|
||||
pub fn cached_subtrees_below(
|
||||
&self,
|
||||
host: &HostKey,
|
||||
root_path: &Path,
|
||||
@@ -641,7 +655,7 @@ impl CacheDb {
|
||||
now: u64,
|
||||
ttl_secs: u64,
|
||||
exclude: &FxHashSet<PathBuf>,
|
||||
) -> Result<FxHashMap<PathBuf, u64>, FallbackReason> {
|
||||
) -> Result<SubtreeCatalog, FallbackReason> {
|
||||
let host_key = host.as_db_key();
|
||||
let normalized_root = normalize_path(root_path);
|
||||
let prefix = if normalized_root == "/" {
|
||||
@@ -661,7 +675,7 @@ impl CacheDb {
|
||||
.open_table(DIR_INDEX_TABLE)
|
||||
.map_err(|e| classify_redb_error(&e.into()))?;
|
||||
|
||||
let mut fresh = FxHashMap::default();
|
||||
let mut catalog = SubtreeCatalog::default();
|
||||
let start = (host_key.as_str(), prefix.as_str());
|
||||
let iter = path_to_dir
|
||||
.range(start..)
|
||||
@@ -685,18 +699,21 @@ impl CacheDb {
|
||||
if let Some(entry) = read_dir_entry(&dir_index, &host_key, dir_id)?
|
||||
&& entry.chunk_id != 0
|
||||
&& entry.scanned_at_unix > 0
|
||||
&& now.saturating_sub(entry.scanned_at_unix) <= ttl_secs
|
||||
&& is_entry_compatible(&entry, options)
|
||||
{
|
||||
fresh.insert(path_buf, dir_id);
|
||||
if now.saturating_sub(entry.scanned_at_unix) <= ttl_secs {
|
||||
catalog.fresh.insert(path_buf, dir_id);
|
||||
} else {
|
||||
catalog.stale.insert(path_buf, entry.scanned_at_unix);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(fresh)
|
||||
Ok(catalog)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "cache-db"))]
|
||||
pub fn fresh_subtrees_below(
|
||||
pub fn cached_subtrees_below(
|
||||
&self,
|
||||
_host: &HostKey,
|
||||
_root_path: &Path,
|
||||
@@ -704,8 +721,26 @@ impl CacheDb {
|
||||
_now: u64,
|
||||
_ttl_secs: u64,
|
||||
_exclude: &FxHashSet<PathBuf>,
|
||||
) -> Result<SubtreeCatalog, FallbackReason> {
|
||||
Ok(SubtreeCatalog::default())
|
||||
}
|
||||
|
||||
/// Preload the map of fresh (`<= ttl_secs`) cached shard `dir_id`s
|
||||
/// strictly beneath `root_path` so the parallel walker can skip them
|
||||
/// lock-free.
|
||||
pub fn fresh_subtrees_below(
|
||||
&self,
|
||||
host: &HostKey,
|
||||
root_path: &Path,
|
||||
options: &ScanOptions,
|
||||
now: u64,
|
||||
ttl_secs: u64,
|
||||
exclude: &FxHashSet<PathBuf>,
|
||||
) -> Result<FxHashMap<PathBuf, u64>, FallbackReason> {
|
||||
Ok(FxHashMap::default())
|
||||
self.cached_subtrees_below(
|
||||
host, root_path, options, now, ttl_secs, exclude,
|
||||
)
|
||||
.map(|catalog| catalog.fresh)
|
||||
}
|
||||
|
||||
/// Load a single shard by `dir_id` (used when grafting a skipped fresh
|
||||
|
||||
@@ -19,7 +19,7 @@ pub mod walk;
|
||||
#[cfg(windows)]
|
||||
pub mod windows;
|
||||
|
||||
pub use db::{CacheDb, CachedSubtree, InvalidateReport};
|
||||
pub use db::{CacheDb, CachedSubtree, InvalidateReport, SubtreeCatalog};
|
||||
pub use mounts::{default_cache_db_path, space_info};
|
||||
pub use session::{ScanEvent, ScanSession, ScanSnapshot, Scanner};
|
||||
pub use stream::{
|
||||
@@ -34,5 +34,6 @@ pub use types::{
|
||||
SpaceInfo, StorageMode, SubtreeStatus, unix_now,
|
||||
};
|
||||
pub use walk::{
|
||||
DirTallyHook, PauseGate, SkipOracle, WalkConfig, WalkOutcome, WalkProgress,
|
||||
DirFreshness, DirTallyHook, PauseGate, SkipOracle, WalkConfig, WalkOutcome,
|
||||
WalkProgress,
|
||||
};
|
||||
|
||||
@@ -749,33 +749,47 @@ fn run_background_walk(
|
||||
.db
|
||||
.clone();
|
||||
|
||||
// Preload fresh subtrees strictly beneath `walk_root` into a lock-free map.
|
||||
let db_fresh = if policy.reuse_fresh_subtrees && !policy.force_refresh {
|
||||
if let Some(db) = &db_opt {
|
||||
match db.fresh_subtrees_below(
|
||||
host,
|
||||
walk_root,
|
||||
options,
|
||||
now,
|
||||
ttl_secs,
|
||||
&FxHashSet::default(),
|
||||
) {
|
||||
Ok(map) => map,
|
||||
Err(reason) => {
|
||||
let from = downgrade_storage(storage, reason.clone());
|
||||
let _ = event_tx.send(ScanEvent::StorageFallback {
|
||||
from,
|
||||
to: ActiveStorageMode::InMemory,
|
||||
reason,
|
||||
});
|
||||
FxHashMap::default()
|
||||
// Preload fresh (skip) and stale (defer-last, oldest-first) subtrees
|
||||
// strictly beneath `walk_root`. Even on `force_refresh`, loading stale
|
||||
// timestamps lets brand-new unscanned directories walk ahead of cached ones.
|
||||
let catalog = if let Some(db) = &db_opt {
|
||||
let effective_ttl =
|
||||
if policy.reuse_fresh_subtrees && !policy.force_refresh {
|
||||
ttl_secs
|
||||
} else {
|
||||
0
|
||||
};
|
||||
match db.cached_subtrees_below(
|
||||
host,
|
||||
walk_root,
|
||||
options,
|
||||
now,
|
||||
effective_ttl,
|
||||
&FxHashSet::default(),
|
||||
) {
|
||||
Ok(mut catalog) => {
|
||||
if !policy.reuse_fresh_subtrees || policy.force_refresh {
|
||||
// Nothing is skipped on force_refresh; treat any
|
||||
// just-written `now` entries as stale too so unscanned
|
||||
// paths still run first.
|
||||
for (path, _) in catalog.fresh.drain() {
|
||||
catalog.stale.insert(path, now);
|
||||
}
|
||||
}
|
||||
catalog
|
||||
}
|
||||
Err(reason) => {
|
||||
let from = downgrade_storage(storage, reason.clone());
|
||||
let _ = event_tx.send(ScanEvent::StorageFallback {
|
||||
from,
|
||||
to: ActiveStorageMode::InMemory,
|
||||
reason,
|
||||
});
|
||||
crate::db::SubtreeCatalog::default()
|
||||
}
|
||||
} else {
|
||||
FxHashMap::default()
|
||||
}
|
||||
} else {
|
||||
FxHashMap::default()
|
||||
crate::db::SubtreeCatalog::default()
|
||||
};
|
||||
|
||||
let loader: Option<ShardLoader> = db_opt.as_ref().map(|db| {
|
||||
@@ -797,7 +811,8 @@ fn run_background_walk(
|
||||
|
||||
let oracle: Arc<dyn SkipOracle> = Arc::new(MapSkipOracle {
|
||||
in_memory: Arc::clone(completed_immediate),
|
||||
db_fresh,
|
||||
db_fresh: catalog.fresh,
|
||||
db_stale: catalog.stale,
|
||||
loader,
|
||||
});
|
||||
|
||||
|
||||
@@ -118,12 +118,37 @@ impl PauseGate {
|
||||
}
|
||||
}
|
||||
|
||||
/// Callback oracle consulted before entering a subdirectory to reuse an
|
||||
/// already-fresh cached (or freshly prioritized) subtree without touching disk.
|
||||
/// Freshness tier of a subdirectory for priority-ordered traversal.
|
||||
///
|
||||
/// Scheduling order:
|
||||
/// 1. `Priority::Immediate` (user-requested, preempts via [`PauseGate`])
|
||||
/// 2. [`Self::Unscanned`] (no cached data at all — fill blind spots first)
|
||||
/// 3. [`Self::Stale`] (cached data exists, older than TTL — oldest first, last)
|
||||
/// 4. [`Self::Fresh`] (within TTL — grafted from cache without touching disk)
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum DirFreshness {
|
||||
/// Cached and within TTL: graft without walking disk.
|
||||
Fresh,
|
||||
/// No complete cached data (missing, stub, or invalidated): walk first.
|
||||
Unscanned,
|
||||
/// Complete cached data exists, older than TTL: defer and walk oldest-first.
|
||||
Stale { scanned_at: u64 },
|
||||
}
|
||||
|
||||
/// Oracle consulted before entering a subdirectory.
|
||||
///
|
||||
/// Reuses already-fresh cached (or freshly prioritized) subtrees without
|
||||
/// touching disk, and classifies remaining subdirectories as unscanned vs stale.
|
||||
pub trait SkipOracle: Send + Sync {
|
||||
/// If `path` is already fresh and compatible, return its ready
|
||||
/// [`TreeArena`] to graft directly into the walk.
|
||||
fn try_reuse(&self, path: &Path) -> Option<TreeArena>;
|
||||
|
||||
/// Classify `path` for priority ordering: unscanned (no data) walks before
|
||||
/// stale (has cached data).
|
||||
fn freshness(&self, _path: &Path) -> DirFreshness {
|
||||
DirFreshness::Unscanned
|
||||
}
|
||||
}
|
||||
|
||||
/// Live atomic counters published while a walk is in progress.
|
||||
@@ -264,6 +289,7 @@ pub fn walk_parallel(
|
||||
on_dir_tally: config.on_dir_tally,
|
||||
#[cfg(windows)]
|
||||
volume,
|
||||
deferred_stale: Mutex::new(Vec::new()),
|
||||
finished_root: Mutex::new(None),
|
||||
});
|
||||
|
||||
@@ -302,6 +328,80 @@ pub fn walk_parallel(
|
||||
scan_dir(s, &ctx, &root_pending);
|
||||
});
|
||||
});
|
||||
// Every Unscanned (no-data) directory has now been walked. Drain
|
||||
// deferred Stale directories last, oldest first, so blind spots always
|
||||
// get data before cached areas are re-walked.
|
||||
loop {
|
||||
if ctx.cancel.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
let mut stale = std::mem::take(
|
||||
&mut *ctx
|
||||
.deferred_stale
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner),
|
||||
);
|
||||
if stale.is_empty() {
|
||||
break;
|
||||
}
|
||||
// Oldest cached data refreshes first (`scope_fifo` preserves FIFO
|
||||
// spawn order rather than Rayon's default LIFO deque).
|
||||
stale.sort_by_key(|(scanned_at, _)| *scanned_at);
|
||||
rayon::scope_fifo(|scope| {
|
||||
for (_, sub) in stale {
|
||||
let ctx = Arc::clone(&ctx);
|
||||
scope.spawn_fifo(move |_| {
|
||||
// A user may have prioritized this stale subtree while
|
||||
// unscanned directories were walking: graft it without
|
||||
// walking twice.
|
||||
if let Some(oracle) = &ctx.skip_oracle
|
||||
&& let Some(reused) = oracle.try_reuse(&sub.path)
|
||||
{
|
||||
let reused_root = reused.node(reused.root());
|
||||
ctx.progress.skipped_fresh_dirs.fetch_add(
|
||||
u64::from(reused_root.dirs),
|
||||
Ordering::Relaxed,
|
||||
);
|
||||
ctx.progress.dirs.fetch_add(
|
||||
u64::from(reused_root.dirs),
|
||||
Ordering::Relaxed,
|
||||
);
|
||||
ctx.progress.files.fetch_add(
|
||||
reused_root.files,
|
||||
Ordering::Relaxed,
|
||||
);
|
||||
ctx.progress.allocated_bytes.fetch_add(
|
||||
reused_root.allocated_bytes,
|
||||
Ordering::Relaxed,
|
||||
);
|
||||
ctx.progress.apparent_bytes.fetch_add(
|
||||
reused_root.apparent_bytes,
|
||||
Ordering::Relaxed,
|
||||
);
|
||||
if let Some(parent) = &sub.parent {
|
||||
parent
|
||||
.children
|
||||
.lock()
|
||||
.unwrap_or_else(
|
||||
std::sync::PoisonError::into_inner,
|
||||
)
|
||||
.push(BuiltChild::Grafted {
|
||||
name: sub.name.clone(),
|
||||
arena: reused,
|
||||
hidden: sub.hidden,
|
||||
lossy_name: sub.lossy_name,
|
||||
});
|
||||
complete_one(&ctx, parent);
|
||||
}
|
||||
return;
|
||||
}
|
||||
rayon::scope(|inner| {
|
||||
scan_dir(inner, &ctx, &sub);
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
|
||||
@@ -360,6 +460,9 @@ struct WalkContext {
|
||||
on_dir_tally: Option<DirTallyHook>,
|
||||
#[cfg(windows)]
|
||||
volume: Option<u32>,
|
||||
/// Stale subdirectories (already have cached data) deferred until every
|
||||
/// Unscanned (no-data) subdirectory finishes.
|
||||
deferred_stale: Mutex<Vec<(u64, Arc<PendingDir>)>>,
|
||||
finished_root: Mutex<Option<BuiltNode>>,
|
||||
}
|
||||
|
||||
@@ -924,16 +1027,30 @@ fn scan_dir(scope: &Scope<'_>, ctx: &Arc<WalkContext>, dir: &Arc<PendingDir>) {
|
||||
.extend(local_children);
|
||||
}
|
||||
|
||||
// Add every subdirectory to `pending` BEFORE spawning so the `+1` sentinel
|
||||
// guarantees `dir` cannot complete prematurely.
|
||||
// Add every subdirectory to `pending` BEFORE spawning or deferring so the
|
||||
// `+1` sentinel guarantees `dir` cannot complete prematurely.
|
||||
if !subdirs.is_empty() {
|
||||
dir.pending.fetch_add(subdirs.len(), Ordering::AcqRel);
|
||||
let mut stale_deferred: Vec<(u64, Arc<PendingDir>)> = Vec::new();
|
||||
for sub in subdirs {
|
||||
if let Some(oracle) = &ctx.skip_oracle
|
||||
&& let DirFreshness::Stale { scanned_at } =
|
||||
oracle.freshness(&sub.path)
|
||||
{
|
||||
stale_deferred.push((scanned_at, sub));
|
||||
continue;
|
||||
}
|
||||
let ctx = Arc::clone(ctx);
|
||||
scope.spawn(move |s| {
|
||||
scan_dir(s, &ctx, &sub);
|
||||
});
|
||||
}
|
||||
if !stale_deferred.is_empty() {
|
||||
ctx.deferred_stale
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.extend(stale_deferred);
|
||||
}
|
||||
}
|
||||
|
||||
// Release this directory's own `+1` sentinel.
|
||||
@@ -1057,14 +1174,18 @@ fn materialize_arena(
|
||||
arena
|
||||
}
|
||||
|
||||
/// Simple map-backed [`SkipOracle`] combining fresh DB shards and recently
|
||||
/// completed immediate priority revalidations.
|
||||
/// Simple map-backed [`SkipOracle`] combining fresh DB shards, stale DB
|
||||
/// timestamps (for defer-last ordering), and recently completed immediate
|
||||
/// priority revalidations.
|
||||
pub struct MapSkipOracle {
|
||||
/// Already-materialized subtrees (e.g. finished `Priority::Immediate`
|
||||
/// scans that the resumed background scan must not re-walk).
|
||||
pub in_memory: Arc<Mutex<FxHashMap<PathBuf, TreeArena>>>,
|
||||
/// Fresh DB shard `dir_id`s preloaded before the walk began.
|
||||
/// Fresh DB shard `dir_id`s preloaded before the walk began (skipped).
|
||||
pub db_fresh: FxHashMap<PathBuf, u64>,
|
||||
/// Stale DB shard `scanned_at` timestamps preloaded before the walk began
|
||||
/// (deferred behind unscanned directories, refreshed oldest-first).
|
||||
pub db_stale: FxHashMap<PathBuf, u64>,
|
||||
/// Loader callback for `db_fresh` hits.
|
||||
pub loader: Option<ShardLoader>,
|
||||
}
|
||||
@@ -1073,6 +1194,7 @@ impl std::fmt::Debug for MapSkipOracle {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("MapSkipOracle")
|
||||
.field("db_fresh_len", &self.db_fresh.len())
|
||||
.field("db_stale_len", &self.db_stale.len())
|
||||
.field("has_loader", &self.loader.is_some())
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
@@ -1095,4 +1217,134 @@ impl SkipOracle for MapSkipOracle {
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn freshness(&self, path: &Path) -> DirFreshness {
|
||||
if self
|
||||
.in_memory
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.contains_key(path)
|
||||
|| self.db_fresh.contains_key(path)
|
||||
{
|
||||
return DirFreshness::Fresh;
|
||||
}
|
||||
if let Some(&scanned_at) = self.db_stale.get(path) {
|
||||
return DirFreshness::Stale { scanned_at };
|
||||
}
|
||||
DirFreshness::Unscanned
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
struct TestOracle {
|
||||
fresh: FxHashMap<PathBuf, TreeArena>,
|
||||
stale: FxHashMap<PathBuf, u64>,
|
||||
}
|
||||
|
||||
impl SkipOracle for TestOracle {
|
||||
fn try_reuse(&self, path: &Path) -> Option<TreeArena> {
|
||||
self.fresh.get(path).cloned()
|
||||
}
|
||||
|
||||
fn freshness(&self, path: &Path) -> DirFreshness {
|
||||
if self.fresh.contains_key(path) {
|
||||
DirFreshness::Fresh
|
||||
} else if let Some(&scanned_at) = self.stale.get(path) {
|
||||
DirFreshness::Stale { scanned_at }
|
||||
} else {
|
||||
DirFreshness::Unscanned
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unscanned_dirs_walk_before_stale_and_oldest_stale_walks_first() {
|
||||
let temp = tempfile::tempdir().expect("tempdir");
|
||||
let root = temp.path().canonicalize().expect("canonical");
|
||||
let fresh_dir = root.join("a_fresh");
|
||||
let stale_newer = root.join("b_stale_newer");
|
||||
let stale_older = root.join("c_stale_older");
|
||||
let unscanned = root.join("d_unscanned");
|
||||
for dir in [&fresh_dir, &stale_newer, &stale_older, &unscanned] {
|
||||
fs::create_dir(dir).expect("mkdir");
|
||||
fs::write(dir.join("file.bin"), b"1234").expect("write");
|
||||
}
|
||||
|
||||
let mut fresh_arena = TreeArena::new(fresh_dir.clone(), "a_fresh");
|
||||
let fresh_root = fresh_arena.root();
|
||||
fresh_arena.add_child(
|
||||
fresh_root,
|
||||
"file.bin",
|
||||
NodeKind::File,
|
||||
4096,
|
||||
4,
|
||||
0,
|
||||
NodeFlags::new(NodeKind::File),
|
||||
);
|
||||
fresh_arena.aggregate(true, true);
|
||||
|
||||
let mut fresh = FxHashMap::default();
|
||||
fresh.insert(fresh_dir.clone(), fresh_arena);
|
||||
let mut stale = FxHashMap::default();
|
||||
stale.insert(stale_newer.clone(), 2000);
|
||||
stale.insert(stale_older.clone(), 1000);
|
||||
|
||||
let oracle: Arc<dyn SkipOracle> = Arc::new(TestOracle { fresh, stale });
|
||||
let visited: Arc<Mutex<Vec<PathBuf>>> =
|
||||
Arc::new(Mutex::new(Vec::new()));
|
||||
let visited_hook = Arc::clone(&visited);
|
||||
let on_dir_start: DirStartHook = Arc::new(move |dir: &Path| {
|
||||
visited_hook
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.push(dir.to_path_buf());
|
||||
});
|
||||
|
||||
// Single worker guarantees deterministic FIFO ordering within each tier.
|
||||
let options = ScanOptions {
|
||||
apparent_size: true,
|
||||
threads: Some(1),
|
||||
..ScanOptions::default()
|
||||
};
|
||||
let outcome = walk_parallel(
|
||||
&root,
|
||||
WalkConfig {
|
||||
options: &options,
|
||||
cancel: Arc::new(AtomicBool::new(false)),
|
||||
progress: Arc::new(WalkProgress::default()),
|
||||
pause_gate: None,
|
||||
skip_oracle: Some(oracle),
|
||||
on_dir_start: Some(on_dir_start),
|
||||
on_dir_tally: None,
|
||||
},
|
||||
)
|
||||
.expect("walk");
|
||||
|
||||
let order = visited
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clone();
|
||||
assert!(!order.contains(&fresh_dir), "fresh dir must be skipped");
|
||||
let pos_unscanned = order
|
||||
.iter()
|
||||
.position(|p| p == &unscanned)
|
||||
.expect("unscanned walked");
|
||||
let pos_older = order
|
||||
.iter()
|
||||
.position(|p| p == &stale_older)
|
||||
.expect("older stale walked");
|
||||
let pos_newer = order
|
||||
.iter()
|
||||
.position(|p| p == &stale_newer)
|
||||
.expect("newer stale walked");
|
||||
assert!(
|
||||
pos_unscanned < pos_older && pos_older < pos_newer,
|
||||
"expected unscanned < older_stale < newer_stale, got {order:?}"
|
||||
);
|
||||
assert_eq!(outcome.stats.apparent_bytes, 16);
|
||||
assert_eq!(outcome.stats.files, 4);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user