fix(project-tree): apply one fs change with a single model build (#5241)

Each folder reloaded for an fs event copied the listings map and notified the store, so the mounted view rebuilt the whole tree model once per folder, and the reads were unbounded. One event now reads its folders at most eight at a time and applies all listings in one store update; a folder dropped while the batch was reading stays dropped.

Co-authored-by: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com>
This commit is contained in:
Mr0Bread
2026-11-23 13:36:18 +08:00
committed by GitHub
parent 4b55039e6e
commit 2395c9544b
2 changed files with 298 additions and 7 deletions
@@ -0,0 +1,234 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { FileEntry } from "@/bindings";
import { setProjectFsForTests, type ProjectFs } from "./fs";
import { applyFsChange, initProjectTree, loadDir, selectModel, setSelection, useProjectTree } from "./store";
const ROOT = "/p";
const FILES = 3;
const FANOUT = 4;
const dirPath = (k: number) => `${ROOT}/${k}`;
const filePath = (k: number) => `${dirPath(k)}/f.txt`;
/** A tree of `count` folders (heap-numbered, `FANOUT` per folder) below the root; `f.txt` of each folder has a version. */
class TreeFs {
readonly versions = new Map<number, number>();
readonly removed = new Set<number>();
readonly failing = new Set<string>();
readonly gates = new Map<string, Promise<void>>();
readonly reads: string[] = [];
running = 0;
peak = 0;
constructor(readonly count: number) {}
list(path: string): FileEntry[] {
const entry = (p: string, kind: FileEntry["kind"], mtimeMs: number): FileEntry => ({
name: p.slice(p.lastIndexOf("/") + 1),
path: p,
kind,
size: 1,
mtimeMs,
ignored: false,
excluded: false,
hidden: false,
});
if (path === ROOT) return [entry(dirPath(0), "dir", 0)];
const k = Number(path.slice(ROOT.length + 1));
const out: FileEntry[] = [];
for (let c = FANOUT * k + 1; c <= FANOUT * k + FANOUT && c < this.count; c++)
if (!this.removed.has(c)) out.push(entry(dirPath(c), "dir", 0));
out.push(filePath(k).length ? entry(filePath(k), "file", this.versions.get(k) ?? 0) : out[0]!);
for (let i = 1; i < FILES; i++) out.push(entry(`${dirPath(k)}/g${i}.txt`, "file", 0));
return out;
}
async readDir(path: string): Promise<FileEntry[]> {
this.reads.push(path);
this.running++;
this.peak = Math.max(this.peak, this.running);
const snapshot = this.list(path);
try {
await (this.gates.get(path) ?? new Promise<void>((r) => setTimeout(r, 0)));
if (this.failing.has(path)) throw new Error("EIO");
return snapshot;
} finally {
this.running--;
}
}
asProjectFs = () => ({ readDir: (p: string) => this.readDir(p) }) as ProjectFs;
}
/** Starts a project with every folder loaded, as after the user expanded the whole tree. */
function loadedTree(fs: TreeFs) {
setProjectFsForTests(fs.asProjectFs(), ROOT);
initProjectTree(ROOT, "proj");
const listings = new Map<string, readonly FileEntry[]>([[ROOT, fs.list(ROOT)]]);
for (let k = 0; k < fs.count; k++) listings.set(dirPath(k), fs.list(dirPath(k)));
useProjectTree.setState({ listings });
fs.reads.length = 0;
fs.peak = 0;
}
const modify = (fs: TreeFs, ks: number[]) => {
for (const k of ks) fs.versions.set(k, (fs.versions.get(k) ?? 0) + 1);
return { created: [], modified: ks.map(filePath), removed: [] };
};
/** What a mounted ProjectView does: select the model on every store notification. */
function watchModels() {
let last = selectModel(useProjectTree.getState());
let builds = 0;
const unsubscribe = useProjectTree.subscribe((s) => {
const model = selectModel(s);
if (model !== last) {
last = model;
builds++;
}
});
return { builds: () => builds, unsubscribe };
}
const range = (n: number) => Array.from({ length: n }, (_, i) => i);
const listingsOf = () => useProjectTree.getState().listings;
beforeEach(() => localStorage.clear());
afterEach(() => {
setProjectFsForTests(null);
initProjectTree(null);
});
describe("applyFsChange reload of many folders", () => {
it("builds the model once and caps the concurrent reads, however many folders changed", async () => {
const fs = new TreeFs(300);
loadedTree(fs);
const view = watchModels();
await applyFsChange(modify(fs, range(300)));
view.unsubscribe();
expect(fs.reads).toHaveLength(300);
expect(view.builds()).toBeLessThanOrEqual(2);
expect(fs.peak).toBeGreaterThan(1);
expect(fs.peak).toBeLessThanOrEqual(16);
expect(
listingsOf()
.get(dirPath(299))
?.find((e) => e.name === "f.txt")?.mtimeMs,
).toBe(1);
});
it("leaves folders without changes untouched and does not notify when nothing differs", async () => {
const fs = new TreeFs(20);
loadedTree(fs);
const before = listingsOf();
const view = watchModels();
let notified = 0;
const unsubscribe = useProjectTree.subscribe(() => notified++);
await applyFsChange({ created: [], modified: [filePath(3), filePath(4)], removed: [] });
expect(listingsOf()).toBe(before);
expect(notified).toBe(0);
await applyFsChange(modify(fs, [3]));
unsubscribe();
view.unsubscribe();
expect(listingsOf().get(dirPath(3))).not.toBe(before.get(dirPath(3)));
for (const k of [0, 1, 2, 4, 5]) expect(listingsOf().get(dirPath(k))).toBe(before.get(dirPath(k)));
});
it("keeps the old listing of a folder whose read fails", async () => {
const fs = new TreeFs(10);
loadedTree(fs);
const before = listingsOf();
fs.failing.add(dirPath(2));
await applyFsChange(modify(fs, [1, 2, 3]));
expect(listingsOf().get(dirPath(2))).toBe(before.get(dirPath(2)));
expect(
listingsOf()
.get(dirPath(1))
?.find((e) => e.name === "f.txt")?.mtimeMs,
).toBe(1);
expect(
listingsOf()
.get(dirPath(3))
?.find((e) => e.name === "f.txt")?.mtimeMs,
).toBe(1);
});
it("drops a folder that vanished while the batch was reading and does not bring it back", async () => {
const fs = new TreeFs(10);
loadedTree(fs);
const first = applyFsChange(modify(fs, [1, 2, 3]));
fs.removed.add(3);
await applyFsChange({ created: [], modified: [], removed: [dirPath(3)] });
await first;
expect(listingsOf().has(dirPath(3))).toBe(false);
expect(listingsOf().has(dirPath(2))).toBe(true);
});
it("keeps a listing that a later event read while an earlier batch was still waiting for a slow folder", async () => {
const fs = new TreeFs(10);
loadedTree(fs);
let release!: () => void;
fs.gates.set(dirPath(9), new Promise<void>((r) => (release = r)));
const first = applyFsChange(modify(fs, [1, 9]));
await new Promise((r) => setTimeout(r, 5));
await applyFsChange(modify(fs, [1]));
release();
await first;
expect(
listingsOf()
.get(dirPath(1))
?.find((e) => e.name === "f.txt")?.mtimeMs,
).toBe(2);
expect(
listingsOf()
.get(dirPath(9))
?.find((e) => e.name === "f.txt")?.mtimeMs,
).toBe(1);
});
it("ends with the listings and selection that reloading each folder on its own gives", async () => {
const changed = [1, 2, 5, 7];
const run = async (reload: (fs: TreeFs) => Promise<void>) => {
const fs = new TreeFs(12);
loadedTree(fs);
useProjectTree.setState({ expanded: new Set([ROOT, dirPath(0), dirPath(1)]) });
setSelection(new Set([filePath(1), dirPath(2)]), filePath(1));
const before = listingsOf();
modify(fs, changed);
await reload(fs);
const s = useProjectTree.getState();
return { before, listings: s.listings, expanded: s.expanded, selected: s.selected, lead: s.lead };
};
const batched = await run((fs) =>
applyFsChange({ created: [], modified: changed.map(filePath), removed: [] }).then(() => void fs),
);
const single = await run(async () => {
for (const k of changed) await loadDir(dirPath(k), true);
});
expect(batched.listings).toEqual(single.listings);
expect(batched.expanded).toEqual(single.expanded);
expect([...batched.selected].sort()).toEqual([...single.selected].sort());
expect(batched.lead).toBe(single.lead);
for (const [path, listing] of batched.listings) {
for (const [i, e] of listing.entries()) {
const old = batched.before.get(path)?.find((o) => o.path === e.path);
if (old && old.mtimeMs === e.mtimeMs && old.kind === e.kind && batched.before.get(path)?.[i] === old)
expect(e).toBe(old);
}
}
expect([...batched.selected].sort()).toEqual([filePath(1), dirPath(2)]);
});
});
+64 -7
View File
@@ -327,6 +327,8 @@ export const currentModel = () => selectModel(get());
let generation = 0;
const inflight = new Map<string, Promise<void>>();
/** Listings read by a batch and not applied yet; `reload` marks folders that were loaded when read. */
const pending = new Map<string, { entries: readonly FileEntry[]; reload: boolean }>();
let persistTimer: ReturnType<typeof setTimeout> | undefined;
/** Resets the view for a newly opened project, restoring its expansion state. */
@@ -338,6 +340,7 @@ export function initProjectTree(
) {
generation++;
inflight.clear();
pending.clear();
outlineInflight.clear();
clearTimeout(persistTimer);
modeExpanded.clear();
@@ -509,25 +512,73 @@ function putListing(path: string, entries: readonly FileEntry[]) {
set({ listings: new Map(listings).set(path, merged) });
}
/** Folder reads a batch runs at once; a checkout can change thousands of folders. */
const READ_SLOTS = 8;
let readsRunning = 0;
const readQueue: (() => void)[] = [];
async function withReadSlot<T>(read: () => Promise<T>): Promise<T> {
if (readsRunning < READ_SLOTS) readsRunning++;
else await new Promise<void>((resolve) => readQueue.push(resolve));
try {
return await read();
} finally {
const next = readQueue.shift();
if (next) next();
else readsRunning--;
}
}
/** Applies the batched listings in one update, so the tree model is built once for all of them. */
function flushPending() {
const { listings } = get();
let next: Map<string, readonly FileEntry[]> | undefined;
for (const [path, { entries, reload }] of pending) {
// A folder dropped while the batch was reading stays dropped.
if (reload && !listings.has(path)) continue;
const merged = mergeListing(listings.get(path), entries);
if (merged !== listings.get(path)) (next ??= new Map(listings)).set(path, merged);
}
pending.clear();
if (next) set({ listings: next });
}
/** Loads (or reloads) one folder. Concurrent calls for the same folder share a request. */
export function loadDir(path: string, force = false): Promise<void> {
return load(path, force, false);
}
/**
* With `batched`, the listing waits in `pending` for `flushPending` and the read takes one of `READ_SLOTS`;
* a later read of the same folder replaces it, so a flush never applies a listing older than one already read.
*/
function load(path: string, force: boolean, batched: boolean): Promise<void> {
const { root, listings } = get();
if (!root || isGroupKey(path)) return Promise.resolve();
if (!force && listings.has(path)) return Promise.resolve();
const running = inflight.get(path);
if (running) return running;
const gen = generation;
const reload = listings.has(path);
const p = (async () => {
try {
const entries = await projectFs(root).readDir(path);
const read = () => projectFs(root).readDir(path);
const entries = await (batched ? withReadSlot(read) : read());
if (gen !== generation) return;
putListing(path, entries);
if (batched) pending.set(path, { entries, reload });
else {
pending.delete(path);
putListing(path, entries);
}
// Compact Middle Packages needs to look one level down a single-folder chain.
const s = get();
if (treeOptions(s).compact) {
const visible = visibleEntries(entries, treeOptions(s));
const only = visible.length === 1 ? visible[0]! : null;
if (only && isDirEntry(only) && !only.ignored && !s.listings.has(only.path)) void loadDir(only.path);
if (only && isDirEntry(only) && !only.ignored && !s.listings.has(only.path)) {
const next = load(only.path, false, batched);
if (batched) await next;
}
}
} catch (e) {
if (gen !== generation) return;
@@ -550,6 +601,12 @@ export function loadDir(path: string, force = false): Promise<void> {
return p;
}
/** Re-reads `paths` as one batch: bounded concurrent reads, one update of the listings. */
async function reloadDirs(paths: readonly string[]) {
await Promise.all(paths.map((p) => load(p, true, true)));
flushPending();
}
/** Applies a backend `fsChanged` event: reloads affected loaded folders only. */
export async function applyFsChange(event: {
created: string[];
@@ -583,7 +640,7 @@ export async function applyFsChange(event: {
});
}
}
await Promise.all(plan.reload.map((p) => loadDir(p, true)));
await reloadDirs(plan.reload);
// Member rows go stale when the file changes on disk: drop and refetch.
if (event.modified.length) dropOutlines(event.modified);
if (event.removed.length) {
@@ -602,7 +659,7 @@ export async function applyFsChange(event: {
/** Re-reads the folders among `dirs` the tree has loaded; the rest stay unread. */
export async function reloadLoadedDirs(dirs: readonly string[]) {
const { listings } = get();
await Promise.all(dirs.filter((p) => listings.has(p)).map((p) => loadDir(p, true)));
await reloadDirs(dirs.filter((p) => listings.has(p)));
}
/**
@@ -612,13 +669,13 @@ export async function reloadLoadedDirs(dirs: readonly string[]) {
export async function reloadArchiveDirs() {
const { listings } = get();
const inArchive = (p: string) => p.endsWith("!") || p.includes("!/") || p.includes("!\\");
await Promise.all([...listings.keys()].filter(inArchive).map((p) => loadDir(p, true)));
await reloadDirs([...listings.keys()].filter(inArchive));
}
/** Re-reads every loaded folder (View › Reload from Disk). */
export async function reloadAll() {
const { listings } = get();
await Promise.all([...listings.keys()].map((p) => loadDir(p, true)));
await reloadDirs([...listings.keys()]);
}
// ---------------------------------------------------------------------------