mirror of
https://github.com/tobi/disktree.git
synced 2026-12-04 08:01:05 +00:00
feat(scanner,remote): cadence-based incremental checkpointing and live remote treemap previews
This commit is contained in:
@@ -11,19 +11,23 @@
|
||||
//! the connection.
|
||||
|
||||
use std::io::{self, BufReader, BufWriter, Read as _, Write};
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use disktree_core::remote::{
|
||||
Operation, Request, SessionRequest, write_arena, write_header,
|
||||
write_marker, write_progress,
|
||||
};
|
||||
use disktree_core::scan_preview;
|
||||
use disktree_scanner::{
|
||||
CachePolicy, Freshness, HostKey, ScanEvent, Scanner, StorageMode,
|
||||
CachePolicy, DirTallyHook, Freshness, HostKey, ScanEvent, Scanner,
|
||||
StorageMode,
|
||||
};
|
||||
|
||||
const STDOUT_BUFFER_BYTES: usize = 256 * 1024;
|
||||
const HEARTBEAT_INTERVAL: Duration = Duration::from_millis(200);
|
||||
const PREVIEW_INTERVAL: Duration = Duration::from_millis(500);
|
||||
|
||||
pub fn serve_stdio_v1() -> io::Result<()> {
|
||||
limit_resources()?;
|
||||
@@ -180,19 +184,45 @@ fn serve_scan_from_scanner<W: Write>(
|
||||
stale_while_revalidate: true,
|
||||
..CachePolicy::default()
|
||||
};
|
||||
let session = scanner.open_with(
|
||||
let preview = Arc::new(Mutex::new(scan_preview::Builder::default()));
|
||||
let apparent = request.options.apparent_size;
|
||||
let on_dir_tally: Option<DirTallyHook> = flags.live_progress.then(|| {
|
||||
let preview = Arc::clone(&preview);
|
||||
let hook_root = root.clone();
|
||||
let hook: DirTallyHook =
|
||||
Arc::new(move |dir: &Path, alloc: u64, app: u64, files: u64| {
|
||||
let Ok(below) = dir.strip_prefix(&hook_root) else {
|
||||
return;
|
||||
};
|
||||
let name = below
|
||||
.components()
|
||||
.next()
|
||||
.and_then(|c| c.as_os_str().to_str());
|
||||
let bytes = if apparent { app } else { alloc };
|
||||
if let Ok(mut guard) = preview.lock() {
|
||||
guard.add(name, bytes, files);
|
||||
guard.directory(dir);
|
||||
}
|
||||
});
|
||||
hook
|
||||
});
|
||||
let session = scanner.open_with_tally(
|
||||
HostKey::Local,
|
||||
root,
|
||||
request.options.to_scanner(),
|
||||
policy,
|
||||
on_dir_tally,
|
||||
)?;
|
||||
|
||||
let mut last_heartbeat = Instant::now();
|
||||
let mut last_preview: Option<Instant> = None;
|
||||
let mut streamed_final = false;
|
||||
let mut streamed_stale = false;
|
||||
let apparent = request.options.apparent_size;
|
||||
|
||||
let emit_progress = |last: &mut Instant, out: &mut W| -> io::Result<()> {
|
||||
let emit_progress = |last: &mut Instant,
|
||||
last_preview: &mut Option<Instant>,
|
||||
out: &mut W|
|
||||
-> io::Result<()> {
|
||||
if !flags.live_progress || last.elapsed() < HEARTBEAT_INTERVAL {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -208,12 +238,27 @@ fn serve_scan_from_scanner<W: Write>(
|
||||
} else {
|
||||
stats.allocated_bytes
|
||||
};
|
||||
let want_preview =
|
||||
last_preview.is_none_or(|t| t.elapsed() >= PREVIEW_INTERVAL);
|
||||
let preview_entries = want_preview.then(|| {
|
||||
preview
|
||||
.lock()
|
||||
.map(|b| b.snapshot().entries)
|
||||
.unwrap_or_default()
|
||||
});
|
||||
let preview_slice = preview_entries
|
||||
.as_deref()
|
||||
.filter(|entries| !entries.is_empty());
|
||||
if preview_slice.is_some() {
|
||||
*last_preview = Some(Instant::now());
|
||||
}
|
||||
write_progress(
|
||||
dir.as_deref(),
|
||||
stats.files,
|
||||
stats.dirs,
|
||||
bytes,
|
||||
stats.errors,
|
||||
preview_slice,
|
||||
out,
|
||||
)?;
|
||||
*last = Instant::now();
|
||||
@@ -223,7 +268,26 @@ fn serve_scan_from_scanner<W: Write>(
|
||||
loop {
|
||||
match session.recv_timeout(HEARTBEAT_INTERVAL) {
|
||||
Ok(ScanEvent::Snapshot(snap)) => match snap.freshness {
|
||||
Freshness::Partial { .. } => {}
|
||||
Freshness::Partial { .. } => {
|
||||
// If an earlier or interrupted scan already checkpointed
|
||||
// completed folders in the remote DB, stream that
|
||||
// approximate tree right away so the user can explore
|
||||
// while the remaining holes fill in.
|
||||
if flags.stream_stale
|
||||
&& !streamed_stale
|
||||
&& snap.arena.node(snap.arena.root()).files > 0
|
||||
{
|
||||
write_arena(
|
||||
&snap.arena,
|
||||
&request.options,
|
||||
flags.client_dedup,
|
||||
out,
|
||||
)?;
|
||||
write_marker("stale", out)?;
|
||||
streamed_stale = true;
|
||||
last_heartbeat = Instant::now();
|
||||
}
|
||||
}
|
||||
Freshness::Fresh { .. } => {
|
||||
write_arena(
|
||||
&snap.arena,
|
||||
@@ -279,7 +343,7 @@ fn serve_scan_from_scanner<W: Write>(
|
||||
| ScanEvent::StorageFallback { .. },
|
||||
)
|
||||
| Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
|
||||
emit_progress(&mut last_heartbeat, out)?;
|
||||
emit_progress(&mut last_heartbeat, &mut last_preview, out)?;
|
||||
}
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
|
||||
if streamed_final {
|
||||
|
||||
@@ -230,6 +230,7 @@ struct Control {
|
||||
dirs: Option<u64>,
|
||||
bytes: Option<u64>,
|
||||
errors: Option<u64>,
|
||||
preview: Option<Vec<crate::scan_preview::Entry>>,
|
||||
}
|
||||
|
||||
fn json_error(error: serde_json::Error) -> io::Error {
|
||||
@@ -340,13 +341,15 @@ pub fn write_header(
|
||||
out.flush()
|
||||
}
|
||||
|
||||
/// Emit a live progress heartbeat line during a remote parallel scan.
|
||||
/// Emit a live progress heartbeat (with optional bounded top-level treemap
|
||||
/// preview buckets) during a remote parallel scan.
|
||||
pub fn write_progress(
|
||||
dir: Option<&Path>,
|
||||
files: u64,
|
||||
dirs: u64,
|
||||
bytes: u64,
|
||||
errors: u64,
|
||||
preview: Option<&[crate::scan_preview::Entry]>,
|
||||
out: &mut impl Write,
|
||||
) -> io::Result<()> {
|
||||
#[derive(Serialize)]
|
||||
@@ -357,6 +360,8 @@ pub fn write_progress(
|
||||
dirs: u64,
|
||||
bytes: u64,
|
||||
errors: u64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
preview: Option<&'a [crate::scan_preview::Entry]>,
|
||||
}
|
||||
send(
|
||||
out,
|
||||
@@ -366,6 +371,7 @@ pub fn write_progress(
|
||||
dirs,
|
||||
bytes,
|
||||
errors,
|
||||
preview,
|
||||
},
|
||||
)?;
|
||||
out.flush()
|
||||
@@ -673,6 +679,7 @@ fn read_snapshot_with_progress(
|
||||
|| control.files.is_some()
|
||||
|| control.dirs.is_some()
|
||||
|| control.bytes.is_some()
|
||||
|| control.preview.is_some()
|
||||
{
|
||||
if let Some(directory) = control.directory {
|
||||
progress.directory = Some(directory);
|
||||
@@ -689,6 +696,15 @@ fn read_snapshot_with_progress(
|
||||
if let Some(errors) = control.errors {
|
||||
progress.errors = errors;
|
||||
}
|
||||
if let Some(entries) = control.preview
|
||||
&& !entries.is_empty()
|
||||
{
|
||||
progress.preview =
|
||||
Some(Arc::new(crate::scan_preview::Preview {
|
||||
entries,
|
||||
directory: progress.directory.clone(),
|
||||
}));
|
||||
}
|
||||
progress.updated = Some(Instant::now());
|
||||
*shared.lock().expect("remote progress lock") =
|
||||
progress.clone();
|
||||
|
||||
@@ -368,6 +368,7 @@ impl ScanHandle {
|
||||
skip_oracle,
|
||||
on_dir_start: None,
|
||||
on_dir_tally: Some(on_dir_tally),
|
||||
on_dir_complete: None,
|
||||
},
|
||||
)
|
||||
.map(|walk| walk.arena);
|
||||
@@ -701,6 +702,7 @@ pub fn scan(root: &Path, options: ScanOptions) -> io::Result<Node> {
|
||||
skip_oracle: None,
|
||||
on_dir_start: None,
|
||||
on_dir_tally: None,
|
||||
on_dir_complete: None,
|
||||
},
|
||||
)?;
|
||||
Ok(arena_to_node(
|
||||
@@ -1079,6 +1081,7 @@ mod tests {
|
||||
skip_oracle: None,
|
||||
on_dir_start: None,
|
||||
on_dir_tally: None,
|
||||
on_dir_complete: None,
|
||||
},
|
||||
)
|
||||
.expect("inner")
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
//! Bounded, non-actionable overview; never a replacement filesystem tree.
|
||||
use rustc_hash::FxHashMap;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// A measured contribution, not the total size of an unfinished directory.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
pub struct Entry {
|
||||
pub name: String,
|
||||
pub bytes: u64,
|
||||
pub files: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
pub struct Preview {
|
||||
pub entries: Vec<Entry>,
|
||||
pub directory: Option<std::path::PathBuf>,
|
||||
@@ -18,14 +19,14 @@ pub struct Preview {
|
||||
/// Keep top-level arrival order, rather than re-ranking the view every tick.
|
||||
/// Extra names share one overflow bucket; no tree or per-file copy is kept.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Builder {
|
||||
pub struct Builder {
|
||||
index: FxHashMap<String, usize>,
|
||||
entries: Vec<Entry>,
|
||||
directory: Option<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
impl Builder {
|
||||
pub(crate) fn add(&mut self, name: Option<&str>, bytes: u64, files: u64) {
|
||||
pub fn add(&mut self, name: Option<&str>, bytes: u64, files: u64) {
|
||||
const LIMIT: usize = 128;
|
||||
let key = name.unwrap_or("");
|
||||
let index = if let Some(index) = self.index.get(key) {
|
||||
@@ -52,11 +53,12 @@ impl Builder {
|
||||
entry.files = entry.files.saturating_add(files);
|
||||
}
|
||||
|
||||
pub(crate) fn directory(&mut self, path: &std::path::Path) {
|
||||
pub fn directory(&mut self, path: &std::path::Path) {
|
||||
path.clone_into(self.directory.get_or_insert_default());
|
||||
}
|
||||
|
||||
pub(crate) fn snapshot(&self) -> Preview {
|
||||
#[must_use]
|
||||
pub fn snapshot(&self) -> Preview {
|
||||
Preview {
|
||||
entries: self.entries.clone(),
|
||||
directory: self.directory.clone(),
|
||||
|
||||
+176
-130
@@ -247,12 +247,35 @@ impl CacheDb {
|
||||
options: &ScanOptions,
|
||||
scanned_at: u64,
|
||||
) -> Result<(), FallbackReason> {
|
||||
self.store_subtrees_batch(host, &[arena], options, scanned_at)
|
||||
}
|
||||
|
||||
/// Persist a batch of completed subtrees inside a single `redb` write
|
||||
/// transaction (used for cadence-based incremental checkpointing during
|
||||
/// long walks so interrupted scans resume from already-finished folders).
|
||||
#[cfg(feature = "cache-db")]
|
||||
pub fn store_subtrees_batch(
|
||||
&self,
|
||||
host: &HostKey,
|
||||
arenas: &[&TreeArena],
|
||||
options: &ScanOptions,
|
||||
scanned_at: u64,
|
||||
) -> Result<(), FallbackReason> {
|
||||
if arenas.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
check_cache_headroom(&self.path, self.min_free_headroom)?;
|
||||
|
||||
let host_key = host.as_db_key();
|
||||
let canonical_root = normalize_path(arena.root_path());
|
||||
let counts = arena.subtree_counts();
|
||||
let shard_nodes = choose_shard_roots(arena, &counts);
|
||||
let planned: Vec<(String, Vec<NodeId>, &TreeArena)> = arenas
|
||||
.iter()
|
||||
.map(|&arena| {
|
||||
let canonical_root = normalize_path(arena.root_path());
|
||||
let counts = arena.subtree_counts();
|
||||
let shard_nodes = choose_shard_roots(arena, &counts);
|
||||
(canonical_root, shard_nodes, arena)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let txn = self
|
||||
.db
|
||||
@@ -280,71 +303,13 @@ impl CacheDb {
|
||||
|
||||
let mut next_id = read_next_id(&meta)?;
|
||||
|
||||
// Upsert host record.
|
||||
// Upsert host record once per batch transaction.
|
||||
let host_record = make_host_record(host, &host_key, scanned_at);
|
||||
let host_bytes = encode_framed(&host_record);
|
||||
hosts
|
||||
.insert(host_key.as_str(), host_bytes.as_slice())
|
||||
.map_err(|e| classify_redb_error(&e.into()))?;
|
||||
|
||||
// Ensure ancestor chain exists from filesystem root down to
|
||||
// `canonical_root`.
|
||||
let root_dir_id = ensure_ancestor_chain(
|
||||
&host_key,
|
||||
&canonical_root,
|
||||
&mut next_id,
|
||||
&mut path_to_dir,
|
||||
&mut dir_index,
|
||||
&mut dir_children,
|
||||
)?;
|
||||
|
||||
// Remove old descendants and old chunk(s) under `root_dir_id` so
|
||||
// deleted directories never linger as ghost shards.
|
||||
purge_descendants(
|
||||
&host_key,
|
||||
root_dir_id,
|
||||
&mut path_to_dir,
|
||||
&mut dir_index,
|
||||
&mut dir_children,
|
||||
&mut chunks,
|
||||
)?;
|
||||
|
||||
// Allocate deterministic dir_ids and chunk_ids for every shard
|
||||
// root in this arena.
|
||||
let mut node_to_dir_id: FxHashMap<NodeId, u64> =
|
||||
FxHashMap::default();
|
||||
let mut node_to_chunk_id: FxHashMap<NodeId, u64> =
|
||||
FxHashMap::default();
|
||||
node_to_dir_id.insert(arena.root(), root_dir_id);
|
||||
node_to_chunk_id.insert(arena.root(), alloc_id(&mut next_id));
|
||||
|
||||
for &shard_node in &shard_nodes {
|
||||
if shard_node == arena.root() {
|
||||
continue;
|
||||
}
|
||||
let shard_path = normalize_path(&arena.path_of(shard_node));
|
||||
let dir_id = if let Some(existing) = path_to_dir
|
||||
.get((host_key.as_str(), shard_path.as_str()))
|
||||
.map_err(|e| classify_redb_error(&e.into()))?
|
||||
.map(|v| v.value())
|
||||
{
|
||||
existing
|
||||
} else {
|
||||
alloc_id(&mut next_id)
|
||||
};
|
||||
node_to_dir_id.insert(shard_node, dir_id);
|
||||
node_to_chunk_id.insert(shard_node, alloc_id(&mut next_id));
|
||||
}
|
||||
|
||||
// Determine parent dir_id for each shard root (linking through
|
||||
// nearest ancestor shard root, creating intermediate stubs if
|
||||
// needed so whole-FS navigation works cleanly).
|
||||
let root_parent_id = dir_index
|
||||
.get((host_key.as_str(), root_dir_id))
|
||||
.map_err(|e| classify_redb_error(&e.into()))?
|
||||
.and_then(|v| decode_framed::<DirIndexEntry>(v.value()).ok())
|
||||
.map_or(0, |entry| entry.parent_id);
|
||||
|
||||
let coverage = if options.max_depth.is_some() {
|
||||
Coverage::Shallow as u32
|
||||
} else {
|
||||
@@ -354,80 +319,148 @@ impl CacheDb {
|
||||
.max_depth
|
||||
.map_or(0, |d| d.min(u32::MAX as usize) as u32);
|
||||
|
||||
for &shard_node in &shard_nodes {
|
||||
let dir_id = node_to_dir_id[&shard_node];
|
||||
let chunk_id = node_to_chunk_id[&shard_node];
|
||||
let shard_path = normalize_path(&arena.path_of(shard_node));
|
||||
for (canonical_root, shard_nodes, arena) in planned {
|
||||
// Ensure ancestor chain exists from filesystem root down to
|
||||
// `canonical_root`.
|
||||
let root_dir_id = ensure_ancestor_chain(
|
||||
&host_key,
|
||||
&canonical_root,
|
||||
&mut next_id,
|
||||
&mut path_to_dir,
|
||||
&mut dir_index,
|
||||
&mut dir_children,
|
||||
)?;
|
||||
|
||||
let parent_dir_id = if shard_node == arena.root() {
|
||||
root_parent_id
|
||||
} else {
|
||||
let parent_path = parent_normalized_path(&shard_path);
|
||||
match parent_path {
|
||||
Some(p) => ensure_ancestor_chain(
|
||||
&host_key,
|
||||
&p,
|
||||
&mut next_id,
|
||||
&mut path_to_dir,
|
||||
&mut dir_index,
|
||||
&mut dir_children,
|
||||
)?,
|
||||
None => 0,
|
||||
// Remove old descendants and old chunk(s) under `root_dir_id`
|
||||
// so deleted directories never linger as ghost shards.
|
||||
purge_descendants(
|
||||
&host_key,
|
||||
root_dir_id,
|
||||
&mut path_to_dir,
|
||||
&mut dir_index,
|
||||
&mut dir_children,
|
||||
&mut chunks,
|
||||
)?;
|
||||
|
||||
// Allocate deterministic dir_ids and chunk_ids for every shard
|
||||
// root in this arena.
|
||||
let mut node_to_dir_id: FxHashMap<NodeId, u64> =
|
||||
FxHashMap::default();
|
||||
let mut node_to_chunk_id: FxHashMap<NodeId, u64> =
|
||||
FxHashMap::default();
|
||||
node_to_dir_id.insert(arena.root(), root_dir_id);
|
||||
node_to_chunk_id.insert(arena.root(), alloc_id(&mut next_id));
|
||||
|
||||
for &shard_node in &shard_nodes {
|
||||
if shard_node == arena.root() {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let shard_path = normalize_path(&arena.path_of(shard_node));
|
||||
let dir_id = if let Some(existing) = path_to_dir
|
||||
.get((host_key.as_str(), shard_path.as_str()))
|
||||
.map_err(|e| classify_redb_error(&e.into()))?
|
||||
.map(|v| v.value())
|
||||
{
|
||||
existing
|
||||
} else {
|
||||
alloc_id(&mut next_id)
|
||||
};
|
||||
node_to_dir_id.insert(shard_node, dir_id);
|
||||
node_to_chunk_id.insert(shard_node, alloc_id(&mut next_id));
|
||||
}
|
||||
|
||||
// Encode chunk stopping at nested shard roots.
|
||||
let chunk = encode_subtree_chunk(
|
||||
arena,
|
||||
shard_node,
|
||||
chunk_id,
|
||||
dir_id,
|
||||
scanned_at,
|
||||
&node_to_dir_id,
|
||||
);
|
||||
let chunk_bytes = encode_framed(&chunk);
|
||||
chunks
|
||||
.insert(
|
||||
(host_key.as_str(), chunk_id),
|
||||
chunk_bytes.as_slice(),
|
||||
)
|
||||
.map_err(|e| classify_redb_error(&e.into()))?;
|
||||
let root_parent_id = dir_index
|
||||
.get((host_key.as_str(), root_dir_id))
|
||||
.map_err(|e| classify_redb_error(&e.into()))?
|
||||
.and_then(|v| {
|
||||
decode_framed::<DirIndexEntry>(v.value()).ok()
|
||||
})
|
||||
.map_or(0, |entry| entry.parent_id);
|
||||
|
||||
let node = arena.node(shard_node);
|
||||
let dir_ts = if node.scanned_at > 0 {
|
||||
node.scanned_at
|
||||
} else {
|
||||
scanned_at
|
||||
};
|
||||
let entry = DirIndexEntry {
|
||||
dir_id,
|
||||
parent_id: parent_dir_id,
|
||||
name: leaf_name(&shard_path).to_owned(),
|
||||
scanned_at_unix: dir_ts,
|
||||
coverage,
|
||||
scanned_max_depth: max_depth_u32,
|
||||
options_mask: options.cache_topology_mask(),
|
||||
mount_dev: 0,
|
||||
dir_mtime: node.modified,
|
||||
chunk_id,
|
||||
allocated_bytes: node.allocated_bytes,
|
||||
apparent_bytes: node.apparent_bytes,
|
||||
files: node.files,
|
||||
dirs: node.dirs,
|
||||
newest_mtime: node.modified,
|
||||
};
|
||||
let entry_bytes = encode_framed(&entry);
|
||||
for &shard_node in &shard_nodes {
|
||||
let dir_id = node_to_dir_id[&shard_node];
|
||||
let chunk_id = node_to_chunk_id[&shard_node];
|
||||
let shard_path = normalize_path(&arena.path_of(shard_node));
|
||||
|
||||
path_to_dir
|
||||
.insert((host_key.as_str(), shard_path.as_str()), dir_id)
|
||||
.map_err(|e| classify_redb_error(&e.into()))?;
|
||||
dir_index
|
||||
.insert((host_key.as_str(), dir_id), entry_bytes.as_slice())
|
||||
.map_err(|e| classify_redb_error(&e.into()))?;
|
||||
if parent_dir_id != 0 {
|
||||
dir_children
|
||||
.insert((host_key.as_str(), parent_dir_id, dir_id), ())
|
||||
let parent_dir_id = if shard_node == arena.root() {
|
||||
root_parent_id
|
||||
} else {
|
||||
let parent_path = parent_normalized_path(&shard_path);
|
||||
match parent_path {
|
||||
Some(p) => ensure_ancestor_chain(
|
||||
&host_key,
|
||||
&p,
|
||||
&mut next_id,
|
||||
&mut path_to_dir,
|
||||
&mut dir_index,
|
||||
&mut dir_children,
|
||||
)?,
|
||||
None => 0,
|
||||
}
|
||||
};
|
||||
|
||||
// Encode chunk stopping at nested shard roots.
|
||||
let chunk = encode_subtree_chunk(
|
||||
arena,
|
||||
shard_node,
|
||||
chunk_id,
|
||||
dir_id,
|
||||
scanned_at,
|
||||
&node_to_dir_id,
|
||||
);
|
||||
let chunk_bytes = encode_framed(&chunk);
|
||||
chunks
|
||||
.insert(
|
||||
(host_key.as_str(), chunk_id),
|
||||
chunk_bytes.as_slice(),
|
||||
)
|
||||
.map_err(|e| classify_redb_error(&e.into()))?;
|
||||
|
||||
let node = arena.node(shard_node);
|
||||
let dir_ts = if node.scanned_at > 0 {
|
||||
node.scanned_at
|
||||
} else {
|
||||
scanned_at
|
||||
};
|
||||
let entry = DirIndexEntry {
|
||||
dir_id,
|
||||
parent_id: parent_dir_id,
|
||||
name: leaf_name(&shard_path).to_owned(),
|
||||
scanned_at_unix: dir_ts,
|
||||
coverage,
|
||||
scanned_max_depth: max_depth_u32,
|
||||
options_mask: options.cache_topology_mask(),
|
||||
mount_dev: 0,
|
||||
dir_mtime: node.modified,
|
||||
chunk_id,
|
||||
allocated_bytes: node.allocated_bytes,
|
||||
apparent_bytes: node.apparent_bytes,
|
||||
files: node.files,
|
||||
dirs: node.dirs,
|
||||
newest_mtime: node.modified,
|
||||
};
|
||||
let entry_bytes = encode_framed(&entry);
|
||||
|
||||
path_to_dir
|
||||
.insert(
|
||||
(host_key.as_str(), shard_path.as_str()),
|
||||
dir_id,
|
||||
)
|
||||
.map_err(|e| classify_redb_error(&e.into()))?;
|
||||
dir_index
|
||||
.insert(
|
||||
(host_key.as_str(), dir_id),
|
||||
entry_bytes.as_slice(),
|
||||
)
|
||||
.map_err(|e| classify_redb_error(&e.into()))?;
|
||||
if parent_dir_id != 0 {
|
||||
dir_children
|
||||
.insert(
|
||||
(host_key.as_str(), parent_dir_id, dir_id),
|
||||
(),
|
||||
)
|
||||
.map_err(|e| classify_redb_error(&e.into()))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -452,6 +485,19 @@ impl CacheDb {
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "cache-db"))]
|
||||
pub fn store_subtrees_batch(
|
||||
&self,
|
||||
_host: &HostKey,
|
||||
_arenas: &[&TreeArena],
|
||||
_options: &ScanOptions,
|
||||
_scanned_at: u64,
|
||||
) -> Result<(), FallbackReason> {
|
||||
Err(FallbackReason::DatabaseUnavailable {
|
||||
detail: "compiled without cache-db feature".to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Load a cached subtree rooted at `root_path` (supporting direct hits,
|
||||
/// narrowing into a cached ancestor shard, and partial ancestor hits).
|
||||
#[cfg(feature = "cache-db")]
|
||||
|
||||
@@ -23,10 +23,16 @@ use crate::types::{
|
||||
HostKey, Priority, ScanOptions, ScanStats, StorageMode, unix_now,
|
||||
};
|
||||
use crate::walk::{
|
||||
DirStartHook, DirTallyHook, MapSkipOracle, PauseGate, ShardLoader,
|
||||
SkipOracle, WalkConfig, WalkProgress, walk_parallel,
|
||||
DirCompleteHook, DirStartHook, DirTallyHook, MapSkipOracle, PauseGate,
|
||||
ShardLoader, SkipOracle, WalkConfig, WalkProgress, walk_parallel,
|
||||
};
|
||||
|
||||
/// How often completed subtrees are flushed to `scan-cache.redb` in one
|
||||
/// batched write transaction during a background walk.
|
||||
const CHECKPOINT_CADENCE: Duration = Duration::from_secs(4);
|
||||
/// Maximum queued completed subtrees before forcing an immediate batch flush.
|
||||
const CHECKPOINT_MAX_BATCH: usize = 32;
|
||||
|
||||
/// A tree snapshot emitted by a [`ScanSession`].
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ScanSnapshot {
|
||||
@@ -1026,7 +1032,39 @@ fn run_background_walk(
|
||||
}
|
||||
});
|
||||
|
||||
let outcome = match walk_parallel(
|
||||
// Spawn a dedicated non-blocking checkpoint writer thread so scan workers
|
||||
// never stall on DB fsyncs while completed depth-1 and large depth-2
|
||||
// subtrees are committed on a cadence (4 s / 32 subtrees). If the walk is
|
||||
// cancelled or disconnected midway, everything already completed is safely
|
||||
// in `scan-cache.redb` and skipped on the next resume.
|
||||
let (cp_tx, cp_rx) = mpsc::channel::<(PathBuf, usize, Arc<TreeArena>)>();
|
||||
let checkpoint_worker = {
|
||||
let storage = Arc::clone(storage);
|
||||
let host = host.clone();
|
||||
let options = *options;
|
||||
let event_tx = event_tx.clone();
|
||||
thread::Builder::new()
|
||||
.name("disktree-checkpoint".into())
|
||||
.spawn(move || {
|
||||
run_checkpoint_writer(
|
||||
&cp_rx, &storage, &host, &options, &event_tx,
|
||||
);
|
||||
})
|
||||
.ok()
|
||||
};
|
||||
let on_dir_complete: Option<DirCompleteHook> =
|
||||
checkpoint_worker.as_ref().map(|_| {
|
||||
let tx = cp_tx.clone();
|
||||
let hook: DirCompleteHook = Arc::new(
|
||||
move |path: PathBuf, depth: usize, arena: Arc<TreeArena>| {
|
||||
let _ = tx.send((path, depth, arena));
|
||||
},
|
||||
);
|
||||
hook
|
||||
});
|
||||
drop(cp_tx);
|
||||
|
||||
let outcome = walk_parallel(
|
||||
walk_root,
|
||||
WalkConfig {
|
||||
options,
|
||||
@@ -1036,8 +1074,18 @@ fn run_background_walk(
|
||||
skip_oracle: Some(oracle),
|
||||
on_dir_start: Some(on_dir_start),
|
||||
on_dir_tally,
|
||||
on_dir_complete,
|
||||
},
|
||||
) {
|
||||
);
|
||||
|
||||
// Join the checkpoint writer BEFORE final root persistence (or exit on
|
||||
// cancel) so any completed subtrees queued so far are durably flushed and
|
||||
// there is no redb write-lock contention with the final root commit.
|
||||
if let Some(handle) = checkpoint_worker {
|
||||
let _ = handle.join();
|
||||
}
|
||||
|
||||
let outcome = match outcome {
|
||||
Ok(outcome) => outcome,
|
||||
Err(error) => {
|
||||
let _ = event_tx.send(ScanEvent::Error {
|
||||
@@ -1124,6 +1172,7 @@ fn run_priority_loop(
|
||||
skip_oracle: None,
|
||||
on_dir_start: None,
|
||||
on_dir_tally: None,
|
||||
on_dir_complete: None,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1170,6 +1219,91 @@ fn run_priority_loop(
|
||||
}
|
||||
}
|
||||
|
||||
fn run_checkpoint_writer(
|
||||
rx: &Receiver<(PathBuf, usize, Arc<TreeArena>)>,
|
||||
storage: &Arc<Mutex<StorageState>>,
|
||||
host: &HostKey,
|
||||
options: &ScanOptions,
|
||||
event_tx: &Sender<ScanEvent>,
|
||||
) {
|
||||
let mut pending: Vec<(PathBuf, usize, Arc<TreeArena>)> = Vec::new();
|
||||
let mut last_flush = Instant::now();
|
||||
|
||||
let flush = |pending: &mut Vec<(PathBuf, usize, Arc<TreeArena>)>| {
|
||||
if pending.is_empty() {
|
||||
return;
|
||||
}
|
||||
let now = unix_now();
|
||||
let db_opt = {
|
||||
let mut guard = storage
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(cache) = guard.mem_cache_mut() {
|
||||
for (path, _, arena) in pending.iter() {
|
||||
cache.insert(
|
||||
(host.as_db_key(), path.clone()),
|
||||
(Arc::clone(arena), now, options.cache_topology_mask()),
|
||||
);
|
||||
}
|
||||
}
|
||||
guard.db()
|
||||
};
|
||||
if let Some(db) = db_opt {
|
||||
let refs: Vec<&TreeArena> =
|
||||
pending.iter().map(|(_, _, a)| a.as_ref()).collect();
|
||||
if let Err(reason) =
|
||||
db.store_subtrees_batch(host, &refs, options, now)
|
||||
{
|
||||
let from = downgrade_storage(storage, reason.clone());
|
||||
let _ = event_tx.send(ScanEvent::StorageFallback {
|
||||
from,
|
||||
to: ActiveStorageMode::InMemory,
|
||||
reason,
|
||||
});
|
||||
}
|
||||
}
|
||||
for (path, depth, arena) in pending.drain(..) {
|
||||
if depth == 1 {
|
||||
let _ = event_tx.send(ScanEvent::SubtreeRefreshed {
|
||||
path,
|
||||
arena,
|
||||
priority: Priority::Background,
|
||||
scanned_at: now,
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
loop {
|
||||
let wait = if pending.is_empty() {
|
||||
CHECKPOINT_CADENCE
|
||||
} else {
|
||||
CHECKPOINT_CADENCE.saturating_sub(last_flush.elapsed())
|
||||
};
|
||||
match rx.recv_timeout(wait) {
|
||||
Ok(item) => {
|
||||
pending.push(item);
|
||||
if pending.len() >= CHECKPOINT_MAX_BATCH
|
||||
|| last_flush.elapsed() >= CHECKPOINT_CADENCE
|
||||
{
|
||||
flush(&mut pending);
|
||||
last_flush = Instant::now();
|
||||
}
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => {
|
||||
if !pending.is_empty() {
|
||||
flush(&mut pending);
|
||||
last_flush = Instant::now();
|
||||
}
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => {
|
||||
flush(&mut pending);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn persist_arena(
|
||||
storage: &Arc<Mutex<StorageState>>,
|
||||
host: &HostKey,
|
||||
@@ -1576,4 +1710,75 @@ mod tests {
|
||||
.expect("second");
|
||||
assert_eq!(second.stats.apparent_bytes, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incremental_checkpoint_resumes_by_skipping_completed_subtrees() {
|
||||
let temp = tempfile::tempdir().expect("tempdir");
|
||||
let db_path = temp.path().join("checkpoint.redb");
|
||||
let root = temp.path().join("root");
|
||||
let alpha = root.join("alpha");
|
||||
let beta = root.join("beta");
|
||||
fs::create_dir_all(&alpha).expect("mkdir alpha");
|
||||
fs::create_dir_all(&beta).expect("mkdir beta");
|
||||
fs::write(alpha.join("a.bin"), vec![1u8; 200]).expect("write a");
|
||||
fs::write(beta.join("b.bin"), vec![2u8; 300]).expect("write b");
|
||||
|
||||
let policy = CachePolicy {
|
||||
min_free_headroom: 0,
|
||||
..CachePolicy::default()
|
||||
};
|
||||
let scanner = Scanner::new(
|
||||
StorageMode::Persistent {
|
||||
path: db_path,
|
||||
strict: true,
|
||||
},
|
||||
policy,
|
||||
)
|
||||
.expect("scanner");
|
||||
|
||||
// Checkpoint ONLY `alpha` (as happens when a long walk is interrupted
|
||||
// after `alpha` finished and flushed to the DB, while `beta` is still
|
||||
// an unscanned hole).
|
||||
let _ = scanner
|
||||
.scan_blocking(&alpha, ScanOptions::default(), policy, false)
|
||||
.expect("checkpoint alpha");
|
||||
|
||||
// Opening the parent `root` should emit a Partial cached snapshot
|
||||
// containing `alpha`, skip re-walking `alpha`, walk the unscanned hole
|
||||
// `beta`, and emit the complete Live snapshot with both.
|
||||
let session = scanner
|
||||
.open_with(HostKey::Local, root, ScanOptions::default(), policy)
|
||||
.expect("open root");
|
||||
|
||||
let mut saw_partial = false;
|
||||
let mut live_snap = None;
|
||||
while let Ok(ev) = session.recv_timeout(Duration::from_secs(5)) {
|
||||
match ev {
|
||||
ScanEvent::Snapshot(snap) => match snap.freshness {
|
||||
Freshness::Partial { .. } => {
|
||||
assert_eq!(
|
||||
snap.arena.node(snap.arena.root()).apparent_bytes,
|
||||
200
|
||||
);
|
||||
saw_partial = true;
|
||||
}
|
||||
Freshness::Live { .. } => {
|
||||
live_snap = Some(snap);
|
||||
}
|
||||
Freshness::Fresh { .. } | Freshness::Stale { .. } => {}
|
||||
},
|
||||
ScanEvent::Finished => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert!(saw_partial, "partial checkpoint should surface immediately");
|
||||
let live = live_snap.expect("live snapshot");
|
||||
assert!(
|
||||
live.stats.skipped_fresh_dirs >= 1,
|
||||
"completed checkpoint `alpha` should be skipped on resume, stats: {:?}",
|
||||
live.stats
|
||||
);
|
||||
assert_eq!(live.stats.apparent_bytes, 500);
|
||||
assert_eq!(live.stats.files, 2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,6 +36,12 @@ pub type DirStartHook = Arc<dyn Fn(&Path) + Send + Sync>;
|
||||
/// `(dir_path, allocated_bytes, apparent_bytes, files)`.
|
||||
pub type DirTallyHook = Arc<dyn Fn(&Path, u64, u64, u64) + Send + Sync>;
|
||||
|
||||
/// Callback invoked when a complete, uncancelled subtree finishes walking
|
||||
/// (used for cadence-based incremental DB checkpointing and live UI updates):
|
||||
/// `(dir_path, depth, materialized_arena)`.
|
||||
pub type DirCompleteHook =
|
||||
Arc<dyn Fn(PathBuf, usize, Arc<TreeArena>) + Send + Sync>;
|
||||
|
||||
/// Callback loading a cached shard by `dir_id` and path.
|
||||
pub type ShardLoader =
|
||||
Arc<dyn Fn(u64, &Path) -> Option<TreeArena> + Send + Sync>;
|
||||
@@ -272,6 +278,10 @@ pub struct WalkConfig<'a> {
|
||||
/// Optional hook invoked after a directory's direct files are tallied (for
|
||||
/// live treemap previews during cold scans).
|
||||
pub on_dir_tally: Option<DirTallyHook>,
|
||||
/// Optional hook invoked when a complete `depth == 1` (or large `depth == 2`)
|
||||
/// subtree finishes walking, for incremental checkpointing and live UI
|
||||
/// updates without blocking scan workers.
|
||||
pub on_dir_complete: Option<DirCompleteHook>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for WalkConfig<'_> {
|
||||
@@ -366,6 +376,7 @@ pub fn walk_parallel(
|
||||
skip_oracle: config.skip_oracle,
|
||||
on_dir_start: config.on_dir_start,
|
||||
on_dir_tally: config.on_dir_tally,
|
||||
on_dir_complete: config.on_dir_complete,
|
||||
#[cfg(windows)]
|
||||
volume,
|
||||
deferred_stale: Mutex::new(Vec::new()),
|
||||
@@ -590,7 +601,7 @@ fn run_deferred_stale(ctx: &Arc<WalkContext>, sub: &Arc<PendingDir>) {
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.push(BuiltChild::Grafted(Box::new(GraftedChild {
|
||||
name: sub.name.clone(),
|
||||
arena: reused,
|
||||
arena: Arc::new(reused),
|
||||
hidden: sub.hidden,
|
||||
lossy_name: sub.lossy_name,
|
||||
})));
|
||||
@@ -615,6 +626,7 @@ struct WalkContext {
|
||||
skip_oracle: Option<Arc<dyn SkipOracle>>,
|
||||
on_dir_start: Option<DirStartHook>,
|
||||
on_dir_tally: Option<DirTallyHook>,
|
||||
on_dir_complete: Option<DirCompleteHook>,
|
||||
#[cfg(windows)]
|
||||
volume: Option<u32>,
|
||||
/// Stale subdirectories (already have cached data) deferred until every
|
||||
@@ -634,6 +646,9 @@ struct PendingDir {
|
||||
hidden: bool,
|
||||
lossy_name: bool,
|
||||
read_error: AtomicBool,
|
||||
/// Set if this directory or any descendant was cut short by cancellation.
|
||||
/// Incomplete subtrees are never incrementally checkpointed to the DB.
|
||||
incomplete: AtomicBool,
|
||||
/// Starts at `1` (the `+1` sentinel for this directory's own scan).
|
||||
pending: AtomicUsize,
|
||||
children: Mutex<Vec<BuiltChild>>,
|
||||
@@ -658,6 +673,7 @@ impl PendingDir {
|
||||
hidden,
|
||||
lossy_name,
|
||||
read_error: AtomicBool::new(false),
|
||||
incomplete: AtomicBool::new(false),
|
||||
pending: AtomicUsize::new(1),
|
||||
children: Mutex::new(Vec::new()),
|
||||
}
|
||||
@@ -672,7 +688,7 @@ pub(crate) enum BuiltChild {
|
||||
|
||||
pub(crate) struct GraftedChild {
|
||||
pub name: String,
|
||||
pub arena: TreeArena,
|
||||
pub arena: Arc<TreeArena>,
|
||||
pub hidden: bool,
|
||||
pub lossy_name: bool,
|
||||
}
|
||||
@@ -901,6 +917,7 @@ fn scan_dir(scope: &Scope<'_>, ctx: &Arc<WalkContext>, dir: &Arc<PendingDir>) {
|
||||
}
|
||||
|
||||
if ctx.cancel.load(Ordering::Relaxed) {
|
||||
dir.incomplete.store(true, Ordering::Relaxed);
|
||||
complete_one(ctx, dir);
|
||||
return;
|
||||
}
|
||||
@@ -932,6 +949,7 @@ fn scan_dir(scope: &Scope<'_>, ctx: &Arc<WalkContext>, dir: &Arc<PendingDir>) {
|
||||
|
||||
for entry_res in entries {
|
||||
if ctx.cancel.load(Ordering::Relaxed) {
|
||||
dir.incomplete.store(true, Ordering::Relaxed);
|
||||
break;
|
||||
}
|
||||
let entry = match entry_res {
|
||||
@@ -1089,7 +1107,7 @@ fn scan_dir(scope: &Scope<'_>, ctx: &Arc<WalkContext>, dir: &Arc<PendingDir>) {
|
||||
local_children.push(BuiltChild::Grafted(Box::new(
|
||||
GraftedChild {
|
||||
name,
|
||||
arena: reused,
|
||||
arena: Arc::new(reused),
|
||||
hidden,
|
||||
lossy_name,
|
||||
},
|
||||
@@ -1225,6 +1243,7 @@ fn complete_one(ctx: &WalkContext, start: &Arc<PendingDir>) {
|
||||
if current.pending.fetch_sub(1, Ordering::AcqRel) != 1 {
|
||||
return;
|
||||
}
|
||||
let incomplete = current.incomplete.load(Ordering::Relaxed);
|
||||
let children = std::mem::take(
|
||||
&mut *current
|
||||
.children
|
||||
@@ -1240,11 +1259,37 @@ fn complete_one(ctx: &WalkContext, start: &Arc<PendingDir>) {
|
||||
children,
|
||||
};
|
||||
if let Some(parent) = current.parent.as_ref().map(Arc::clone) {
|
||||
if incomplete {
|
||||
parent.incomplete.store(true, Ordering::Relaxed);
|
||||
}
|
||||
let child = if !incomplete
|
||||
&& !ctx.cancel.load(Ordering::Relaxed)
|
||||
&& let Some(hook) = &ctx.on_dir_complete
|
||||
&& should_checkpoint_dir(current.depth, &built)
|
||||
{
|
||||
let scanned_at = unix_now();
|
||||
let mut arena =
|
||||
materialize_arena(current.path.clone(), built, scanned_at);
|
||||
arena.aggregate(
|
||||
ctx.options.dedup_hardlinks,
|
||||
ctx.options.include_hidden,
|
||||
);
|
||||
let arena = Arc::new(arena);
|
||||
hook(current.path.clone(), current.depth, Arc::clone(&arena));
|
||||
BuiltChild::Grafted(Box::new(GraftedChild {
|
||||
name: current.name.clone(),
|
||||
arena,
|
||||
hidden: current.hidden,
|
||||
lossy_name: current.lossy_name,
|
||||
}))
|
||||
} else {
|
||||
BuiltChild::Dir(Box::new(built))
|
||||
};
|
||||
parent
|
||||
.children
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.push(BuiltChild::Dir(Box::new(built)));
|
||||
.push(child);
|
||||
current = parent;
|
||||
} else {
|
||||
*ctx.finished_root
|
||||
@@ -1256,6 +1301,43 @@ fn complete_one(ctx: &WalkContext, start: &Arc<PendingDir>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimum node count before a `depth == 2` directory is checkpointed
|
||||
/// independently (every `depth == 1` directory is always eligible).
|
||||
const DEPTH2_CHECKPOINT_THRESHOLD: usize = 512;
|
||||
|
||||
fn should_checkpoint_dir(depth: usize, built: &BuiltNode) -> bool {
|
||||
match depth {
|
||||
1 => true,
|
||||
2 => subtree_has_at_least(built, DEPTH2_CHECKPOINT_THRESHOLD),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn subtree_has_at_least(root: &BuiltNode, threshold: usize) -> bool {
|
||||
let mut count = 0usize;
|
||||
let mut stack: Vec<&BuiltNode> = vec![root];
|
||||
while let Some(node) = stack.pop() {
|
||||
for child in &node.children {
|
||||
match child {
|
||||
BuiltChild::Leaf(_) => {
|
||||
count += 1;
|
||||
}
|
||||
BuiltChild::Dir(dir) => {
|
||||
count += 1;
|
||||
stack.push(dir);
|
||||
}
|
||||
BuiltChild::Grafted(grafted) => {
|
||||
count = count.saturating_add(grafted.arena.len());
|
||||
}
|
||||
}
|
||||
if count >= threshold {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Convert the completed parallel tree into a flat [`TreeArena`] in one
|
||||
/// iterative pass.
|
||||
fn materialize_arena(
|
||||
@@ -1592,6 +1674,7 @@ mod tests {
|
||||
skip_oracle: Some(oracle),
|
||||
on_dir_start: Some(on_dir_start),
|
||||
on_dir_tally: None,
|
||||
on_dir_complete: None,
|
||||
},
|
||||
)
|
||||
.expect("walk");
|
||||
|
||||
Reference in New Issue
Block a user