feat(remote): back --stdio-v1 with remote host's own redb SWR cache and parallel scanner

This commit is contained in:
Tobi Lutke
2026-11-26 10:24:29 -05:00
parent b1edd42da8
commit 26b8a6da7b
5 changed files with 585 additions and 18 deletions
+35 -2
View File
@@ -2035,7 +2035,9 @@ impl Disktree {
disk: self.remote_disk,
options: self.options,
};
match disktree_core::remote::RemoteScan::spawn(host, &request) {
match disktree_core::remote::RemoteScan::spawn_with_refresh(
host, &request, true,
) {
Ok(handle) => {
self.active_scan =
Some(ActiveScan::Remote { handle, intent });
@@ -2162,7 +2164,11 @@ impl Disktree {
disk: self.remote_disk,
options: self.options,
};
match disktree_core::remote::RemoteScan::spawn(&host, &request) {
match disktree_core::remote::RemoteScan::spawn_with_refresh(
&host,
&request,
policy.force_refresh,
) {
Ok(handle) => {
self.active_scan =
Some(ActiveScan::Remote { handle, intent });
@@ -2262,6 +2268,33 @@ impl Disktree {
self.remote_progress = handle.progress();
let auth_url = self.remote_progress.auth_url.clone();
self.handle_auth_url(auth_url, cx);
if self.tree.is_none()
&& let Some(stale) =
self.remote_progress.stale_snapshot.clone()
{
let stale_dirs = stale.tree.dirs;
self.root_path.clone_from(&stale.header.root);
self.home.clone_from(&stale.header.home);
self.disk_root.clone_from(&stale.header.disk_root);
self.space = stale.header.space;
self.remote_platform.clone_from(&stale.header.platform);
self.update_remote_identity(stale.header.identity.clone());
self.device = self.remote.as_ref().map(|host| {
format!("{host} · read-only · cached (refreshing…)")
});
self.arena =
Some(Arc::new(disktree_core::scan::node_to_arena_at(
self.root_path.clone(),
&stale.tree,
1,
)));
self.freshness = Some(Freshness::Stale {
oldest_at: 1,
newest_at: 1,
stale_dirs,
});
self.install_tree(stale.tree.clone(), None, cx);
}
self.scan_preview.clone_from(&self.remote_progress.preview);
self.progress.files = self.remote_progress.files;
self.progress.dirs = self.remote_progress.dirs;
+233 -8
View File
@@ -1,14 +1,29 @@
//! Read-only `--stdio-v1` SSH remote protocol server.
//!
//! Invoked over SSH by `disktree` (auto-deployed from the portable binary or
//! found on the server's `PATH`). Enforces a 1 GiB address-space ceiling on
//! Linux, a 30-minute wall deadline, and exits immediately if the SSH pipe
//! closes so a blocked filesystem never outlives the connection.
//! found on the server's `PATH`). Uses `disktree-scanner`'s local `redb` SWR
//! cache on the remote host — the exact same database `disktree-cli` uses when
//! run locally — so warm scans return in milliseconds, stale scans stream
//! cached data first while revalidating in parallel, and cold scans walk in
//! parallel and populate the remote host's cache. Enforces a 1 GiB
//! address-space ceiling on Linux, a 30-minute wall deadline, and exits
//! immediately if the SSH pipe closes so a blocked filesystem never outlives
//! the connection.
use std::io::{self, BufReader, BufWriter, Read as _};
use std::time::Duration;
use std::io::{self, BufReader, BufWriter, Read as _, Write};
use std::path::PathBuf;
use std::time::{Duration, Instant};
use disktree_core::remote::{
Operation, Request, SessionRequest, write_arena, write_header,
write_heartbeat, write_marker,
};
use disktree_scanner::{
CachePolicy, Freshness, HostKey, ScanEvent, Scanner, StorageMode,
};
const STDOUT_BUFFER_BYTES: usize = 256 * 1024;
const HEARTBEAT_INTERVAL: Duration = Duration::from_millis(200);
pub fn serve_stdio_v1() -> io::Result<()> {
limit_resources()?;
@@ -47,12 +62,222 @@ pub fn serve_stdio_v1() -> io::Result<()> {
}
})?;
}
disktree_core::remote::serve_session(
session,
&mut BufWriter::with_capacity(STDOUT_BUFFER_BYTES, io::stdout().lock()),
let mut out =
BufWriter::with_capacity(STDOUT_BUFFER_BYTES, io::stdout().lock());
serve_with_remote_db(session, &mut out)
}
fn serve_with_remote_db(
session: SessionRequest,
out: &mut impl Write,
) -> io::Result<()> {
let SessionRequest {
operation,
watch_disconnect,
live_progress,
client_dedup,
live_tree,
stream_stale,
force_refresh,
} = session;
let request = match operation {
Operation::Discover { .. } => {
return disktree_core::remote::serve_session(
SessionRequest {
operation,
watch_disconnect,
live_progress,
client_dedup,
live_tree,
stream_stale,
force_refresh,
},
out,
);
}
Operation::Scan(request) => request,
};
if request.options.follow_links || !request.options.one_filesystem {
return Err(io::Error::other(
"Remote scans never follow symlinks or cross mounts; \
select that mount as a separate scan root.",
));
}
let home = std::env::home_dir();
let root = request
.root
.clone()
.or_else(|| home.clone())
.ok_or_else(|| io::Error::other("no remote home directory"))?;
let root = if request.disk {
disktree_core::space::volume_root_for(&root)
.unwrap_or_else(|| PathBuf::from("/"))
} else {
root
}
.canonicalize()?;
if !root.is_dir() {
return Err(io::Error::other("scan root is not a directory"));
}
// Use the remote host's own redb SWR cache DB when available. If storage
// cannot be opened at all, fall back to the bounded streaming walker.
let Ok(scanner) = Scanner::open_default().or_else(|_| {
Scanner::new(StorageMode::InMemory, CachePolicy::default())
}) else {
return disktree_core::remote::serve_session(
SessionRequest {
operation: Operation::Scan(request),
watch_disconnect,
live_progress,
client_dedup,
live_tree,
stream_stale,
force_refresh,
},
out,
);
};
write_header(&root, home, out)?;
serve_scan_from_scanner(
&scanner,
root,
&request,
StreamFlags {
live_progress,
client_dedup,
stream_stale,
force_refresh,
},
out,
)
}
#[derive(Clone, Copy)]
#[allow(
clippy::struct_excessive_bools,
reason = "protocol opt-in flags mirrored from SessionRequest"
)]
struct StreamFlags {
live_progress: bool,
client_dedup: bool,
stream_stale: bool,
force_refresh: bool,
}
fn serve_scan_from_scanner(
scanner: &Scanner,
root: PathBuf,
request: &Request,
flags: StreamFlags,
out: &mut impl Write,
) -> io::Result<()> {
let policy = CachePolicy {
force_refresh: flags.force_refresh,
stale_while_revalidate: true,
..CachePolicy::default()
};
let session = scanner.open_with(
HostKey::Local,
root,
request.options.to_scanner(),
policy,
)?;
let mut last_heartbeat = Instant::now();
let mut streamed_final = false;
let mut streamed_stale = false;
loop {
match session.recv_timeout(HEARTBEAT_INTERVAL) {
Ok(ScanEvent::Snapshot(snap)) => match snap.freshness {
Freshness::Partial { .. } => {}
Freshness::Fresh { .. } => {
write_arena(
&snap.arena,
&request.options,
flags.client_dedup,
out,
)?;
streamed_final = true;
}
Freshness::Stale { .. } => {
if flags.stream_stale && !streamed_stale {
write_arena(
&snap.arena,
&request.options,
flags.client_dedup,
out,
)?;
write_marker("stale", out)?;
streamed_stale = true;
last_heartbeat = Instant::now();
}
}
Freshness::Live { .. } => {
write_arena(
&snap.arena,
&request.options,
flags.client_dedup,
out,
)?;
out.flush()?;
streamed_final = true;
}
},
Ok(ScanEvent::Finished) => {
// Waiting until `Finished` guarantees the remote host's cache
// DB commit completed before `"done"` lets the client close
// stdin and exit this helper.
if !streamed_final {
return Err(io::Error::other(
"remote scan finished without producing a snapshot",
));
}
write_marker("done", out)?;
return Ok(());
}
Ok(ScanEvent::Error { message }) => {
return Err(io::Error::other(message));
}
Ok(
ScanEvent::SubtreeUpdating { .. }
| ScanEvent::SubtreeRefreshed { .. }
| ScanEvent::Progress { .. }
| ScanEvent::StorageFallback { .. },
) => {}
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
if flags.live_progress
&& last_heartbeat.elapsed() >= HEARTBEAT_INTERVAL
{
let dir = session
.progress()
.active_path
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone();
if let Some(dir) = dir {
write_heartbeat(&dir, out)?;
}
last_heartbeat = Instant::now();
}
}
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
if streamed_final {
write_marker("done", out)?;
return Ok(());
}
return Err(io::Error::other(
"remote scanner disconnected unexpectedly",
));
}
}
}
}
/// Kernel-enforced, not a sampled RSS check that can miss an allocation
/// burst. Keep this in the helper: never constrain the desktop process.
#[cfg(target_os = "linux")]
+63
View File
@@ -262,3 +262,66 @@ fn executable_discovers_roots_without_scanning_a_path() {
assert!(helper.0.wait().unwrap().success());
drop(input);
}
#[cfg(unix)]
#[test]
fn stdio_persists_to_remote_cache_db_and_revalidates_on_force_refresh() {
let dir = tempfile::tempdir().unwrap();
let cache_home = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("first.bin"), [0_u8; 100]).unwrap();
let run = |force_refresh: bool| {
let mut child = Command::new(env!("CARGO_BIN_EXE_disktree-cli"))
.arg("--stdio-v1")
.env("XDG_CACHE_HOME", cache_home.path())
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let mut input = child.stdin.take().unwrap();
let req = serde_json::json!({
"root": dir.path(),
"disk": false,
"options": ScanOptions {
apparent_size: true,
..ScanOptions::default()
},
"watch_disconnect": true,
"stream_stale": true,
"force_refresh": force_refresh,
});
serde_json::to_writer(&mut input, &req).unwrap();
input.write_all(b"\n").unwrap();
let snapshot =
read_snapshot(&mut BufReader::new(child.stdout.take().unwrap()))
.unwrap();
drop(input);
assert!(child.wait().unwrap().success());
snapshot
};
// 1. Cold scan populates the remote host's cache DB.
let first = run(false);
assert_eq!(first.tree.bytes, 100);
assert!(
cache_home.path().join("disktree/scan-cache.redb").exists(),
"remote helper should persist its redb cache DB"
);
// 2. Add a file; a warm request within TTL hits the remote DB directly.
std::fs::write(dir.path().join("second.bin"), [0_u8; 250]).unwrap();
let warm = run(false);
assert_eq!(
warm.tree.bytes, 100,
"warm scan should come straight from the remote cache DB"
);
// 3. Explicit force_refresh bypasses TTL, revalidates, and updates the DB.
let refreshed = run(true);
assert_eq!(refreshed.tree.bytes, 350);
// 4. Subsequent warm scan sees the newly persisted remote DB state.
let after = run(false);
assert_eq!(after.tree.bytes, 350);
}
+251 -8
View File
@@ -152,6 +152,13 @@ pub struct SessionRequest {
pub client_dedup: bool,
#[serde(default)]
pub live_tree: bool,
/// Opt-in: allow the remote host to stream a stale cached snapshot first
/// (terminated by `"stale"`) before revalidating and streaming `"done"`.
#[serde(default)]
pub stream_stale: bool,
/// Ask the remote host to bypass its own 15m cache TTL and revalidate.
#[serde(default)]
pub force_refresh: bool,
}
/// The target's root candidates, without walking or probing any of them.
@@ -182,7 +189,7 @@ pub fn read_roots(input: &mut impl BufRead) -> io::Result<Roots> {
Ok(roots)
}
#[derive(Debug, Serialize, Deserialize)]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Header {
version: u32,
pub root: PathBuf,
@@ -307,6 +314,195 @@ pub fn serve_session(
}
}
/// Write the scan header line for `root` (shared by both the streaming and
/// cache-backed `--stdio-v1` server).
pub fn write_header(
root: &Path,
home: Option<PathBuf>,
out: &mut impl Write,
) -> io::Result<()> {
send(
out,
&Header {
version: VERSION,
disk_root: volume_root_for(root),
space: space_info(root).ok(),
root: root.to_path_buf(),
home,
platform: std::env::consts::OS.into(),
identity: crate::identity::HostIdentity::current(),
},
)?;
out.flush()
}
/// Emit a live directory heartbeat line during a remote scan.
pub fn write_heartbeat(dir: &Path, out: &mut impl Write) -> io::Result<()> {
#[derive(Serialize)]
struct Heartbeat<'a> {
directory: &'a Path,
}
send(out, &Heartbeat { directory: dir })?;
out.flush()
}
/// Emit a stream terminator marker (`"stale"` or `"done"`).
pub fn write_marker(marker: &str, out: &mut impl Write) -> io::Result<()> {
send(out, &marker)?;
out.flush()
}
/// Serialize a `disktree_scanner::TreeArena` in the postorder `Record` wire
/// format expected by `read_snapshot` / `RemoteScan`.
pub fn write_arena(
arena: &disktree_scanner::TreeArena,
options: &ScanOptions,
client_dedup: bool,
out: &mut impl Write,
) -> io::Result<()> {
use disktree_scanner::{NodeFlags, NodeId, NodeKind as ScannerKind};
use rustc_hash::{FxHashMap, FxHashSet};
#[derive(Serialize)]
struct LinkRecord<'a> {
entry: &'a Record,
link: (u64, u64),
}
// Iterative postorder traversal so arbitrarily deep trees never blow the
// helper thread stack.
struct Frame {
id: NodeId,
depth: usize,
emitted_children: usize,
next_child: Option<NodeId>,
}
let mut hardlinks: FxHashMap<NodeId, (u64, u64)> = FxHashMap::default();
if !arena.hardlinks().is_empty() {
hardlinks.reserve(arena.hardlinks().len());
for entry in arena.hardlinks() {
hardlinks.insert(entry.node, (entry.dev, entry.ino));
}
}
let mut seen_links: FxHashSet<(u64, u64)> = FxHashSet::default();
let root_id = arena.root();
let mut frames = vec![Frame {
id: root_id,
depth: 0,
emitted_children: 0,
next_child: arena.node(root_id).first_child,
}];
while let Some(top) = frames.last_mut() {
let Some(child_id) = top.next_child else {
let done = frames.pop().expect("checked non-empty");
let an = arena.node(done.id);
let wire_name = if done.depth == 0 {
"root".to_owned()
} else {
arena.name(done.id).to_owned()
};
let record = Record(
wire_name,
0,
0,
0,
an.modified,
an.read_error(),
done.emitted_children,
);
send(out, &record)?;
continue;
};
let child = arena.node(child_id);
top.next_child = child.next_sibling;
if !options.include_hidden && child.flags.has(NodeFlags::HIDDEN) {
continue;
}
let name = arena.name(child_id);
if name.is_empty()
|| name == "."
|| name == ".."
|| name.contains(['/', '\0'])
{
continue;
}
let child_depth = top.depth + 1;
if child.kind() == ScannerKind::Directory {
if options.max_depth.is_some_and(|limit| child_depth > limit) {
continue;
}
top.emitted_children += 1;
frames.push(Frame {
id: child_id,
depth: child_depth,
emitted_children: 0,
next_child: child.first_child,
});
continue;
}
top.emitted_children += 1;
let kind_code = match child.kind() {
ScannerKind::Directory => 0,
ScannerKind::File => 1,
ScannerKind::Symlink => 2,
ScannerKind::Other => 3,
};
let mut bytes = if options.apparent_size {
child.apparent_bytes
} else {
child.allocated_bytes
};
let link = hardlinks.get(&child_id).copied();
if let Some(id) = link
&& options.dedup_hardlinks
&& kind_code == 1
{
if client_dedup {
let record = Record(
name.to_owned(),
kind_code,
bytes,
1,
child.modified,
child.read_error(),
0,
);
send(
out,
&LinkRecord {
entry: &record,
link: id,
},
)?;
continue;
}
if bytes > 0 && !seen_links.insert(id) {
bytes = 0;
}
}
let files = u64::from(kind_code == 1);
let record = Record(
name.to_owned(),
kind_code,
bytes,
files,
child.modified,
child.read_error(),
0,
);
send(out, &record)?;
}
Ok(())
}
/// Scan a decoded request. The standalone helper supervises its lifetime.
pub fn serve_request(request: Request, out: &mut impl Write) -> io::Result<()> {
serve_request_with_progress(request, out, false, false, false)
@@ -422,7 +618,7 @@ fn read_snapshot_with_progress(
let mut published = Instant::now();
let mut stack = Vec::<Node>::new();
let mut line = String::new();
let seen = crate::tree::Seen::new();
let mut seen = crate::tree::Seen::new();
let mut preview = crate::scan_preview::Builder::default();
let mut ancestors = Vec::<String>::new();
let mut preview_published = Instant::now();
@@ -469,11 +665,38 @@ fn read_snapshot_with_progress(
entry.2 = 0;
}
entry
} else if serde_json::from_str::<String>(text).map_err(json_error)?
== "done"
{
break;
} else {
let marker: String =
serde_json::from_str(text).map_err(json_error)?;
if marker == "done" {
break;
}
if marker == "stale" {
if stack.len() != 1 {
return Err(io::Error::other(
"incomplete remote stale tree",
));
}
let mut stale_tree = stack.pop().expect("one root checked");
aggregate(&mut stale_tree, crate::tree::Metric::Bytes);
crate::classify::classify(&mut stale_tree);
progress.stale_snapshot = Some(Arc::new(Snapshot {
header: header.clone(),
tree: stale_tree,
}));
progress.files = 0;
progress.dirs = 0;
progress.bytes = 0;
progress.errors = 0;
progress.updated = Some(Instant::now());
*shared.lock().expect("remote progress lock") =
progress.clone();
seen = crate::tree::Seen::new();
preview = crate::scan_preview::Builder::default();
ancestors.clear();
published = Instant::now();
continue;
}
return Err(io::Error::other("invalid remote stream marker"));
};
let Record(name, kind, bytes, files, modified, read_error, count) =
@@ -685,8 +908,16 @@ fn ssh_command(
impl RemoteScan {
pub fn spawn(host: &str, request: &Request) -> io::Result<Self> {
Self::spawn_with_refresh(host, request, false)
}
pub fn spawn_with_refresh(
host: &str,
request: &Request,
force_refresh: bool,
) -> io::Result<Self> {
let (command, archive) = ssh_command(host)?;
Self::spawn_with_archive(command, host, request, archive)
Self::spawn_with_archive(command, host, request, archive, force_refresh)
}
// Only the Unix tests run a fake ssh, so Windows has no caller.
@@ -696,7 +927,7 @@ impl RemoteScan {
host: &str,
request: &Request,
) -> io::Result<Self> {
Self::spawn_with_archive(command, host, request, None)
Self::spawn_with_archive(command, host, request, None, false)
}
fn spawn_with_archive(
@@ -704,6 +935,7 @@ impl RemoteScan {
host: &str,
request: &Request,
archive: Option<crate::payload::Archive>,
force_refresh: bool,
) -> io::Result<Self> {
let metric = request.options.metric;
Self::start(
@@ -711,6 +943,7 @@ impl RemoteScan {
host,
Operation::Scan(request.clone()),
archive,
force_refresh,
move |input, progress| {
let mut snapshot =
read_snapshot_with_progress(input, progress)?;
@@ -733,6 +966,7 @@ impl RemoteRoots {
discover_version: VERSION,
},
archive,
false,
|input, _| read_roots(input),
)
}
@@ -744,6 +978,7 @@ impl<T: Send + 'static> RemoteJob<T> {
host: &str,
operation: Operation,
archive: Option<crate::payload::Archive>,
force_refresh: bool,
decode: impl FnOnce(
&mut BufReader<std::process::ChildStdout>,
&Shared,
@@ -791,6 +1026,8 @@ impl<T: Send + 'static> RemoteJob<T> {
live_progress: true,
client_dedup: true,
live_tree: true,
stream_stale: true,
force_refresh,
},
)?;
decode(&mut input, &live)
@@ -987,6 +1224,8 @@ mod tests {
live_progress: true,
client_dedup: true,
live_tree: true,
stream_stale: false,
force_refresh: false,
};
let bytes = serde_json::to_vec(&session).unwrap();
assert!(serde_json::from_slice::<Request>(&bytes).is_err());
@@ -1164,6 +1403,7 @@ mod tests {
"fixture",
&request,
Some(archive.clone()),
false,
)
.unwrap();
let snapshot = wait(&handle).unwrap();
@@ -1210,6 +1450,7 @@ mod tests {
discover_version: VERSION,
},
Some(archive),
false,
|input, _| read_roots(input),
)
.unwrap();
@@ -1429,6 +1670,8 @@ mod tests {
client_dedup: true,
live_tree: true,
watch_disconnect: false,
stream_stale: false,
force_refresh: false,
};
let mut data = Vec::new();
serve_session(session, &mut data).unwrap();
@@ -40,6 +40,9 @@ pub struct Progress {
pub auth_url: Option<String>,
pub updated: Option<Instant>,
pub preview: Option<Arc<crate::scan_preview::Preview>>,
/// Stale cached snapshot streamed from the remote host's own cache DB
/// while parallel revalidation runs on the remote host.
pub stale_snapshot: Option<Arc<crate::remote::Snapshot>>,
}
/// Extract a Tailscale SSH check/login URL from SSH stderr diagnostics.