Skip to content

A high-performance Android storage analyzer that bypasses MTP using a native C++ daemon, a Rust TCP bridge, and a React Treemap UI.

Rust

Stream authenticated scan entries during traversal (#47)

Vishnu Srivatsavacde1b22610d5
diff --git a/README.md b/README.md
index c4cdc41..f9ac4c0 100644
--- a/README.md
+++ b/README.md
@@ -198,11 +198,15 @@ sequenceDiagram
R-->>U: Connected!
%% Scan Phase
- U->>R: invoke("run_scan", { path: "/sdcard" })
- R->>D: TCP Send: `SCAN /sdcard\n`
- Note over D: Recursive Fast POSIX Traversal
- D-->>R: Stream Large JSON Tree
- R-->>U: Parse & Render Treemap
+ U->>R: invoke("run_scan", { path, scanId, onProgress })
+ R->>D: TCP Send: `SCAN_STREAM /sdcard\n`
+ Note over D: Bounded POSIX Traversal
+ loop During traversal
+ D-->>R: Length-prefixed entry batches
+ R-->>U: Partial counts and recent entries
+ end
+ D-->>R: Completion totals, then EOF
+ R-->>U: Validate and render finished tree
%% Delete Phase
U->>R: invoke("delete_item", { path })
@@ -243,6 +247,15 @@ and does not keep directory descriptors open. Root and `--read-only` scans
remain serial, retaining their exclusions and scan-wide inode deduplication.
The authenticated protocol and deletion checks apply to every worker setting.
+The app uses scan stream v1 (advertised alongside protocol v3): bounded JSON
+frames arrive during traversal, with partial counts/recent entries and a cancel
+button. Successful results require verified totals, a terminal completion frame
+and EOF. Rebuild the daemon before running this version locally; older v3
+binaries without the streaming capability are refused. See
+[the stream contract](docs/scan-stream-v1.md) for bounds, completion rules,
+cancellation, timing semantics and the remaining full-tree frontend limitation.
+
+
### 2. Install Frontend Dependencies
```bash
cd ..
diff --git a/docs/scan-stream-v1.md b/docs/scan-stream-v1.md
new file mode 100644
index 0000000..31fc630
--- /dev/null
+++ b/docs/scan-stream-v1.md
@@ -0,0 +1,116 @@
+# Scan stream v1
+
+`PING` retains authenticated protocol version 3 and advertises
+`scan_stream_version: 1`. The desktop bridge requires both. Each connection
+still begins with `AUTH <64-hex-character session secret>\n`. The new command
+is `SCAN_STREAM <absolute root>\n`; legacy `SCAN` remains available for
+reference tests and diagnostics. Keep the client's write side open until the
+response finishes: half-close, disconnect, and extra command bytes abort the
+stream. Commands cannot contain CR, LF, or NUL, and retain the 16 KiB limit.
+
+## Framing and records
+
+Each frame is a four-byte unsigned big-endian byte length followed by UTF-8
+JSON. Length must be between 1 and 131,072 bytes. The envelope has exactly
+`type` and `data`; the daemon writes `type` first so the receiver can decode the
+selected payload directly. A batch contains 1–128 entries.
+
+```json
+{"type":"started","data":{"stream_version":1,"root":"/sdcard","read_only":false}}
+{"type":"entries","data":{"entries":[{"id":0,"parent":null,"name":"sdcard","kind":"directory","size":0,"counted":true}]}}
+{"type":"entries","data":{"entries":[{"id":1,"parent":0,"name":"photo.jpg","kind":"file","size":7,"counted":true}]}}
+```
+
+IDs are contiguous from zero in stream order. A parent must already exist and
+be a counted directory. ID zero is the sole root, with the name derived from
+the `started` root (`/` names itself). Names remain exact UTF-8 bytes; child
+names cannot be empty, `.`, `..`, contain slash/NUL, or exceed 255 bytes. Invalid
+UTF-8 causes refusal, never replacement characters in a usable path. Support
+for arbitrary filename bytes remains future protocol work.
+
+Kinds are `file`, `directory`, and `other`. File sizes are logical bytes.
+Directory and other record sizes are zero: the host derives directory sums.
+`counted` distinguishes regular files/directories from zero-byte placeholders
+and root-mode deduplicated entries. Uncounted entries cannot have children or
+nonzero sizes. A zero-byte regular file still counts as a file. Excluded root
+mount aliases are omitted, and the terminal `skipped` counter reports them.
+
+Successful completion is exactly one `done` frame, followed by socket EOF:
+
+```json
+{"type":"done","data":{"total_files":1,"total_dirs":1,"total_size":7,"errors":0,"skipped":0,"scan_time_ms":1,"scan_threads":4,"serialize_ms":0,"send_ms":0,"bytes_sent":123}}
+```
+
+`bytes_sent` above is illustrative. Its real value must equal the received
+bytes of all preceding frames, including length prefixes; the completion
+frame itself is excluded. The host checks file/directory/byte totals against
+records and subtree sums, rejects duplicate filenames within a directory,
+and checks negotiated read-only mode and worker count. Root/read-only scans
+retain one worker, mount exclusions and scan-wide inode deduplication.
+
+An error may appear before or during a scan:
+
+```json
+{"type":"error","data":{"message":"Scan root changed during scan; scan again"}}
+```
+
+Missing/truncated headers or payloads, malformed JSON, unknown fields/types,
+invalid ordering, mismatched counts, and any data after completion are errors.
+Error counts and exclusions remain visible even for a successfully completed
+scan with unreadable areas. Partial/cancelled scans are never successful
+baselines. The bridge clears its deletion root before each attempt and only
+sets it after valid completion/EOF and successful response serialization.
+The daemon pins its pending root separately and promotes it only after an
+unchanged-root check and successful completion write. Existing descriptor-
+anchored deletion and root read-only checks remain in force.
+
+## Bounds and cancellation
+
+Normal scanning retains immediate directory jobs rather than completed file
+subtrees. The queue holds at most 64 jobs with no descriptors; worker count is
+1–8. Inline fallback closes enumeration descriptors first. Shared directory
+staging has a conservative 64 MiB budget; exceeding it fails the scan instead
+of publishing partial success. Root-mode inode deduplication still requires a
+scan-wide set. Output batches flush on count/size limits, after 50 ms of scan
+activity, and immediately for the root and first discovered entry.
+
+Socket writes have an absolute 30-second deadline per complete frame, and
+host reads an absolute 120-second deadline per complete frame, including its
+header. Disconnect/write failure stops further traversal between filesystem
+operations. A filesystem operation already blocked in the kernel is not
+interruptible by this socket cancellation mechanism.
+
+The host accepts at most 2,000,000 records, depth 64, and path length 16 KiB.
+A conservative catalog estimate (path bytes, name bytes, 256 bytes per node)
+is capped at 128 MiB; the final UI JSON is capped at 256 MiB. Integer values and
+computed totals must fit JavaScript's exact integer range. These are data
+budgets, not promises that total process RSS equals those limits.
+
+Progress uses scan IDs, at most five recent names, and a 100 ms update interval
+plus first/final updates. Only one message may await acknowledgement from the
+webview; subsequent updates coalesce. Late progress/ack/cancel operations
+cannot affect a different scan ID. Cancellation bypasses the serialized
+operation lock and closes the active socket. The UI discards failed rescan
+results and returns to setup, avoiding actions based on an obsolete tree.
+
+The host keeps compact names, links and sizes, derives subtree totals, and
+serializes paths directly into the existing dashboard response. It does not
+buffer the whole wire response or build a second recursive host tree. The
+finished frontend still receives one full tree and locally clones it after
+deletion. Persistent Rust ownership, bounded queries and progressive browsing
+remain #29/#30 work; this change provides partial counts/recent entries during
+scanning rather than a browsable incomplete dashboard.
+
+## Timing and attribution
+
+For streamed scans, `scan_time_ms`/`traverse_ms` measure daemon traversal with
+interleaved encoding/writes. `serialize_ms` and `send_ms` are cumulative daemon
+encoding/write times; `sort_ms` measures host aggregation/sorting. These overlap
+and must not be added or compared directly with the old exclusive phase split.
+Final host response serialization and frontend rendering are not included.
+
+Directory streaming and compact host construction are inspired by
+[Shanmukh's reviewed fork](https://github.com/ksaishanmukh/SocketSweep/tree/d677b530e00dec75c305fc56318720aa8c161692),
+particularly `e21a430`, `ec0679f` and `e7a7383`. This implementation keeps the
+current C++ engine, authenticated session, anchored reads/deletion and root
+safeguards rather than adopting the fork's daemon/transport wholesale.
diff --git a/engine/daemon.cpp b/engine/daemon.cpp
index fb3be04..69c5507 100644
--- a/engine/daemon.cpp
+++ b/engine/daemon.cpp
@@ -12,6 +12,7 @@
#include <string>
#include <vector>
#include <set>
+#include <limits>
#if defined(__linux__)
#include <linux/magic.h>
#include <sys/vfs.h>
@@ -29,6 +30,8 @@
#include <iostream>
#include <fstream>
#include <poll.h>
+#include <atomic>
+#include <mutex>
// ── Configuration ───────────────────────────────────────────────────────────
namespace cfg {
@@ -159,7 +162,8 @@ struct ScanStats {
};
// ── JSON helpers ────────────────────────────────────────────────────────────
-static void json_escape_into(JsonStream& out, const std::string& s) {
+template <typename Output>
+static void json_escape_into(Output& out, const std::string& s) {
for (unsigned char c : s) {
switch (c) {
case '"': out.write("\\\"", 2); break;
@@ -182,6 +186,8 @@ static void json_escape_into(JsonStream& out, const std::string& s) {
}
}
+#include "scan_output.h"
+
static void serialize_node(JsonStream& out, const FileNode& node) {
out.write("{\"name\":\"");
json_escape_into(out, node.name);
@@ -234,41 +240,54 @@ static bool root_mount_alias(const char* name) {
}
static FileNode scan(const std::string& path, const std::string& name,
- ScanStats& st, int depth)
+ ScanStats& st, int depth, ScanOutput* output = nullptr, uint64_t parent = 0)
{
FileNode node;
node.name = name;
node.path = path;
+ uint64_t id = 0;
+ const auto emit = [&](const char* kind, bool counted) {
+ return !output || output->entry(node, parent, kind, counted, id);
+ };
+ if (output && !output->alive()) return node;
struct stat info{};
int stat_res = (depth == 0) ? ::stat(path.c_str(), &info) : ::lstat(path.c_str(), &info);
if (stat_res != 0) {
++st.errors;
+ emit("other", false);
return node;
}
- if (depth > 0 && S_ISLNK(info.st_mode)) return node;
+ if (depth > 0 && S_ISLNK(info.st_mode)) { emit("other", false); return node; }
node.is_dir = S_ISDIR(info.st_mode);
if (g_read_only && (S_ISREG(info.st_mode) || S_ISDIR(info.st_mode))) {
if ((S_ISDIR(info.st_mode) && virtual_filesystem(path)) ||
!st.seen.emplace(info.st_dev, info.st_ino).second) {
++st.skipped;
+ emit(node.is_dir ? "directory" : "file", false);
return node;
}
}
if (S_ISREG(info.st_mode)) {
+ if (output && (info.st_size < 0 || st.total_size > std::numeric_limits<int64_t>::max() - info.st_size)) {
+ output->error("Scan byte total overflow");
+ return node;
+ }
node.size = info.st_size;
++st.files;
st.total_size += info.st_size;
+ emit("file", true);
return node;
}
- if (!S_ISDIR(info.st_mode)) return node;
+ if (!S_ISDIR(info.st_mode)) { emit("other", false); return node; }
node.is_dir = true;
++st.dirs;
+ if (!emit("directory", true)) return node;
if (depth >= cfg::MAX_DEPTH) { ++st.errors; return node; }
@@ -276,7 +295,11 @@ static FileNode scan(const std::string& path, const std::string& name,
if (!dir) { ++st.errors; return node; }
struct dirent* ent;
- while ((ent = ::readdir(dir)) != nullptr) {
+ while (true) {
+ if (output && !output->alive()) break;
+ errno = 0;
+ ent = ::readdir(dir);
+ if (!ent) { if (output && errno != 0) ++st.errors; break; }
if (ent->d_name[0] == '.') {
if (ent->d_name[1] == '\0') continue;
if (ent->d_name[1] == '.' && ent->d_name[2] == '\0') continue;
@@ -292,12 +315,13 @@ static FileNode scan(const std::string& path, const std::string& name,
}
std::string child_path = (path == "/" ? path : path + '/') + ent->d_name;
- FileNode child = scan(child_path, ent->d_name, st, depth + 1);
+ FileNode child = scan(child_path, ent->d_name, st, depth + 1, output, id);
node.size += child.size;
- node.children.push_back(std::move(child));
+ if (!output) node.children.push_back(std::move(child));
}
::closedir(dir);
+ if (output) return node; // Completed children have already been sent.
const auto sort_t0 = std::chrono::steady_clock::now();
std::sort(node.children.begin(), node.children.end(),
[](const FileNode& a, const FileNode& b) {
@@ -310,6 +334,7 @@ static FileNode scan(const std::string& path, const std::string& name,
}
#include "parallel_scan.h"
+#include "stream_scan.h"
// ── Command dispatch ────────────────────────────────────────────────────────
static void handle_client(int fd) {
@@ -330,7 +355,7 @@ static void handle_client(int fd) {
}
if (cmd == "PING") {
- out.write("{\"status\":\"ok\",\"message\":\"pong\",\"protocol_version\":3,\"uid\":");
+ out.write("{\"status\":\"ok\",\"message\":\"pong\",\"protocol_version\":3,\"scan_stream_version\":1,\"uid\":");
out.write(std::to_string(::geteuid()));
out.write(",\"read_only\":");
out.write(g_read_only ? "true" : "false");
@@ -363,6 +388,10 @@ static void handle_client(int fd) {
out.write(" items\"}\n");
}
}
+ else if (cmd == "SCAN_STREAM" || cmd.rfind("SCAN_STREAM ", 0) == 0) {
+ stream_scan::handle(fd, cmd.size() > 11 ? cmd.substr(12) : cfg::DEFAULT_ROOT);
+ return;
+ }
else if (cmd == "SCAN" || cmd.rfind("SCAN ", 0) == 0) {
std::string root = cfg::DEFAULT_ROOT;
if (cmd.size() > 4) {
diff --git a/engine/parallel_scan.h b/engine/parallel_scan.h
index 5ec9b78..b647b6e 100644
--- a/engine/parallel_scan.h
+++ b/engine/parallel_scan.h
@@ -31,6 +31,32 @@ struct Task {
int depth;
};
+inline safe_delete::Fd open_directory(const safe_delete::Root& root, const FileNode& node) {
+ // Reopen from the pinned root one component at a time. In particular,
+ // opening a queued path must not follow a replaced parent symlink.
+ safe_delete::Fd current(::openat(root.fd.get(), ".",
+ O_RDONLY | O_DIRECTORY | O_CLOEXEC));
+ if (current.get() < 0) return current;
+ const size_t prefix = root.path.size() + (root.path == "/" ? 0 : 1);
+ size_t start = prefix;
+ while (start < node.path.size()) {
+ size_t end = node.path.find('/', start);
+ if (end == std::string::npos) end = node.path.size();
+ const std::string name = node.path.substr(start, end - start);
+ SOCKETSWEEP_SCAN_CHECKPOINT("before_open", current.get(), name.c_str());
+ current.reset(::openat(current.get(), name.c_str(),
+ O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
+ if (current.get() < 0) return current;
+ start = end + 1;
+ }
+ struct stat actual{};
+ if (::fstat(current.get(), &actual) != 0 ||
+ actual.st_dev != node.device || actual.st_ino != node.inode) {
+ current.reset();
+ }
+ return current;
+}
+
// Only directory jobs enter the queue. Its entries own no descriptors. A
// worker owns its subtree's child vector until enumeration is finished, then
// publishes pointers into that stable vector. Aggregation and sorting happen
@@ -49,32 +75,6 @@ class Pool {
size_t queue_peak_ = 1;
std::array<Worker, MAX_WORKERS> workers_;
- safe_delete::Fd open_directory(const FileNode& node) const {
- // Reopen from the pinned root one component at a time. In particular,
- // opening a queued path must not follow a replaced parent symlink.
- safe_delete::Fd current(::openat(root_.fd.get(), ".",
- O_RDONLY | O_DIRECTORY | O_CLOEXEC));
- if (current.get() < 0) return current;
- const size_t prefix = root_.path.size() + (root_.path == "/" ? 0 : 1);
- size_t start = prefix;
- while (start < node.path.size()) {
- size_t end = node.path.find('/', start);
- if (end == std::string::npos) end = node.path.size();
- const std::string name = node.path.substr(start, end - start);
- SOCKETSWEEP_SCAN_CHECKPOINT("before_open", current.get(), name.c_str());
- current.reset(::openat(current.get(), name.c_str(),
- O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
- if (current.get() < 0) return current;
- start = end + 1;
- }
- struct stat actual{};
- if (::fstat(current.get(), &actual) != 0 ||
- actual.st_dev != node.device || actual.st_ino != node.inode) {
- current.reset();
- }
- return current;
- }
-
bool enqueue(Task task) {
std::lock_guard<std::mutex> lock(mutex_);
if (queue_.size() >= MAX_PENDING) return false;
@@ -89,7 +89,7 @@ class Pool {
FileNode& node = *task.node;
++stats.dirs;
if (task.depth >= max_depth_) { ++stats.errors; return; }
- safe_delete::Fd opened = open_directory(node);
+ safe_delete::Fd opened = open_directory(root_, node);
if (opened.get() < 0) { ++stats.errors; return; }
SOCKETSWEEP_SCAN_CHECKPOINT("opened", opened.get(), node.path.c_str());
DIR* listing = ::fdopendir(opened.get());
diff --git a/engine/scan_output.h b/engine/scan_output.h
new file mode 100644
index 0000000..828dad0
--- /dev/null
+++ b/engine/scan_output.h
@@ -0,0 +1,148 @@
+#pragma once
+
+// Stream v1 is bounded, length-prefixed JSON, independent of the legacy SCAN
+// response. Entries precede their children; directory totals are computed by
+// the host. No lossy filename conversion is performed by either endpoint.
+class ScanOutput {
+ struct Buffer {
+ std::string text;
+ bool write(const std::string& s) { text += s; return true; }
+ bool write(const char* s, size_t n) { text.append(s, n); return true; }
+ };
+ int fd_;
+ std::mutex mutex_;
+ std::atomic<bool> failed_{false};
+ uint64_t next_id_ = 0;
+ size_t entries_ = 0;
+ std::string batch_;
+ std::chrono::steady_clock::time_point flushed_ = std::chrono::steady_clock::now();
+ int64_t encode_ns_ = 0;
+
+ bool peer_alive() {
+ char byte;
+ const ssize_t n = ::recv(fd_, &byte, 1, MSG_PEEK | MSG_DONTWAIT);
+ // Half-close and extra commands both abort this one-command stream.
+ return n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR);
+ }
+ bool send_bytes(const char* data, size_t length) {
+ const auto start = std::chrono::steady_clock::now();
+ const auto deadline = start + std::chrono::seconds(cfg::RECV_TIMEOUT_SEC);
+ size_t left = length;
+ while (left && g_running && !failed_) {
+ const auto now = std::chrono::steady_clock::now();
+ if (now >= deadline) break;
+ const ssize_t n = ::send(fd_, data, left, MSG_NOSIGNAL | MSG_DONTWAIT);
+ if (n > 0) { data += n; left -= static_cast<size_t>(n); continue; }
+ if (n < 0 && errno == EINTR) continue;
+ if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
+ struct pollfd event { fd_, POLLOUT, 0 };
+ const auto remaining = std::chrono::duration_cast<std::chrono::milliseconds>(deadline - now).count();
+ if (::poll(&event, 1, static_cast<int>(std::min<int64_t>(remaining, 100))) >= 0) continue;
+ if (errno == EINTR) continue;
+ }
+ break;
+ }
+ g_send_bytes += length - left;
+ g_send_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - start).count();
+ if (left) failed_ = true;
+ return left == 0;
+ }
+ bool frame(const std::string& text) {
+ // Put the discriminator before the data. Serde can then deserialize
+ // the selected frame directly instead of buffering a generic JSON tree.
+ const auto comma = text.find(',');
+ if (comma == std::string::npos) { failed_ = true; return false; }
+ const std::string payload = text.substr(0, comma) + ",\"data\":{" + text.substr(comma + 1) + "}";
+ if (payload.size() > MAX_FRAME_BYTES || !peer_alive()) {
+ failed_ = true;
+ return false;
+ }
+ const uint32_t length = htonl(static_cast<uint32_t>(payload.size()));
+ std::string wire;
+ wire.reserve(sizeof(length) + payload.size());
+ wire.append(reinterpret_cast<const char*>(&length), sizeof(length));
+ wire += payload;
+ return send_bytes(wire.data(), wire.size());
+ }
+ bool flush_locked() {
+ if (entries_ == 0) return !failed_;
+ batch_ += "]}";
+ const bool ok = frame(batch_);
+ batch_.clear();
+ entries_ = 0;
+ flushed_ = std::chrono::steady_clock::now();
+ return ok;
+ }
+public:
+ static constexpr size_t MAX_FRAME_BYTES = 128 * 1024;
+ static constexpr size_t MAX_BATCH_ENTRIES = 128;
+ explicit ScanOutput(int fd) : fd_(fd) { batch_.reserve(64 * 1024); }
+ bool alive() {
+ if (failed_ || !g_running) return false;
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (std::chrono::steady_clock::now() - flushed_ >= std::chrono::milliseconds(50)) {
+ if (!peer_alive()) failed_ = true;
+ if (!failed_) flush_locked();
+ flushed_ = std::chrono::steady_clock::now();
+ }
+ return !failed_;
+ }
+ bool start(const std::string& root) {
+ Buffer out;
+ out.write("{\"type\":\"started\",\"stream_version\":1,\"root\":\"");
+ json_escape_into(out, root);
+ out.write("\",\"read_only\":");
+ out.write(g_read_only ? "true}" : "false}");
+ return frame(out.text);
+ }
+ bool entry(const FileNode& node, uint64_t parent, const char* kind, bool counted, uint64_t& id) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (failed_ || !g_running) return false;
+ const auto start = std::chrono::steady_clock::now();
+ id = next_id_++;
+ Buffer out;
+ out.write("{\"id\":" + std::to_string(id) + ",\"parent\":");
+ out.write(id == 0 ? "null" : std::to_string(parent));
+ out.write(",\"name\":\"");
+ json_escape_into(out, node.name);
+ out.write("\",\"kind\":\"" + std::string(kind) + "\",\"size\":" + std::to_string(node.size));
+ out.write(counted ? ",\"counted\":true}" : ",\"counted\":false}");
+ encode_ns_ += std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - start).count();
+ if (out.text.size() + 48 > MAX_FRAME_BYTES) { failed_ = true; return false; }
+ if (entries_ && (batch_.size() + out.text.size() + 16 > MAX_FRAME_BYTES || entries_ == MAX_BATCH_ENTRIES)) {
+ if (!flush_locked()) return false;
+ }
+ if (entries_ == 0) batch_ = "{\"type\":\"entries\",\"entries\":[";
+ else batch_ += ',';
+ batch_ += out.text;
+ ++entries_;
+ // Publish the root and the first discovered entry promptly, then batch
+ // subsequent records by size/count/time instead of a syscall per file.
+ if (id <= 1 || entries_ == MAX_BATCH_ENTRIES ||
+ std::chrono::steady_clock::now() - flushed_ >= std::chrono::milliseconds(50)) return flush_locked();
+ return true;
+ }
+ bool error(const std::string& message) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ batch_.clear(); entries_ = 0;
+ Buffer out;
+ out.write("{\"type\":\"error\",\"message\":\"");
+ json_escape_into(out, message);
+ out.write("\"}");
+ const bool sent = frame(out.text);
+ failed_ = true;
+ return sent;
+ }
+ bool finish(const ScanStats& stats, int64_t elapsed_ms, int workers) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (failed_ || !flush_locked()) return false;
+ const std::string text = "{\"type\":\"done\",\"total_files\":" + std::to_string(stats.files) +
+ ",\"total_dirs\":" + std::to_string(stats.dirs) + ",\"total_size\":" + std::to_string(stats.total_size) +
+ ",\"errors\":" + std::to_string(stats.errors) + ",\"skipped\":" + std::to_string(stats.skipped) +
+ ",\"scan_time_ms\":" + std::to_string(elapsed_ms) + ",\"scan_threads\":" + std::to_string(workers) +
+ ",\"serialize_ms\":" + std::to_string(ns_to_ms(encode_ns_)) +
+ ",\"send_ms\":" + std::to_string(ns_to_ms(g_send_ns)) +
+ ",\"bytes_sent\":" + std::to_string(g_send_bytes) + "}";
+ return frame(text);
+ }
+};
diff --git a/engine/stream_scan.h b/engine/stream_scan.h
new file mode 100644
index 0000000..9905849
--- /dev/null
+++ b/engine/stream_scan.h
@@ -0,0 +1,199 @@
+#pragma once
+
+namespace stream_scan {
+
+// Jobs own their directory metadata, never a pointer into a completed tree or
+// an open descriptor. Only immediate subdirectories are retained while a
+// directory is enumerated. Completed file records/subtrees are not retained.
+class Pool {
+ struct Task { FileNode node; uint64_t id; int depth; };
+ struct Worker { Pool* pool = nullptr; ScanStats stats; };
+ const safe_delete::Root& root_;
+ ScanOutput& output_;
+ const size_t staging_limit_;
+ std::atomic<size_t> staged_bytes_{0};
+ std::mutex mutex_;
+ std::condition_variable ready_;
+ std::deque<Task> queue_;
+ size_t outstanding_ = 1;
+ size_t queue_peak_ = 1;
+ std::array<Worker, parallel_scan::MAX_WORKERS> workers_;
+
+ bool enqueue(Task& task) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (!output_.alive() || queue_.size() >= parallel_scan::MAX_PENDING) return false;
+ queue_.push_back(std::move(task));
+ ++outstanding_;
+ queue_peak_ = std::max(queue_peak_, queue_.size());
+ ready_.notify_one();
+ return true;
+ }
+ void process(const Task& task, ScanStats& stats) {
+ if (!output_.alive()) return;
+ ++stats.dirs;
+ if (task.depth >= cfg::MAX_DEPTH) { ++stats.errors; return; }
+ safe_delete::Fd opened = parallel_scan::open_directory(root_, task.node);
+ if (opened.get() < 0) { ++stats.errors; return; }
+ SOCKETSWEEP_SCAN_CHECKPOINT("opened", opened.get(), task.node.path.c_str());
+ DIR* listing = ::fdopendir(opened.get());
+ if (!listing) { ++stats.errors; return; }
+ opened.release();
+ std::vector<Task> directories;
+ struct Staging {
+ std::atomic<size_t>& total;
+ size_t bytes = 0;
+ ~Staging() { total.fetch_sub(bytes); }
+ bool reserve(size_t cost, size_t limit) {
+ const size_t previous = total.fetch_add(cost);
+ if (cost > limit || previous > limit - cost) {
+ total.fetch_sub(cost);
+ return false;
+ }
+ bytes += cost;
+ return true;
+ }
+ } staging{staged_bytes_};
+ while (output_.alive()) {
+ errno = 0;
+ const auto* entry = ::readdir(listing);
+ if (!entry) { if (errno) ++stats.errors; break; }
+ const std::string name = entry->d_name;
+ if (name == "." || name == "..") continue;
+#ifdef DT_LNK
+ if (entry->d_type == DT_LNK) continue;
+#endif
+ FileNode node;
+ node.name = name;
+ node.path = (task.node.path == "/" ? task.node.path : task.node.path + '/') + name;
+ struct stat info{};
+ const char* kind = "other";
+ bool counted = false;
+ if (::fstatat(::dirfd(listing), name.c_str(), &info, AT_SYMLINK_NOFOLLOW) != 0) {
+ ++stats.errors;
+ } else if (S_ISLNK(info.st_mode)) {
+ continue;
+ } else if (S_ISDIR(info.st_mode)) {
+ node.is_dir = true;
+ node.device = info.st_dev;
+ node.inode = info.st_ino;
+ kind = "directory"; counted = true;
+ } else if (S_ISREG(info.st_mode)) {
+ if (info.st_size < 0 || stats.total_size > std::numeric_limits<int64_t>::max() - info.st_size) {
+ output_.error("Scan byte total overflow");
+ break;
+ }
+ node.size = info.st_size;
+ ++stats.files; stats.total_size += info.st_size;
+ kind = "file"; counted = true;
+ }
+ uint64_t id = 0;
+ if (!output_.entry(node, task.id, kind, counted, id)) break;
+ if (node.is_dir) {
+ // Include vector growth and owned strings. This shared budget
+ // also covers inline fallbacks, not just the queued jobs.
+ const size_t cost = 2 * sizeof(Task) + node.path.capacity() + node.name.capacity() + 64;
+ if (!staging.reserve(cost, staging_limit_)) {
+ output_.error("Scan directory staging limit exceeded");
+ break;
+ }
+ directories.push_back({std::move(node), id, task.depth + 1});
+ }
+ }
+ ::closedir(listing);
+ // Match the legacy pool's descriptor bound: close before inline
+ // fallback, and never wait for queue space (which could deadlock).
+ for (auto& child : directories) {
+ if (!output_.alive()) break;
+ if (!enqueue(child)) process(child, stats);
+ }
+ }
+ void work(ScanStats& stats) {
+ while (true) {
+ Task task;
+ {
+ std::unique_lock<std::mutex> lock(mutex_);
+ ready_.wait(lock, [&] { return !queue_.empty() || outstanding_ == 0; });
+ if (!outstanding_) return;
+ task = std::move(queue_.front()); queue_.pop_front();
+ }
+ process(task, stats);
+ {
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (--outstanding_ == 0) ready_.notify_all();
+ }
+ }
+ }
+ static void* entry(void* context) {
+ auto& worker = *static_cast<Worker*>(context);
+ worker.pool->work(worker.stats);
+ return nullptr;
+ }
+public:
+ Pool(const safe_delete::Root& root, ScanOutput& output, FileNode node,
+ size_t staging_limit = 64 * 1024 * 1024)
+ : root_(root), output_(output), staging_limit_(staging_limit) {
+ queue_.push_back({std::move(node), 0, 0});
+ for (auto& worker : workers_) worker.pool = this;
+ }
+ size_t queue_peak() const { return queue_peak_; }
+ int run(ScanStats& stats, int requested) {
+ requested = std::max(1, std::min(requested, parallel_scan::MAX_WORKERS));
+ std::array<pthread_t, parallel_scan::MAX_WORKERS - 1> threads{};
+ int count = 1;
+ for (int i = 1; i < requested; ++i) {
+ if (SOCKETSWEEP_SCAN_CREATE_THREAD(&threads[i - 1], nullptr, entry, &workers_[i])) break;
+ ++count;
+ }
+ work(workers_[0].stats);
+ for (int i = 1; i < count; ++i) ::pthread_join(threads[i - 1], nullptr);
+ for (int i = 0; i < count; ++i) {
+ if (stats.total_size > std::numeric_limits<int64_t>::max() - workers_[i].stats.total_size) {
+ output_.error("Scan byte total overflow");
+ break;
+ }
+ stats.files += workers_[i].stats.files; stats.dirs += workers_[i].stats.dirs;
+ stats.total_size += workers_[i].stats.total_size; stats.errors += workers_[i].stats.errors;
+ }
+ return count;
+ }
+};
+
+static void handle(int fd, std::string root) {
+ g_scan_root.clear();
+ g_send_ns = 0; g_send_bytes = 0;
+ ScanOutput output(fd);
+ while (root.size() > 1 && root.back() == '/') root.pop_back();
+ if (root.empty() || root.front() != '/') { output.error("Scan root must be an absolute directory"); return; }
+ if (g_read_only) {
+ char* canonical = ::realpath(root.c_str(), nullptr);
+ if (!canonical) { output.error("Scan root is not an accessible directory"); return; }
+ root = canonical; std::free(canonical);
+ if (virtual_filesystem(root)) { output.error("Virtual filesystems are excluded from root scans"); return; }
+ }
+ safe_delete::Root pending;
+ if (!pending.open(root)) { output.error("Scan root is not an accessible directory"); return; }
+ if (!output.start(root)) return;
+ const auto start = std::chrono::steady_clock::now();
+ ScanStats stats;
+ int workers = 1;
+ const auto position = root.rfind('/');
+ const auto name = position + 1 < root.size() ? root.substr(position + 1) : root;
+ if (g_read_only) {
+ scan(root, name, stats, 0, &output);
+ } else {
+ FileNode node;
+ node.name = name; node.path = root; node.is_dir = true;
+ node.device = pending.identity.st_dev; node.inode = pending.identity.st_ino;
+ uint64_t id = 0;
+ if (!output.entry(node, 0, "directory", true, id)) return;
+ Pool pool(pending, output, std::move(node));
+ workers = pool.run(stats, g_scan_threads);
+ }
+ if (!output.alive()) return;
+ if (!pending.unchanged()) { output.error("Scan root changed during scan; scan again"); return; }
+ const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();
+ // A cancelled/failed scan never becomes a daemon deletion root. The host
+ // separately validates completion, counts and EOF before authorizing it.
+ if (output.finish(stats, elapsed, workers)) g_scan_root = std::move(pending);
+}
+} // namespace stream_scan
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index aca30b9..d98f19f 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -8,12 +8,16 @@
// Wire protocol (matches Phase 1 daemon):
// Each connection starts with "AUTH <session token>\n", then one command.
// → "PING\n" ← {"status":"ok","protocol_version":3,"uid":…,"read_only":…}
-// → "SCAN [path]\n" ← {"status":"ok","scan_time_ms":…,"tree":{…}}
+// → "SCAN_STREAM path\n" ← length-prefixed JSON frames (scan stream v1)
+// → "SCAN [path]\n" ← legacy whole-tree JSON (diagnostics/tests)
// → "SHUTDOWN\n" ← {"status":"ok","message":"shutting down"}
// ============================================================================
use std::io::{Read, Write};
-use std::net::TcpStream;
+use std::net::{Shutdown, TcpStream};
+use std::sync::{Arc, atomic::{AtomicBool, Ordering}};
+use tauri::ipc::Channel;
+mod scan_stream;
use std::process::Command;
use std::sync::Mutex;
use std::time::Duration;
@@ -251,13 +255,14 @@ struct DaemonStatus {
status: String,
message: Option<String>,
protocol_version: Option<u32>,
+ scan_stream_version: Option<u32>,
uid: Option<u32>,
read_only: Option<bool>,
}
fn require_handshake(response: &str, root_mode: bool) -> Result<DaemonStatus, String> {
let parsed = require_ok(response)?;
- if parsed.protocol_version != Some(3) || parsed.uid.is_none() || parsed.read_only.is_none() {
+ if parsed.protocol_version != Some(3) || parsed.scan_stream_version != Some(1) || parsed.uid.is_none() || parsed.read_only.is_none() {
return Err("Bundled daemon is outdated. Rebuild it before connecting.".into());
}
if (root_mode && parsed.uid != Some(0)) || (parsed.uid == Some(0) && parsed.read_only != Some(true)) {
@@ -421,24 +426,172 @@ fn init_daemon_inner(app: tauri::AppHandle, root_mode: bool) -> Result<String, S
))
}
+// Cancellation deliberately bypasses DAEMON_OPERATION: otherwise it would
+// wait for the scan it is meant to stop. IDs prevent a late click cancelling
+// another scan. Registration happens before connect, so early clicks count.
+struct ActiveScan {
+ id: String,
+ cancelled: Arc<AtomicBool>,
+ progress_pending: Arc<AtomicBool>,
+ socket: Option<TcpStream>,
+}
+static ACTIVE_SCAN: Mutex<Option<ActiveScan>> = Mutex::new(None);
+struct ScanRegistration(String);
+impl Drop for ScanRegistration {
+ fn drop(&mut self) {
+ if let Ok(mut active) = ACTIVE_SCAN.lock() {
+ if active.as_ref().is_some_and(|scan| scan.id == self.0) {
+ if let Some(socket) = active.take().and_then(|scan| scan.socket) {
+ let _ = socket.shutdown(Shutdown::Both);
+ }
+ }
+ }
+ }
+}
+#[derive(serde::Serialize)]
+struct ScanProgress {
+ scan_id: String,
+ #[serde(flatten)]
+ progress: scan_stream::Progress,
+}
+
+// At most one progress message may await delivery/acknowledgement. A slow
+// webview cannot turn progress events into an unbounded IPC payload queue.
#[tauri::command(async)]
-fn run_scan(path: Option<String>) -> Result<String, String> {
- let _operation = DAEMON_OPERATION.lock().map_err(|_| "Daemon state is unavailable")?;
- let effective_root = match path {
- Some(ref p) if !p.is_empty() => p.clone(),
- _ => "/sdcard".to_string(), // daemon default
- };
- let cmd = format!("SCAN {effective_root}");
- *SCAN_ROOT.lock().map_err(|_| "Scan state is unavailable")? = None;
- let response = daemon_command(&cmd)?;
- require_ok(&response)?;
+fn acknowledge_scan_progress(scan_id: String) -> Result<(), String> {
+ let active = ACTIVE_SCAN
+ .lock()
+ .map_err(|_| "Scan state is unavailable")?;
+ if let Some(scan) = active.as_ref().filter(|scan| scan.id == scan_id) {
+ scan.progress_pending.store(false, Ordering::SeqCst);
+ }
+ Ok(())
+}
- // Store the scan root so delete_item can guard against it.
- if let Ok(mut root) = SCAN_ROOT.lock() {
- *root = Some(effective_root);
+#[tauri::command(async)]
+fn cancel_scan(scan_id: String) -> Result<(), String> {
+ let active = ACTIVE_SCAN
+ .lock()
+ .map_err(|_| "Scan state is unavailable")?;
+ if let Some(scan) = active.as_ref().filter(|scan| scan.id == scan_id) {
+ scan.cancelled.store(true, Ordering::SeqCst);
+ if let Some(socket) = &scan.socket {
+ let _ = socket.shutdown(Shutdown::Both);
+ }
}
+ Ok(())
+}
- Ok(response)
+#[tauri::command(async)]
+fn run_scan(
+ path: Option<String>,
+ scan_id: String,
+ on_progress: Channel<ScanProgress>,
+) -> Result<String, String> {
+ if scan_id.is_empty()
+ || scan_id.len() > 64
+ || !scan_id
+ .bytes()
+ .all(|b| b.is_ascii_alphanumeric() || b == b'-')
+ {
+ return Err("Invalid scan identifier".into());
+ }
+ let _operation = DAEMON_OPERATION
+ .lock()
+ .map_err(|_| "Daemon state is unavailable")?;
+ *SCAN_ROOT.lock().map_err(|_| "Scan state is unavailable")? = None;
+ let effective_root = path
+ .filter(|p| !p.is_empty())
+ .unwrap_or_else(|| "/sdcard".into());
+ let token = SESSION_TOKEN
+ .lock()
+ .map_err(|_| "Session state is unavailable")?
+ .clone()
+ .ok_or("No active daemon session. Connect your device first.")?;
+ let payload = command_payload(&format!("SCAN_STREAM {effective_root}"), &token)?;
+ let read_only = *READ_ONLY
+ .lock()
+ .map_err(|_| "Session state is unavailable")?;
+ let cancelled = Arc::new(AtomicBool::new(false));
+ let progress_pending = Arc::new(AtomicBool::new(false));
+ *ACTIVE_SCAN
+ .lock()
+ .map_err(|_| "Scan state is unavailable")? = Some(ActiveScan {
+ id: scan_id.clone(),
+ cancelled: cancelled.clone(),
+ progress_pending: progress_pending.clone(),
+ socket: None,
+ });
+ let _registration = ScanRegistration(scan_id.clone());
+ let result = (|| {
+ let mut stream =
+ TcpStream::connect_timeout(&DAEMON_ADDR.parse().unwrap(), TCP_CONNECT_TIMEOUT)
+ .map_err(|e| format!("Cannot connect to daemon at {DAEMON_ADDR}: {e}"))?;
+ stream
+ .set_read_timeout(Some(TCP_READ_TIMEOUT))
+ .map_err(|e| e.to_string())?;
+ stream
+ .set_write_timeout(Some(TCP_CONNECT_TIMEOUT))
+ .map_err(|e| e.to_string())?;
+ {
+ let mut active = ACTIVE_SCAN
+ .lock()
+ .map_err(|_| "Scan state is unavailable")?;
+ if cancelled.load(Ordering::SeqCst) {
+ return Err("Scan cancelled".into());
+ }
+ active.as_mut().unwrap().socket = Some(stream.try_clone().map_err(|e| e.to_string())?);
+ }
+ stream
+ .write_all(payload.as_bytes())
+ .map_err(|e| format!("Failed to send scan command: {e}"))?;
+ let response = scan_stream::read(
+ &mut scan_stream::SocketReader::new(&mut stream),
+ read_only,
+ |progress| {
+ if cancelled.load(Ordering::SeqCst) {
+ return Err("Scan cancelled".into());
+ }
+ if progress_pending
+ .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
+ .is_err()
+ {
+ return Ok(()); // coalesce updates while the previous one awaits acknowledgement
+ }
+ on_progress
+ .send(ScanProgress {
+ scan_id: scan_id.clone(),
+ progress: progress.clone(),
+ })
+ .map_err(|e| format!("Cannot deliver scan progress: {e}"))
+ },
+ )?;
+ if !read_only {
+ let normalized = effective_root.trim_end_matches('/');
+ let normalized = if normalized.is_empty() { "/" } else { normalized };
+ if response.root() != normalized {
+ return Err("Daemon scanned an unexpected root".into());
+ }
+ }
+ let json = response.json()?;
+ // Serialize before authorization too: a result exceeding the UI limit
+ // must not leave a bridge deletion root behind.
+ let mut active = ACTIVE_SCAN
+ .lock()
+ .map_err(|_| "Scan state is unavailable")?;
+ if cancelled.load(Ordering::SeqCst) {
+ return Err("Scan cancelled".into());
+ }
+ *SCAN_ROOT.lock().map_err(|_| "Scan state is unavailable")? =
+ Some(response.root().to_string());
+ active.take();
+ Ok(json)
+ })();
+ if cancelled.load(Ordering::SeqCst) {
+ Err("Scan cancelled".into())
+ } else {
+ result
+ }
}
#[tauri::command(async)]
@@ -501,6 +654,8 @@ pub fn run() {
check_adb,
init_daemon,
run_scan,
+ cancel_scan,
+ acknowledge_scan_progress,
ping_daemon,
stop_daemon,
delete_item,
@@ -532,7 +687,7 @@ mod tests {
#[test]
fn root_handshake_rejects_wrong_uid_writable_daemon_and_old_protocol() {
- let response = |version, uid, read_only| format!("{{\"status\":\"ok\",\"protocol_version\":{version},\"uid\":{uid},\"read_only\":{read_only}}}");
+ let response = |version, uid, read_only| format!("{{\"status\":\"ok\",\"protocol_version\":{version},\"scan_stream_version\":1,\"uid\":{uid},\"read_only\":{read_only}}}");
assert!(require_handshake(&response(3, 0, true), true).is_ok());
assert!(require_handshake(&response(3, 2000, false), false).is_ok());
assert!(require_handshake(&response(3, 0, true), false).is_ok());
@@ -541,6 +696,7 @@ mod tests {
assert!(require_handshake(&response(3, 0, false), false).is_err());
assert!(require_handshake(&response(2, 0, true), true).is_err());
assert!(require_handshake("{\"status\":\"ok\",\"protocol_version\":3}", true).is_err());
+ assert!(require_handshake("{\"status\":\"ok\",\"protocol_version\":3,\"uid\":2000,\"read_only\":false}", false).is_err());
}
#[test]
@@ -582,6 +738,33 @@ mod tests {
assert!(require_ok("invalid").is_err());
}
+ #[test]
+ fn cancellation_is_scoped_to_the_active_id_and_registration_cleans_up() {
+ let _operation = DAEMON_OPERATION.lock().unwrap();
+ let cancelled = Arc::new(AtomicBool::new(false));
+ *ACTIVE_SCAN.lock().unwrap() = Some(ActiveScan {
+ id: "current".into(), cancelled: cancelled.clone(), progress_pending: Arc::new(AtomicBool::new(true)), socket: None,
+ });
+ let registration = ScanRegistration("current".into());
+ acknowledge_scan_progress("previous".into()).unwrap();
+ assert!(ACTIVE_SCAN.lock().unwrap().as_ref().unwrap().progress_pending.load(Ordering::SeqCst));
+ acknowledge_scan_progress("current".into()).unwrap();
+ assert!(!ACTIVE_SCAN.lock().unwrap().as_ref().unwrap().progress_pending.load(Ordering::SeqCst));
+ cancel_scan("previous".into()).unwrap();
+ assert!(!cancelled.load(Ordering::SeqCst));
+ cancel_scan("current".into()).unwrap();
+ assert!(cancelled.load(Ordering::SeqCst));
+ drop(registration);
+ assert!(ACTIVE_SCAN.lock().unwrap().is_none());
+ // An old guard must not clear a newer scan registration.
+ *ACTIVE_SCAN.lock().unwrap() = Some(ActiveScan {
+ id: "next".into(), cancelled, progress_pending: Arc::new(AtomicBool::new(false)), socket: None,
+ });
+ drop(ScanRegistration("current".into()));
+ assert!(ACTIVE_SCAN.lock().unwrap().is_some());
+ drop(ScanRegistration("next".into()));
+ }
+
#[test]
fn invalid_filename_bytes_are_not_replaced() {
assert!(decode_daemon_response(b"{\"path\":\"/sdcard/report\xff\"}".to_vec()).is_err());
diff --git a/src-tauri/src/scan_stream.rs b/src-tauri/src/scan_stream.rs
new file mode 100644
index 0000000..2eb7dc7
--- /dev/null
+++ b/src-tauri/src/scan_stream.rs
@@ -0,0 +1,760 @@
+//! Bounded stream-v1 decoder. Compact records exist only for construction of
+//! the current UI response; persistent ownership/query APIs belong to #29.
+use serde::{
+ ser::{SerializeSeq, SerializeStruct},
+ Deserialize, Serialize,
+};
+use std::io::{Read, Write};
+use std::time::{Duration, Instant};
+
+pub const MAX_FRAME_BYTES: usize = 128 * 1024;
+const MAX_BATCH_ENTRIES: usize = 128;
+const MAX_NODES: usize = 2_000_000;
+const MAX_TREE_BYTES: usize = 128 * 1024 * 1024;
+const MAX_RESULT_BYTES: usize = 256 * 1024 * 1024;
+const MAX_SAFE_INTEGER: u64 = (1u64 << 53) - 1;
+const NONE: u32 = u32::MAX;
+
+#[derive(Deserialize)]
+#[serde(
+ tag = "type",
+ content = "data",
+ rename_all = "snake_case",
+ deny_unknown_fields
+)]
+enum Frame {
+ Started {
+ stream_version: u32,
+ root: String,
+ read_only: bool,
+ },
+ Entries {
+ entries: Vec<Entry>,
+ },
+ Done {
+ total_files: u64,
+ total_dirs: u64,
+ total_size: u64,
+ errors: u64,
+ skipped: u64,
+ scan_time_ms: u64,
+ scan_threads: u32,
+ serialize_ms: u64,
+ send_ms: u64,
+ bytes_sent: u64,
+ },
+ Error {
+ message: String,
+ },
+}
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+struct Entry {
+ id: usize,
+ parent: Option<usize>,
+ name: String,
+ kind: Kind,
+ size: u64,
+ counted: bool,
+}
+#[derive(Deserialize, PartialEq, Copy, Clone)]
+#[serde(rename_all = "snake_case")]
+enum Kind {
+ File,
+ Directory,
+ Other,
+}
+struct Node {
+ name: String,
+ size: u64,
+ parent: u32,
+ first_child: u32,
+ next_sibling: u32,
+ path_bytes: u32,
+ depth: u8,
+ kind: Kind,
+ counted: bool,
+}
+// Serialize directly from compact records. Full paths and recursive child
+// objects are never materialized in a second host tree.
+struct NodeView<'a> {
+ nodes: &'a [Node],
+ index: u32,
+ path: &'a str,
+}
+impl Serialize for NodeView<'_> {
+ fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+ let node = &self.nodes[self.index as usize];
+ let directory = node.kind == Kind::Directory;
+ let fields = 4 + usize::from(directory) + usize::from(!node.counted);
+ let mut result = serializer.serialize_struct("Node", fields)?;
+ result.serialize_field("name", &node.name)?;
+ result.serialize_field("path", &self.path)?;
+ result.serialize_field("type", if directory { "directory" } else { "file" })?;
+ result.serialize_field("size", &node.size)?;
+ // Ordinary nodes keep the existing frontend shape. Only placeholders
+ // need an extra field to preserve deletion/counting semantics.
+ if !node.counted {
+ result.serialize_field("counted", &false)?;
+ }
+ if directory {
+ result.serialize_field(
+ "children",
+ &ChildrenView {
+ nodes: self.nodes,
+ first: node.first_child,
+ path: self.path,
+ },
+ )?;
+ }
+ result.end()
+ }
+}
+struct ChildrenView<'a> {
+ nodes: &'a [Node],
+ first: u32,
+ path: &'a str,
+}
+impl Serialize for ChildrenView<'_> {
+ fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+ let mut sequence = serializer.serialize_seq(None)?;
+ let mut index = self.first;
+ while index != NONE {
+ let node = &self.nodes[index as usize];
+ let path = format!(
+ "{}{}{}",
+ self.path,
+ if self.path == "/" { "" } else { "/" },
+ node.name
+ );
+ sequence.serialize_element(&NodeView {
+ nodes: self.nodes,
+ index,
+ path: &path,
+ })?;
+ index = node.next_sibling;
+ }
+ sequence.end()
+ }
+}
+#[derive(Clone, Serialize, Default)]
+pub struct Progress {
+ pub files: u64,
+ pub directories: u64,
+ pub total_size: u64,
+ pub recent_names: Vec<String>,
+}
+#[derive(Serialize)]
+pub struct Response {
+ #[serde(skip)]
+ nodes: Vec<Node>,
+ #[serde(skip)]
+ root: String,
+ status: &'static str,
+ total_files: u64,
+ total_dirs: u64,
+ total_size: u64,
+ errors: u64,
+ skipped: u64,
+ read_only: bool,
+ scan_time_ms: u64,
+ scan_threads: u32,
+ streamed: bool,
+ traverse_ms: u64,
+ sort_ms: u64,
+ serialize_ms: u64,
+ send_ms: u64,
+ bytes_sent: u64,
+}
+impl Response {
+ pub fn root(&self) -> &str {
+ &self.root
+ }
+ pub fn json(&self) -> Result<String, String> {
+ struct Limited(Vec<u8>);
+ impl Write for Limited {
+ fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
+ if bytes.len() > MAX_RESULT_BYTES.saturating_sub(self.0.len()) {
+ return Err(std::io::Error::other(
+ "Scan exceeds the current UI result limit",
+ ));
+ }
+ self.0.extend_from_slice(bytes);
+ Ok(bytes.len())
+ }
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+ }
+ #[derive(Serialize)]
+ struct View<'a> {
+ #[serde(flatten)]
+ response: &'a Response,
+ tree: NodeView<'a>,
+ }
+ let mut output = Limited(Vec::new());
+ serde_json::to_writer(
+ &mut output,
+ &View {
+ response: self,
+ tree: NodeView {
+ nodes: &self.nodes,
+ index: 0,
+ path: &self.root,
+ },
+ },
+ )
+ .map_err(|e| format!("Cannot display scan: {e}"))?;
+ String::from_utf8(output.0).map_err(|_| "Invalid scan encoding".into())
+ }
+}
+pub trait StreamReader: Read {
+ fn begin_frame(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+}
+impl<T: AsRef<[u8]>> StreamReader for std::io::Cursor<T> {}
+// Socket timeouts reset after every short read. Enforce an absolute deadline
+// for each complete frame too, including its length prefix.
+pub struct SocketReader<'a> {
+ socket: &'a mut std::net::TcpStream,
+ deadline: Instant,
+}
+impl<'a> SocketReader<'a> {
+ pub fn new(socket: &'a mut std::net::TcpStream) -> Self {
+ Self {
+ socket,
+ deadline: Instant::now() + super::TCP_READ_TIMEOUT,
+ }
+ }
+}
+impl StreamReader for SocketReader<'_> {
+ fn begin_frame(&mut self) -> std::io::Result<()> {
+ self.deadline = Instant::now() + super::TCP_READ_TIMEOUT;
+ Ok(())
+ }
+}
+impl Read for SocketReader<'_> {
+ fn read(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {
+ let remaining = self
+ .deadline
+ .checked_duration_since(Instant::now())
+ .filter(|duration| !duration.is_zero())
+ .ok_or_else(|| {
+ std::io::Error::new(std::io::ErrorKind::TimedOut, "Scan frame deadline exceeded")
+ })?;
+ self.socket.set_read_timeout(Some(remaining))?;
+ self.socket.read(bytes)
+ }
+}
+fn frame(reader: &mut impl StreamReader) -> Result<(Frame, usize), String> {
+ reader.begin_frame().map_err(|e| e.to_string())?;
+ let mut header = [0u8; 4];
+ reader
+ .read_exact(&mut header)
+ .map_err(|e| format!("Incomplete scan frame header: {e}"))?;
+ let length = u32::from_be_bytes(header) as usize;
+ if length == 0 || length > MAX_FRAME_BYTES {
+ return Err("Invalid scan frame size".into());
+ }
+ let mut bytes = vec![0u8; length];
+ reader
+ .read_exact(&mut bytes)
+ .map_err(|e| format!("Incomplete scan frame payload: {e}"))?;
+ let value = serde_json::from_slice(&bytes)
+ .map_err(|e| format!("Invalid scan frame (filenames must be valid UTF-8): {e}"))?;
+ Ok((value, length + 4))
+}
+fn safe_add(a: u64, b: u64) -> Result<u64, String> {
+ a.checked_add(b)
+ .filter(|v| *v <= MAX_SAFE_INTEGER)
+ .ok_or_else(|| "Scan total exceeds the UI's exact integer range".into())
+}
+
+pub fn read(
+ reader: &mut impl StreamReader,
+ expected_read_only: bool,
+ mut progress: impl FnMut(&Progress) -> Result<(), String>,
+) -> Result<Response, String> {
+ let (first, mut bytes_received) = frame(reader)?;
+ let root = match first {
+ Frame::Error { message } => return Err(message),
+ Frame::Started {
+ stream_version: 1,
+ root,
+ read_only,
+ } if read_only == expected_read_only => root,
+ _ => return Err("Invalid scan start or access-mode negotiation".into()),
+ };
+ if !root.starts_with('/')
+ || root.contains('\0')
+ || root.len() > 16 * 1024
+ || (root.len() > 1 && root.ends_with('/'))
+ {
+ return Err("Invalid scan root".into());
+ }
+ let root_name = if root == "/" {
+ "/"
+ } else {
+ root.rsplit('/').next().unwrap()
+ };
+ let mut nodes: Vec<Node> = Vec::new();
+ let mut tree_bytes = 0usize;
+ let mut observed = Progress::default();
+ let mut last_progress = Instant::now();
+ let mut first_results_sent = false;
+ progress(&observed)?;
+ loop {
+ let (item, byte_count) = frame(reader)?;
+ match item {
+ Frame::Error { message } => return Err(message),
+ Frame::Started { .. } => return Err("Duplicate scan start".into()),
+ Frame::Entries { entries } => {
+ if entries.is_empty() || entries.len() > MAX_BATCH_ENTRIES {
+ return Err("Invalid scan batch size".into());
+ }
+ for entry in entries {
+ if entry.id != nodes.len()
+ || nodes.len() >= MAX_NODES
+ || entry.size > MAX_SAFE_INTEGER
+ || (entry.kind != Kind::File && entry.size != 0)
+ || (!entry.counted && entry.size != 0)
+ || (entry.kind == Kind::Other && entry.counted)
+ {
+ return Err(
+ "Invalid scan entry or scan exceeds the current entry limit".into()
+ );
+ }
+ let (path_bytes, depth, next_sibling) = if let Some(parent_id) = entry.parent {
+ let parent = nodes
+ .get(parent_id)
+ .ok_or("Scan child precedes its parent")?;
+ if parent.kind != Kind::Directory
+ || !parent.counted
+ || entry.name.is_empty()
+ || entry.name == "."
+ || entry.name == ".."
+ || entry.name.contains(['/', '\0'])
+ || entry.name.len() > 255
+ {
+ return Err("Invalid scan parent or filename".into());
+ }
+ (
+ parent.path_bytes as usize
+ + usize::from(!(parent_id == 0 && root == "/"))
+ + entry.name.len(),
+ parent.depth as usize + 1,
+ parent.first_child,
+ )
+ } else {
+ if !nodes.is_empty()
+ || entry.kind != Kind::Directory
+ || !entry.counted
+ || entry.name != root_name
+ {
+ return Err("Invalid scan root entry".into());
+ }
+ (root.len(), 0, NONE)
+ };
+ if path_bytes > 16 * 1024 || depth > 64 {
+ return Err("Scan path/depth limit exceeded".into());
+ }
+ // Conservative budget also accounts for the final path
+ // representation, not just the smaller compact records.
+ tree_bytes = tree_bytes
+ .checked_add(path_bytes + entry.name.len() + 256)
+ .ok_or("Scan memory limit exceeded")?;
+ if tree_bytes > MAX_TREE_BYTES {
+ return Err("Scan exceeds the current UI memory limit".into());
+ }
+ if entry.counted {
+ if entry.kind == Kind::Directory {
+ observed.directories = safe_add(observed.directories, 1)?;
+ } else {
+ observed.files = safe_add(observed.files, 1)?;
+ observed.total_size = safe_add(observed.total_size, entry.size)?;
+ }
+ }
+ if let Some(parent) = entry.parent {
+ nodes[parent].first_child = entry.id as u32;
+ }
+ nodes.push(Node {
+ name: entry.name,
+ size: entry.size,
+ parent: entry.parent.map_or(NONE, |id| id as u32),
+ first_child: NONE,
+ next_sibling,
+ path_bytes: path_bytes as u32,
+ depth: depth as u8,
+ kind: entry.kind,
+ counted: entry.counted,
+ });
+ }
+ if (!first_results_sent && nodes.len() > 1)
+ || last_progress.elapsed() >= Duration::from_millis(100)
+ {
+ observed.recent_names = nodes
+ .iter()
+ .skip(1)
+ .rev()
+ .take(5)
+ .map(|node| node.name.clone())
+ .collect();
+ observed.recent_names.reverse();
+ progress(&observed)?;
+ first_results_sent = true;
+ last_progress = Instant::now();
+ }
+ }
+ Frame::Done {
+ total_files,
+ total_dirs,
+ total_size,
+ errors,
+ skipped,
+ scan_time_ms,
+ scan_threads,
+ serialize_ms,
+ send_ms,
+ bytes_sent,
+ } => {
+ if nodes.is_empty()
+ || total_files != observed.files
+ || total_dirs != observed.directories
+ || total_size != observed.total_size
+ || bytes_sent != bytes_received as u64
+ || !(1..=8).contains(&scan_threads)
+ || (expected_read_only && scan_threads != 1)
+ || [
+ errors,
+ skipped,
+ scan_time_ms,
+ serialize_ms,
+ send_ms,
+ bytes_sent,
+ ]
+ .iter()
+ .any(|v| *v > MAX_SAFE_INTEGER)
+ {
+ return Err(
+ "Scan completion does not match received entries or negotiated mode".into(),
+ );
+ }
+ let mut trailing = [0];
+ if reader
+ .read(&mut trailing)
+ .map_err(|e| format!("Scan did not close after completion: {e}"))?
+ != 0
+ {
+ return Err("Unexpected data after scan completion".into());
+ }
+ let sort_start = Instant::now();
+ for index in (1..nodes.len()).rev() {
+ let parent = nodes[index].parent as usize;
+ nodes[parent].size = safe_add(nodes[parent].size, nodes[index].size)?;
+ }
+ if nodes[0].size != total_size {
+ return Err("Scan tree does not match completion totals".into());
+ }
+ let mut children = Vec::new();
+ for parent in 0..nodes.len() {
+ children.clear();
+ let mut child = nodes[parent].first_child;
+ while child != NONE {
+ children.push(child);
+ child = nodes[child as usize].next_sibling;
+ }
+ children.sort_unstable_by(|a, b| {
+ nodes[*a as usize].name.cmp(&nodes[*b as usize].name)
+ });
+ if children
+ .windows(2)
+ .any(|pair| nodes[pair[0] as usize].name == nodes[pair[1] as usize].name)
+ {
+ return Err("Duplicate filename in scan directory".into());
+ }
+ children.sort_unstable_by(|a, b| {
+ nodes[*b as usize]
+ .size
+ .cmp(&nodes[*a as usize].size)
+ .then(nodes[*a as usize].name.cmp(&nodes[*b as usize].name))
+ });
+ for (index, child) in children.iter().enumerate() {
+ nodes[*child as usize].next_sibling =
+ children.get(index + 1).copied().unwrap_or(NONE);
+ }
+ nodes[parent].first_child = children.first().copied().unwrap_or(NONE);
+ }
+ observed.recent_names = nodes
+ .iter()
+ .skip(1)
+ .rev()
+ .take(5)
+ .map(|node| node.name.clone())
+ .collect();
+ observed.recent_names.reverse();
+ progress(&observed)?;
+ return Ok(Response {
+ status: "ok",
+ nodes,
+ root,
+ total_files,
+ total_dirs,
+ total_size,
+ errors,
+ skipped,
+ read_only: expected_read_only,
+ scan_time_ms,
+ scan_threads,
+ streamed: true,
+ traverse_ms: scan_time_ms,
+ sort_ms: sort_start.elapsed().as_millis() as u64,
+ serialize_ms,
+ send_ms,
+ bytes_sent,
+ });
+ }
+ }
+ bytes_received = bytes_received
+ .checked_add(byte_count)
+ .ok_or("Scan byte counter overflow")?;
+ }
+}
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::{json, Value};
+ use std::io::Cursor;
+ fn encode(value: &Value) -> Vec<u8> {
+ let mut fields = value.as_object().unwrap().clone();
+ let kind = fields.remove("type").unwrap();
+ let data = serde_json::to_vec(&json!({"type":kind,"data":fields})).unwrap();
+ let mut bytes = (data.len() as u32).to_be_bytes().to_vec();
+ bytes.extend(data);
+ bytes
+ }
+ fn start() -> Value {
+ json!({"type":"started","stream_version":1,"root":"/fixture","read_only":false})
+ }
+ fn root() -> Value {
+ json!({"id":0,"parent":null,"name":"fixture","kind":"directory","size":0,"counted":true})
+ }
+ fn file() -> Value {
+ json!({"id":1,"parent":0,"name":"file","kind":"file","size":7,"counted":true})
+ }
+ fn stream(entries: Vec<Value>, changes: Value) -> Vec<u8> {
+ let mut bytes = encode(&start());
+ bytes.extend(encode(&json!({"type":"entries","entries":entries})));
+ let mut done = json!({"type":"done","total_files":1,"total_dirs":1,"total_size":7,
+ "errors":0,"skipped":0,"scan_time_ms":1,"scan_threads":4,"serialize_ms":0,"send_ms":0,"bytes_sent":bytes.len()});
+ for (key, value) in changes.as_object().unwrap() {
+ done[key] = value.clone();
+ }
+ bytes.extend(encode(&done));
+ bytes
+ }
+ fn parse(bytes: Vec<u8>) -> Result<Response, String> {
+ read(&mut Cursor::new(bytes), false, |_| Ok(()))
+ }
+ #[test]
+ fn reconstructs_exact_paths_counts_sorted_sizes_and_progress() {
+ let entries = vec![
+ root(),
+ json!({"id":1,"parent":0,"name":"empty","kind":"directory","size":0,"counted":true}),
+ json!({"id":2,"parent":1,"name":" 写真\n\" ","kind":"file","size":7,"counted":true}),
+ json!({"id":3,"parent":0,"name":"fifo","kind":"other","size":0,"counted":false}),
+ ];
+ let mut snapshots = Vec::new();
+ let result = read(
+ &mut Cursor::new(stream(
+ entries,
+ json!({"total_dirs":2,"errors":3,"skipped":4}),
+ )),
+ false,
+ |p| {
+ snapshots.push(p.clone());
+ Ok(())
+ },
+ )
+ .unwrap();
+ let value: Value = serde_json::from_str(&result.json().unwrap()).unwrap();
+ assert_eq!(value["tree"]["size"], 7);
+ assert_eq!(
+ value["tree"]["children"][0]["children"][0]["path"],
+ "/fixture/empty/ 写真\n\" "
+ );
+ assert_eq!(value["tree"]["children"][1]["counted"], false);
+ assert_eq!(value["errors"], 3);
+ assert_eq!(value["skipped"], 4);
+ assert_eq!(snapshots.first().unwrap().files, 0);
+ assert_eq!(snapshots.last().unwrap().files, 1);
+ assert!(snapshots.len() >= 3);
+ }
+ #[test]
+ fn rejects_every_truncation_and_requires_terminal_eof() {
+ let bytes = stream(vec![root(), file()], json!({}));
+ for length in 0..bytes.len() {
+ assert!(parse(bytes[..length].to_vec()).is_err(), "length {length}");
+ }
+ assert!(parse(bytes.clone()).is_ok());
+ for suffix in [
+ vec![0],
+ encode(&json!({"type":"error","message":"late"})),
+ bytes.clone(),
+ ] {
+ let mut extra = bytes.clone();
+ extra.extend(suffix);
+ assert!(parse(extra).is_err());
+ }
+ }
+ #[test]
+ fn rejects_zero_oversized_and_malformed_frames_without_unbounded_reads() {
+ for size in [0u32, MAX_FRAME_BYTES as u32 + 1, u32::MAX] {
+ assert!(parse(size.to_be_bytes().to_vec()).is_err());
+ }
+ assert!(parse(encode(&json!({"type":"unknown"}))).is_err());
+ let mut unknown_field = start();
+ unknown_field["unexpected"] = json!(true);
+ assert!(parse(encode(&unknown_field)).is_err());
+ let mut bytes = encode(&start());
+ bytes.extend(encode(&start()));
+ assert!(parse(bytes).is_err());
+ let mut bytes = encode(&start());
+ bytes.extend(encode(&json!({"type":"entries","entries":[]})));
+ assert!(parse(bytes).is_err());
+ let entries = vec![root(); MAX_BATCH_ENTRIES + 1];
+ assert!(parse(stream(entries, json!({}))).is_err());
+ let mut invalid_utf8 = encode(&start());
+ invalid_utf8.extend([0, 0, 0, 3, b'"', 255, b'"']);
+ assert!(parse(invalid_utf8).is_err());
+ }
+ #[test]
+ fn rejects_invalid_identifiers_parents_names_sizes_and_duplicates() {
+ for changes in [
+ json!({"id":0}),
+ json!({"id":3}),
+ json!({"parent":1}),
+ json!({"parent":99}),
+ json!({"parent":null}),
+ json!({"name":""}),
+ json!({"name":".."}),
+ json!({"name":"a/b"}),
+ json!({"name":"a\u{0}b"}),
+ json!({"name":"x".repeat(256)}),
+ json!({"size":-1}),
+ json!({"size":MAX_SAFE_INTEGER + 1}),
+ json!({"kind":"other"}),
+ json!({"counted":false}),
+ ] {
+ let mut bad = file();
+ for (key, value) in changes.as_object().unwrap() {
+ bad[key] = value.clone();
+ }
+ assert!(
+ parse(stream(vec![root(), bad], json!({}))).is_err(),
+ "{changes}"
+ );
+ }
+ let mut duplicate = file();
+ duplicate["id"] = json!(2);
+ assert!(parse(stream(
+ vec![root(), file(), duplicate],
+ json!({"total_files":2,"total_size":14})
+ ))
+ .is_err());
+ let mut child = file();
+ child["id"] = json!(2);
+ child["parent"] = json!(1);
+ assert!(parse(stream(
+ vec![root(), file(), child],
+ json!({"total_files":2,"total_size":14})
+ ))
+ .is_err());
+ }
+ #[test]
+ fn rejects_mismatched_completion_and_root_modes() {
+ for changes in [
+ json!({"total_files":0}),
+ json!({"total_dirs":2}),
+ json!({"total_size":8}),
+ json!({"bytes_sent":0}),
+ json!({"scan_threads":0}),
+ json!({"scan_threads":9}),
+ json!({"errors":MAX_SAFE_INTEGER+1}),
+ ] {
+ assert!(parse(stream(vec![root(), file()], changes)).is_err());
+ }
+ let bytes = stream(vec![root(), file()], json!({}));
+ assert!(read(&mut Cursor::new(bytes), true, |_| Ok(())).is_err());
+ for root_path in ["relative", "", "/fixture/", "/fi\u{0}xture"] {
+ let mut bad = start();
+ bad["root"] = json!(root_path);
+ assert!(parse(encode(&bad)).is_err());
+ }
+ }
+ #[test]
+ fn preserves_uncounted_root_mode_entries_and_rejects_children_under_them() {
+ let mut bytes = encode(
+ &json!({"type":"started","stream_version":1,"root":"/fixture","read_only":true}),
+ );
+ bytes.extend(encode(&json!({"type":"entries","entries":[root(),file(),
+ {"id":2,"parent":0,"name":"alias","kind":"file","size":0,"counted":false}]})));
+ let count = bytes.len();
+ bytes.extend(encode(&json!({"type":"done","total_files":1,"total_dirs":1,"total_size":7,
+ "errors":0,"skipped":1,"scan_time_ms":0,"scan_threads":1,"serialize_ms":0,"send_ms":0,"bytes_sent":count})));
+ assert!(read(&mut Cursor::new(bytes), true, |_| Ok(())).is_ok());
+ let alias =
+ json!({"id":1,"parent":0,"name":"alias","kind":"directory","size":0,"counted":false});
+ let mut child = file();
+ child["id"] = json!(2);
+ child["parent"] = json!(1);
+ assert!(parse(stream(vec![root(), alias, child], json!({}))).is_err());
+ }
+ #[test]
+ fn socket_deadline_does_not_reset_after_a_short_read() {
+ use std::net::{TcpListener, TcpStream};
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ let mut client = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
+ let (mut peer, _) = listener.accept().unwrap();
+ let mut reader = SocketReader::new(&mut client);
+ let deadline = reader.deadline;
+ peer.write_all(b"x").unwrap();
+ let mut byte = [0];
+ assert_eq!(reader.read(&mut byte).unwrap(), 1);
+ assert_eq!(reader.deadline, deadline);
+ // Expire the existing frame deadline while the next byte is buffered.
+ reader.deadline = Instant::now() - Duration::from_millis(1);
+ peer.write_all(b"y").unwrap();
+ assert_eq!(
+ reader.read(&mut byte).unwrap_err().kind(),
+ std::io::ErrorKind::TimedOut
+ );
+ reader.begin_frame().unwrap();
+ assert_eq!(reader.read(&mut byte).unwrap(), 1);
+ assert_eq!(byte, [b'y']);
+ }
+
+ #[test]
+ fn progress_failure_aborts_and_io_errors_after_done_are_not_success() {
+ let bytes = stream(vec![root(), file()], json!({}));
+ assert!(read(&mut Cursor::new(bytes.clone()), false, |_| Err(
+ "view closed".into()
+ ))
+ .is_err());
+ struct NoEof(Cursor<Vec<u8>>);
+ impl StreamReader for NoEof {}
+ impl Read for NoEof {
+ fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> {
+ if self.0.position() == self.0.get_ref().len() as u64 {
+ Err(std::io::Error::new(
+ std::io::ErrorKind::TimedOut,
+ "peer stayed open",
+ ))
+ } else {
+ self.0.read(out)
+ }
+ }
+ }
+ assert!(read(&mut NoEof(Cursor::new(bytes)), false, |_| Ok(())).is_err());
+ }
+}
diff --git a/src/App.tsx b/src/App.tsx
index d057571..1c906be 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -1,5 +1,5 @@
import { useState, useCallback, useEffect, useRef } from "react";
-import { invoke } from "@tauri-apps/api/core";
+import { Channel, invoke } from "@tauri-apps/api/core";
import { Treemap, ResponsiveContainer, Tooltip as RechartsTooltip } from "recharts";
import "./App.css";
@@ -10,11 +10,13 @@ interface FileNode {
path: string;
type: "file" | "directory";
size: number;
+ counted?: boolean;
children?: FileNode[];
}
interface ScanResponse {
status: string;
+ streamed?: boolean;
scan_time_ms: number;
total_files: number;
total_dirs: number;
@@ -35,7 +37,7 @@ interface ScanResponse {
const scanPhaseLog = (r: ScanResponse): string | null => {
if (r.traverse_ms === undefined) return null;
const kb = r.bytes_sent !== undefined ? `, ${(r.bytes_sent / 1024).toFixed(0)} KB sent` : "";
- return `[SCAN] Phases: traverse ${r.traverse_ms}ms · sort ${r.sort_ms}ms · serialize ${r.serialize_ms}ms · send ${r.send_ms}ms${kb}`;
+ return `[SCAN] ${r.streamed ? "Stream timings (overlap): scan" : "Phases: traverse"} ${r.traverse_ms}ms · sort ${r.sort_ms}ms · serialize ${r.serialize_ms}ms · send ${r.send_ms}ms${kb}`;
};
interface Toast {
@@ -97,10 +99,10 @@ function buildBreadcrumbs(root: FileNode, targetPath: string): { name: string; p
function countNodeStats(node: FileNode): { size: number; files: number; dirs: number } {
if (node.type === "file") {
- return { size: node.size, files: 1, dirs: 0 };
+ return { size: node.size, files: node.counted === false ? 0 : 1, dirs: 0 };
}
let files = 0;
- let dirs = 1;
+ let dirs = node.counted === false ? 0 : 1;
if (node.children) {
for (const child of node.children) {
const stats = countNodeStats(child);
@@ -361,7 +363,17 @@ function SetupScreen({ onConnect, loading, rootMode, onRootModeChange, rootPath,
// ── Scanning Screen ─────────────────────────────────────────────────────────
-function ScanningScreen({ statusText }: { statusText: string }) {
+interface ScanProgress {
+ scan_id: string;
+ files: number;
+ directories: number;
+ total_size: number;
+ recent_names: string[];
+}
+
+function ScanningScreen({ statusText, progress, onCancel, cancelling }: {
+ statusText: string; progress: ScanProgress | null; onCancel: () => void; cancelling: boolean;
+}) {
return (
<div className="flex flex-col items-center justify-center flex-1 gap-8 animate-fade-in-up">
<div className="relative w-32 h-32">
@@ -386,6 +398,21 @@ function ScanningScreen({ statusText }: { statusText: string }) {
<div className="text-center">
<h2 className="text-lg font-semibold text-zinc-200">Scanning Storage</h2>
<p className="mt-1 text-sm text-zinc-500 font-mono">{statusText}</p>
+ {progress && (
+ <div className="mt-4 space-y-2" aria-live="polite">
+ <p className="text-sm text-zinc-300">
+ {formatNumber(progress.files)} files · {formatNumber(progress.directories)} directories · {formatBytes(progress.total_size)} found
+ </p>
+ <p className="text-xs text-zinc-500">Partial results — totals may increase</p>
+ <ul className="text-xs text-zinc-400 max-w-sm mx-auto space-y-1">
+ {progress.recent_names.map((name, index) => <li className="truncate" key={index}>{name}</li>)}
+ </ul>
+ </div>
+ )}
+ <button onClick={onCancel} disabled={cancelling}
+ className="mt-5 px-4 py-2 rounded-lg text-sm bg-zinc-800 text-zinc-300 hover:bg-zinc-700 disabled:opacity-50">
+ {cancelling ? "Cancelling…" : "Cancel scan"}
+ </button>
</div>
</div>
);
@@ -716,6 +743,9 @@ function App() {
const [rootMode, setRootMode] = useState(false);
const [rootPath, setRootPath] = useState("/data");
const [scanData, setScanData] = useState<ScanResponse | null>(null);
+ const [scanProgress, setScanProgress] = useState<ScanProgress | null>(null);
+ const [cancelling, setCancelling] = useState(false);
+ const activeScan = useRef<string | null>(null);
const [statusText, setStatusText] = useState("Initializing…");
const [toasts, setToasts] = useState<Toast[]>([]);
const [logs, setLogs] = useState<string[]>([]);
@@ -750,6 +780,37 @@ function App() {
setTimeout(() => setToasts((prev) => prev.filter((t) => t.id !== id)), 300);
}, []);
+ const requestScan = useCallback(async (path: string): Promise<ScanResponse> => {
+ const scanId = crypto.randomUUID();
+ activeScan.current = scanId;
+ setScanProgress(null);
+ setCancelling(false);
+ const onProgress = new Channel<ScanProgress>();
+ onProgress.onmessage = (progress) => {
+ if (activeScan.current === scanId && progress.scan_id === scanId) setScanProgress(progress);
+ void invoke("acknowledge_scan_progress", { scanId: progress.scan_id }).catch(() => {
+ // The completed/cancelled scan may already have released its channel.
+ });
+ };
+ try {
+ const raw = await invoke<string>("run_scan", { path, scanId, onProgress });
+ const parsed: ScanResponse = JSON.parse(raw);
+ if (parsed.status !== "ok") throw new Error("Scan returned non-ok status");
+ return parsed;
+ } finally {
+ if (activeScan.current === scanId) activeScan.current = null;
+ setCancelling(false);
+ }
+ }, []);
+
+ const handleCancelScan = useCallback(async () => {
+ const scanId = activeScan.current;
+ if (!scanId) return;
+ setCancelling(true);
+ try { await invoke("cancel_scan", { scanId }); }
+ catch (err) { pushToast(String(err), "error"); setCancelling(false); }
+ }, [pushToast]);
+
// ── Connect flow ────────────────────────────────────────────────────────
const handleConnect = useCallback(async () => {
setPhase("connecting");
@@ -770,8 +831,7 @@ function App() {
setPhase("scanning");
setStatusText(`Scanning ${scanPath} …`);
addLog(`[SCAN] Requesting ${scanPath}${rootMode ? " with read-only root access" : ""}...`);
- const raw = await invoke<string>("run_scan", { path: scanPath });
- const parsed: ScanResponse = JSON.parse(raw);
+ const parsed = await requestScan(scanPath);
if (parsed.status !== "ok") throw new Error("Scan returned non-ok status");
@@ -785,11 +845,11 @@ function App() {
try { await invoke<string>("stop_daemon"); } catch { /* show the original connection error */ }
}
const message = err instanceof Error ? err.message : String(err);
- pushToast(message, "error");
- addLog(`[ERROR] ${message}`);
+ pushToast(message, message === "Scan cancelled" ? "info" : "error");
+ addLog(`${message === "Scan cancelled" ? "[SCAN]" : "[ERROR]"} ${message}`);
setPhase("setup");
}
- }, [pushToast, addLog, rootMode, rootPath]);
+ }, [pushToast, addLog, rootMode, rootPath, requestScan]);
// ── Rescan ──────────────────────────────────────────────────────────────
const handleRescan = useCallback(async () => {
@@ -799,8 +859,7 @@ function App() {
setStatusText(`Re-scanning ${scanPath} …`);
addLog(`[SCAN] Re-scanning ${scanPath}...`);
try {
- const raw = await invoke<string>("run_scan", { path: scanPath });
- const parsed: ScanResponse = JSON.parse(raw);
+ const parsed = await requestScan(scanPath);
setScanData(parsed);
setPhase("result");
addLog(`[SCAN] Complete! ${parsed.scan_time_ms}ms.`);
@@ -808,11 +867,15 @@ function App() {
if (phases) addLog(phases);
} catch (err: unknown) {
const message = err instanceof Error ? err.message : String(err);
- pushToast(message, "error");
- addLog(`[ERROR] ${message}`);
- setPhase("result");
+ pushToast(message, message === "Scan cancelled" ? "info" : "error");
+ addLog(`${message === "Scan cancelled" ? "[SCAN]" : "[ERROR]"} ${message}`);
+ // The failed generation is not an authoritative deletion root. Clear
+ // old results rather than offering actions backed by an invalid scan.
+ try { await invoke("stop_daemon"); } catch { /* retain the scan error */ }
+ setScanData(null);
+ setPhase("setup");
}
- }, [pushToast, addLog, scanData]);
+ }, [pushToast, addLog, scanData, requestScan]);
// ── Disconnect ──────────────────────────────────────────────────────────
const handleDisconnect = useCallback(async () => {
@@ -899,7 +962,7 @@ function App() {
onRootPathChange={setRootPath}
/>
)}
- {phase === "scanning" && <ScanningScreen statusText={statusText} />}
+ {phase === "scanning" && <ScanningScreen statusText={statusText} progress={scanProgress} onCancel={handleCancelScan} cancelling={cancelling} />}
{phase === "result" && scanData && (
<ResultScreen
data={scanData}
diff --git a/tests/parallel_scan_test.cpp b/tests/parallel_scan_test.cpp
index 48e4d01..b23c210 100644
--- a/tests/parallel_scan_test.cpp
+++ b/tests/parallel_scan_test.cpp
@@ -5,6 +5,7 @@
#include <map>
#include <pthread.h>
#include <sys/resource.h>
+#include <thread>
static std::function<void(const char*, int, const char*)> checkpoint;
static void scan_checkpoint(const char* event, int parent, const char* name) {
@@ -52,7 +53,7 @@ struct Snapshot {
ScanStats stats;
parallel_scan::Result result;
};
-static Snapshot run(const std::string& path, int workers) {
+static Snapshot run(const std::string& path, int workers, bool streaming = false) {
safe_delete::Root root;
require(root.open(path), "root open failed");
Snapshot snapshot;
@@ -61,7 +62,24 @@ static Snapshot run(const std::string& path, int workers) {
snapshot.tree.is_dir = true;
snapshot.tree.device = root.identity.st_dev;
snapshot.tree.inode = root.identity.st_ino;
- snapshot.result = parallel_scan::run(root, snapshot.tree, snapshot.stats, workers, cfg::MAX_DEPTH);
+ if (streaming) {
+ int sockets[2];
+ require(::socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == 0, "socketpair failed");
+ safe_delete::Fd writer(sockets[0]), reader(sockets[1]);
+ std::thread drain([&] { char bytes[4096]; while (::recv(reader.get(), bytes, sizeof(bytes), 0) > 0) {} });
+ ScanOutput output(writer.get());
+ require(output.start(path), "stream start failed");
+ uint64_t id = 0;
+ require(output.entry(snapshot.tree, 0, "directory", true, id), "stream root failed");
+ stream_scan::Pool pool(root, output, snapshot.tree);
+ snapshot.result.workers = pool.run(snapshot.stats, workers);
+ snapshot.result.queue_peak = pool.queue_peak();
+ require(output.finish(snapshot.stats, 0, snapshot.result.workers), "stream finish failed");
+ ::shutdown(writer.get(), SHUT_WR);
+ drain.join();
+ } else {
+ snapshot.result = parallel_scan::run(root, snapshot.tree, snapshot.stats, workers, cfg::MAX_DEPTH);
+ }
require(snapshot.result.workers >= 1 && snapshot.result.workers <= workers,
"worker count out of bounds");
require(snapshot.result.queue_peak <= parallel_scan::MAX_PENDING, "queue exceeded bound");
@@ -85,7 +103,7 @@ static void same(const Snapshot& actual, const FileNode& expected, const ScanSta
actual.stats.total_size == stats.total_size && actual.stats.errors == stats.errors &&
actual.stats.skipped == stats.skipped, "parallel statistics differ from serial reference");
}
-static void equivalence() {
+static void equivalence(bool streaming = false) {
Fixture fixture;
for (int d = 0; d < 180; ++d) {
const std::string dir = "album " + std::to_string(d);
@@ -108,7 +126,13 @@ static void equivalence() {
g_read_only = false;
FileNode expected = scan(fixture.path, fixture.path.substr(fixture.path.rfind('/') + 1), stats, 0);
for (int workers : {1, 2, 4, 8}) {
- for (int repeat = 0; repeat < 3; ++repeat) same(run(fixture.path, workers), expected, stats);
+ for (int repeat = 0; repeat < 3; ++repeat) {
+ auto actual = run(fixture.path, workers, streaming);
+ if (!streaming) same(actual, expected, stats);
+ else require(actual.stats.files == stats.files && actual.stats.dirs == stats.dirs &&
+ actual.stats.total_size == stats.total_size && actual.stats.errors == stats.errors,
+ "stream statistics differ from serial reference");
+ }
}
}
static void depth() {
@@ -125,7 +149,7 @@ static void depth() {
require(stats.errors == 1 && stats.dirs == 65 && stats.files == 64, "bad depth fixture");
for (int workers : {1, 4, 8}) same(run(fixture.path, workers), expected, stats);
}
-static void replacement(const std::string& kind) {
+static void replacement(const std::string& kind, bool streaming = false) {
Fixture fixture;
fixture.dir("root");
fixture.dir("root/selected");
@@ -151,7 +175,7 @@ static void replacement(const std::string& kind) {
(fixture.path + "/root/selected").c_str()) == 0, "race symlink failed");
}
};
- const auto snapshot = run(fixture.path + "/root", 4);
+ const auto snapshot = run(fixture.path + "/root", 4, streaming);
checkpoint = {};
require(fired, "race checkpoint not reached");
require(snapshot.stats.total_size == (kind == "opened" ? 3 : 0), "replacement data scanned");
@@ -165,7 +189,7 @@ static size_t descriptors() {
::closedir(dir);
return count;
}
-static void resources() {
+static void resources(bool streaming = false) {
Fixture fixture;
for (int i = 0; i < 800; ++i) {
const auto dir = std::to_string(i);
@@ -178,11 +202,11 @@ static void resources() {
limited.rlim_cur = std::min<rlim_t>(saved.rlim_cur, 32);
require(::setrlimit(RLIMIT_NOFILE, &limited) == 0, "setrlimit failed");
const size_t before = descriptors();
- const auto serial = run(fixture.path, 1);
+ const auto serial = run(fixture.path, 1, streaming);
require(serial.result.queue_peak == parallel_scan::MAX_PENDING && serial.stats.files == 800,
"queue saturation fallback lost work");
for (int i = 0; i < 8; ++i) {
- const auto snapshot = run(fixture.path, 8);
+ const auto snapshot = run(fixture.path, 8, streaming);
require(snapshot.stats.files == 800 && snapshot.stats.total_size == 5600 &&
snapshot.stats.errors == 0, "low-descriptor scan failed");
}
@@ -191,12 +215,97 @@ static void resources() {
for (int failure : {0, 2}) {
fail_after = failure;
create_calls = 0;
- const auto snapshot = run(fixture.path, 8);
+ const auto snapshot = run(fixture.path, 8, streaming);
require(snapshot.result.workers == failure + 1, "worker creation fallback failed");
require(snapshot.stats.files == 800 && snapshot.stats.errors == 0, "worker fallback lost files");
}
fail_after = -1;
}
+static std::string read_frame(int fd) {
+ uint32_t size = 0;
+ require(::recv(fd, &size, sizeof(size), MSG_WAITALL) == sizeof(size), "missing frame header");
+ size = ntohl(size);
+ require(size > 0 && size <= ScanOutput::MAX_FRAME_BYTES, "bad frame size");
+ std::string text(size, ' ');
+ require(::recv(fd, text.data(), size, MSG_WAITALL) == size, "missing frame body");
+ return text;
+}
+static void stream_cancel() {
+ Fixture fixture;
+ fixture.dir("selected"); fixture.file("selected/later", 20); fixture.file("early", 7);
+ g_read_only = false;
+ require(g_scan_root.open(fixture.path), "previous root open failed");
+ int sockets[2];
+ require(::socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == 0, "socketpair failed");
+ safe_delete::Fd writer(sockets[0]), reader(sockets[1]);
+ std::mutex mutex;
+ std::condition_variable ready;
+ bool blocked = false, release = false;
+ checkpoint = [&](const char* event, int, const char* name) {
+ if (std::string(event) != "opened" || std::string(name) != fixture.path + "/selected") return;
+ std::unique_lock<std::mutex> lock(mutex);
+ blocked = true; ready.notify_one();
+ ready.wait(lock, [&] { return release; });
+ };
+ std::thread server([&] { stream_scan::handle(writer.get(), fixture.path); });
+ {
+ std::unique_lock<std::mutex> lock(mutex);
+ require(ready.wait_for(lock, std::chrono::seconds(5), [&] { return blocked; }), "traversal barrier not reached");
+ }
+ // Traversal is deterministically unfinished while these records arrive.
+ require(read_frame(reader.get()).find("started") != std::string::npos, "missing start");
+ // Worker callbacks are paused: the first entry is guaranteed to have been
+ // flushed immediately, irrespective of directory enumeration order.
+ require(read_frame(reader.get()).find("entries") != std::string::npos, "missing root record");
+ const auto first = read_frame(reader.get());
+ require(first.find("entries") != std::string::npos, "missing first result");
+ const bool early = first.find("early") != std::string::npos || first.find("selected") != std::string::npos;
+ require(early, "no result before completion");
+ ::shutdown(reader.get(), SHUT_RDWR);
+ {
+ std::lock_guard<std::mutex> lock(mutex); release = true; ready.notify_one();
+ }
+ server.join(); checkpoint = {};
+ require(g_scan_root.fd.get() < 0, "cancelled scan enabled deletion");
+}
+static void stream_limits_and_root_replacement(bool replace) {
+ Fixture fixture;
+ fixture.dir("root"); fixture.file("root/keep", 7);
+ for (int i = 0; i < 30; ++i) fixture.dir("root/dir" + std::to_string(i));
+ const auto path = fixture.path + "/root";
+ g_read_only = false;
+ int sockets[2];
+ require(::socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == 0, "socketpair failed");
+ safe_delete::Fd writer(sockets[0]), reader(sockets[1]);
+ std::string wire;
+ std::thread drain([&] { char bytes[4096]; ssize_t size; while ((size = ::recv(reader.get(), bytes, sizeof(bytes), 0)) > 0) wire.append(bytes, size); });
+ if (replace) {
+ bool fired = false;
+ checkpoint = [&](const char* event, int, const char* name) {
+ if (fired || std::string(event) != "opened" || std::string(name) != path) return;
+ fired = true;
+ require(::rename(path.c_str(), (fixture.path + "/moved").c_str()) == 0, "root rename failed");
+ fixture.dir("root"); fixture.file("root/replacement", 1000000);
+ };
+ stream_scan::handle(writer.get(), path);
+ checkpoint = {};
+ require(fired && g_scan_root.fd.get() < 0, "changed root enabled deletion");
+ } else {
+ safe_delete::Root root;
+ require(root.open(path), "root open failed");
+ FileNode node; node.name = "root"; node.path = path; node.is_dir = true;
+ node.device = root.identity.st_dev; node.inode = root.identity.st_ino;
+ ScanOutput output(writer.get());
+ require(output.start(path), "stream start failed");
+ uint64_t id = 0; require(output.entry(node, 0, "directory", true, id), "root entry failed");
+ stream_scan::Pool pool(root, output, node, 256);
+ ScanStats stats; const int workers = pool.run(stats, 4);
+ require(!output.finish(stats, 0, workers), "staging budget ignored");
+ }
+ ::shutdown(writer.get(), SHUT_WR); drain.join();
+ require(wire.find("\"type\":\"error\"") != std::string::npos, "missing stream failure");
+ require(wire.find("\"type\":\"done\"") == std::string::npos, "failed stream reported success");
+}
int main(int argc, char** argv) {
require(argc == 2, "test case required");
const std::string test = argv[1];
@@ -204,5 +313,11 @@ int main(int argc, char** argv) {
else if (test == "depth") depth();
else if (test == "symlink" || test == "inode" || test == "opened") replacement(test);
else if (test == "resources") resources();
+ else if (test == "stream_equivalence") equivalence(true);
+ else if (test == "stream_resources") resources(true);
+ else if (test == "stream_symlink" || test == "stream_inode" || test == "stream_opened") replacement(test.substr(7), true);
+ else if (test == "stream_cancel") stream_cancel();
+ else if (test == "stream_budget") stream_limits_and_root_replacement(false);
+ else if (test == "stream_root") stream_limits_and_root_replacement(true);
else require(false, "unknown test case");
}
diff --git a/tests/test_parallel_scan.py b/tests/test_parallel_scan.py
index 6a9a472..9439f14 100644
--- a/tests/test_parallel_scan.py
+++ b/tests/test_parallel_scan.py
@@ -35,6 +35,14 @@ class ParallelScanTests(unittest.TestCase):
def test_queued_directory_inode_replacement_is_reported(self): self.run_case("inode")
def test_opened_directory_cannot_redirect_to_symlink_target(self): self.run_case("opened")
def test_low_descriptor_limit_cleanup_and_worker_creation_failure(self): self.run_case("resources")
+ def test_stream_all_worker_counts_match_serial_statistics(self): self.run_case("stream_equivalence")
+ def test_stream_low_descriptor_limit_and_worker_creation_failure(self): self.run_case("stream_resources")
+ def test_stream_queued_symlink_replacement_is_not_followed(self): self.run_case("stream_symlink")
+ def test_stream_queued_inode_replacement_is_reported(self): self.run_case("stream_inode")
+ def test_stream_opened_directory_cannot_redirect(self): self.run_case("stream_opened")
+ def test_results_precede_completion_and_cancel_never_enables_deletion(self): self.run_case("stream_cancel")
+ def test_stream_staging_budget_fails_without_success(self): self.run_case("stream_budget")
+ def test_stream_root_replacement_fails_without_success(self): self.run_case("stream_root")
class ParallelProtocolTests(DaemonHarness):
diff --git a/tests/test_root_scan.py b/tests/test_root_scan.py
index b24330d..1b0b214 100644
--- a/tests/test_root_scan.py
+++ b/tests/test_root_scan.py
@@ -16,6 +16,7 @@ import sys
import tempfile
import time
import unittest
+import test_stream_scan
@unittest.skipUnless(sys.platform.startswith("linux") and os.geteuid() == 0,
@@ -91,6 +92,26 @@ class RootScanSandboxTests(unittest.TestCase):
self.process.wait()
self.process.stderr.close()
+ connect_scan = test_stream_scan.StreamScanTests.connect_scan
+ collect = test_stream_scan.StreamScanTests.collect
+
+ def test_streamed_root_aliases_preserve_exclusions_deduplication_and_read_only(self):
+ (self.root / "alias").symlink_to("/", target_is_directory=True)
+ os.link(self.root / "data" / "private", self.root / "data" / "hard-link")
+ for path in ["/alias/.", "/./", "/"]:
+ done, entries, _ = self.collect(path)
+ self.assertEqual(done["type"], "done")
+ self.assertEqual(entries[0]["path"], "/")
+ self.assertEqual(done["scan_threads"], 1)
+ self.assertEqual(done["total_files"], 2)
+ self.assertEqual(done["total_size"], len(b"private app data") + len(b"system files"))
+ self.assertEqual(done["skipped"], 8)
+ self.assertTrue(all(not entry["path"].startswith("//") for entry in entries.values()))
+ self.assertFalse(any(entry["name"] in {"proc", "mnt", "storage", "dev", "sys", "data_mirror", "apex"} for entry in entries.values()))
+ result = self.request("DELETE /data/private")
+ self.assertEqual(result["status"], "error")
+ self.assertIn("read-only", result["message"])
+
def test_whole_internal_scan_excludes_aliases_and_uses_single_slash_paths(self):
status = self.request("PING")
self.assertEqual(status["uid"], 0)
diff --git a/tests/test_stream_scan.py b/tests/test_stream_scan.py
new file mode 100644
index 0000000..90fc4eb
--- /dev/null
+++ b/tests/test_stream_scan.py
@@ -0,0 +1,166 @@
+"""Stream contract and end-to-end daemon tests on disposable host fixtures."""
+import json
+import os
+import socket
+import struct
+from test_daemon import DaemonHarness
+
+MAX_FRAME = 128 * 1024
+
+def exact(client, size):
+ data = bytearray()
+ while len(data) < size:
+ piece = client.recv(size - len(data))
+ if not piece:
+ raise AssertionError('Truncated stream')
+ data.extend(piece)
+ return bytes(data)
+
+def frame(client):
+ size, = struct.unpack('!I', exact(client, 4))
+ if not 0 < size <= MAX_FRAME:
+ raise AssertionError('Unbounded frame')
+ value = json.loads(exact(client, size))
+ return dict(type=value["type"], **value["data"]), size + 4
+
+class StreamScanTests(DaemonHarness):
+ def connect_scan(self, root=None):
+ client = socket.create_connection(('127.0.0.1', self.port), timeout=3)
+ client.sendall(f'AUTH {self.token}\nSCAN_STREAM {root or self.root}\n'.encode())
+ return client
+
+ def collect(self, root=None):
+ with self.connect_scan(root) as client:
+ started, byte_count = frame(client)
+ if started['type'] == 'error':
+ return started, {}, []
+ self.assertEqual(started['type'], 'started')
+ self.assertEqual(started['stream_version'], 1)
+ entries, batches = {}, []
+ while True:
+ item, count = frame(client)
+ if item['type'] == 'error':
+ return item, entries, batches
+ if item['type'] == 'done':
+ self.assertEqual(item['bytes_sent'], byte_count)
+ self.assertEqual(client.recv(1), b'')
+ break
+ self.assertEqual(item['type'], 'entries')
+ self.assertTrue(0 < len(item['entries']) <= 128)
+ batches.append(item['entries'])
+ for entry in item['entries']:
+ self.assertEqual(entry['id'], len(entries))
+ parent = entry['parent']
+ if parent is None:
+ self.assertEqual(entry['id'], 0)
+ path = started['root']
+ else:
+ self.assertIn(parent, entries)
+ self.assertEqual(entries[parent]['kind'], 'directory')
+ path = entries[parent]['path'].rstrip('/') + '/' + entry['name']
+ entries[entry['id']] = dict(entry, path=path)
+ byte_count += count
+ self.assertEqual(item['total_files'], sum(e['counted'] and e['kind'] == 'file' for e in entries.values()))
+ self.assertEqual(item['total_dirs'], sum(e['counted'] and e['kind'] == 'directory' for e in entries.values()))
+ self.assertEqual(item['total_size'], sum(e['size'] for e in entries.values()))
+ return item, entries, batches
+
+ def test_stream_requires_authentication_before_any_frames(self):
+ for prefix in ["", f"AUTH {'0' * 64}\n"]:
+ result = self.raw_request(f"{prefix}SCAN_STREAM {self.root}\n".encode())
+ self.assertEqual(result["status"], "error")
+ self.assertIn("Authentication", result["message"])
+ self.assertEqual(self.request("PING")["status"], "ok")
+
+ def test_stream_matches_legacy_tree_and_keeps_frames_bounded(self):
+ for d in range(80):
+ directory = self.root / f'album {d}'
+ directory.mkdir()
+ (directory / 'empty').mkdir()
+ for f in range(12):
+ (directory / f'file {f}').write_bytes(b'x' * (d + f))
+ for name in [' leading trailing ', 'line\nquote"', '.hidden', '写真']:
+ (self.root / name).write_bytes(b'1234567')
+ os.link(self.root / '.hidden', self.root / 'hard-link')
+ (self.root / 'symlink').symlink_to(self.root / '.hidden')
+ os.mkfifo(self.root / 'fifo')
+ legacy = self.scan()
+ done, entries, batches = self.collect()
+ for key in ['total_files', 'total_dirs', 'total_size', 'errors', 'skipped', 'scan_threads']:
+ self.assertEqual(done[key], legacy[key], key)
+ expected = {}
+ def flatten(node):
+ expected[node['path']] = (node['type'], node['size'])
+ for child in node.get('children', []):
+ flatten(child)
+ flatten(legacy['tree'])
+ actual = {}
+ for entry in reversed(list(entries.values())):
+ kind = 'directory' if entry['kind'] == 'directory' else 'file'
+ size = entry['size'] + sum(s for p, (_, s) in actual.items() if p.rsplit('/', 1)[0] == entry['path'])
+ actual[entry['path']] = (kind, size)
+ self.assertEqual(actual, expected)
+ self.assertGreater(len(batches), 5)
+
+ def test_root_and_first_entry_arrive_before_scan_completion(self):
+ for i in range(5000):
+ (self.root / str(i)).write_bytes(b'123')
+ with self.connect_scan() as client:
+ start, _ = frame(client)
+ root, _ = frame(client)
+ entry, _ = frame(client)
+ self.assertEqual(start['type'], 'started')
+ self.assertEqual(root['entries'][0]['id'], 0)
+ self.assertEqual(entry['type'], 'entries')
+ self.assertEqual(entry['entries'][0]['id'], 1)
+ self.assertEqual(entry['entries'][0]['size'], 3)
+ # Closing while consuming partial results cancels traversal and leaves
+ # neither a successful scan root nor a stuck daemon.
+ result = self.request(f'DELETE {self.root / "0"}')
+ self.assertEqual(result['status'], 'error')
+ self.assertTrue((self.root / '0').exists())
+ self.assertEqual(self.request('PING')['status'], 'ok')
+
+ def test_failed_stream_clears_previous_delete_root(self):
+ (self.root / 'keep').write_text('keep')
+ self.scan()
+ result, _, _ = self.collect(self.root / 'missing')
+ self.assertEqual(result['type'], 'error')
+ self.assertEqual(self.request(f'DELETE {self.root / "keep"}')['status'], 'error')
+
+ def test_success_retains_secure_deletion_or_root_read_only(self):
+ (self.root / 'target').write_bytes(b'123')
+ done, _, _ = self.collect()
+ self.assertEqual(done['type'], 'done')
+ result = self.request(f'DELETE {self.root / "target"}')
+ self.assertEqual(result['status'], 'error' if self.read_only or os.geteuid() == 0 else 'ok')
+ self.assertEqual(self.request(f'DELETE {self.root}')['status'], 'error')
+
+ def test_stream_rejects_relative_root(self):
+ result, _, _ = self.collect('relative-root')
+ self.assertEqual(result['type'], 'error')
+
+ def test_depth_limit_preserves_counts_and_reports_error(self):
+ directory = self.root
+ for level in range(67):
+ (directory / 'file').write_bytes(b'x')
+ directory = directory / 'next'
+ directory.mkdir()
+ legacy = self.scan()
+ done, _, _ = self.collect()
+ for key in ['total_files', 'total_dirs', 'total_size', 'errors', 'skipped']:
+ self.assertEqual(done[key], legacy[key], key)
+ self.assertEqual(done['errors'], 1)
+
+ def test_extra_command_bytes_abort_the_stream(self):
+ with socket.create_connection(('127.0.0.1', self.port), timeout=3) as client:
+ client.sendall(f'AUTH {self.token}\nSCAN_STREAM {self.root}\nSHUTDOWN\n'.encode())
+ try:
+ self.assertEqual(client.recv(1), b'')
+ except ConnectionResetError:
+ pass # unread extra command bytes may cause TCP RST
+ self.assertEqual(self.request('PING')['status'], 'ok')
+
+class ReadOnlyStreamScanTests(StreamScanTests):
+ read_only = True
+ scan_threads = 8