mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 02:05:31 +00:00
Keep Git watchers responsive during large directory scans (#10788)
* fix(server): avoid event-loop stalls and timeouts during Git watcher scans Compile file-observer and Git ignore root lists into ancestor-Set matchers so directory scans check direct children in O(1) instead of scanning all ignored roots per entry. Add cooperative time-sliced yielding and mid-directory abort/ignore checks to NativeRecursiveBackend and LinuxBackend directory scans, and enforce the monotonic watcher subscription deadline after Promise.race so late microtask resolutions cannot bypass timeouts. * fix(server): attach Linux directory watches before scanning entries Attach the inotify watcher for each newly discovered directory before calling readdir() in LinuxBackend.scan(), so writes that land during readdir() or mid-directory scan yields are captured live rather than missed between the snapshot and post-scan watch attachment. * fix(server): track Linux directory watch inode identity across replacements Store each Linux directory watcher with its (dev, ino) identity so watch attachment and scan reconciliation detect when a directory at a watched path is moved aside and replaced. Close stale watchers, rebind to the replacement inode, and re-verify identity after attach, readdir, and scan yields.
This commit is contained in:
@@ -31,6 +31,8 @@ export interface ObservationHost {
|
||||
metrics: ObserverMetrics;
|
||||
isActive(): boolean;
|
||||
isIgnored(path: string): boolean;
|
||||
/** O(1) exact ignored-root check for a child whose parent is already known non-ignored. */
|
||||
isIgnoredRoot(path: string): boolean;
|
||||
isPathInside(root: string, path: string): boolean;
|
||||
queueEvent(type: FileChangeType, path: string): void;
|
||||
fail(error: Error): void;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { renameSync, writeFileSync } from "node:fs";
|
||||
import { mkdir, mkdtemp, rename, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { join, sep } from "node:path";
|
||||
import { expect, test } from "vitest";
|
||||
import { createFileObserver } from "../index.js";
|
||||
import { createLinuxBackend } from "./linux.js";
|
||||
@@ -25,6 +26,7 @@ test("the linux backend fails the observation when the classification queue over
|
||||
metrics: observer.getDiagnostics(),
|
||||
isActive: () => active,
|
||||
isIgnored: () => false,
|
||||
isIgnoredRoot: () => false,
|
||||
isPathInside: paths.isInside,
|
||||
queueEvent: () => {},
|
||||
fail: (error) => {
|
||||
@@ -84,6 +86,7 @@ test("an ignore update drains classifications queued below the new excluded root
|
||||
metrics: observer.getDiagnostics(),
|
||||
isActive: () => active,
|
||||
isIgnored: (path) => ignoreGenerated && paths.isInside(ignored, path),
|
||||
isIgnoredRoot: (path) => ignoreGenerated && path === ignored,
|
||||
isPathInside: paths.isInside,
|
||||
queueEvent: (type, path) => {
|
||||
if (type === "create") delivered.push(path);
|
||||
@@ -120,3 +123,229 @@ test("an ignore update drains classifications queued below the new excluded root
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("scan yields to the event loop and aborts mid-directory when the observation closes", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "linux-scan-yield-"));
|
||||
const totalFiles = 700;
|
||||
await Promise.all(
|
||||
Array.from({ length: totalFiles }, (_, index) =>
|
||||
writeFile(join(root, `file-${index}.txt`), "x"),
|
||||
),
|
||||
);
|
||||
const paths = createObserverPaths(process.platform);
|
||||
const observer = createFileObserver();
|
||||
let active = true;
|
||||
let inspected = 0;
|
||||
let yieldedBeforeFinish = false;
|
||||
let scheduledYieldProbe = false;
|
||||
const backend = createLinuxBackend(
|
||||
{
|
||||
root,
|
||||
metrics: observer.getDiagnostics(),
|
||||
isActive: () => active,
|
||||
isIgnored: () => false,
|
||||
isIgnoredRoot: () => {
|
||||
inspected += 1;
|
||||
if (!scheduledYieldProbe && inspected === 260) {
|
||||
scheduledYieldProbe = true;
|
||||
const until = performance.now() + 15;
|
||||
while (performance.now() < until) {
|
||||
// busy wait
|
||||
}
|
||||
setImmediate(() => {
|
||||
if (inspected < totalFiles) {
|
||||
yieldedBeforeFinish = true;
|
||||
}
|
||||
active = false;
|
||||
});
|
||||
}
|
||||
return false;
|
||||
},
|
||||
isPathInside: paths.isInside,
|
||||
queueEvent: () => {},
|
||||
fail: (error) => {
|
||||
throw error;
|
||||
},
|
||||
},
|
||||
paths,
|
||||
() => ({ close: () => {}, on: () => {} }) as never,
|
||||
);
|
||||
try {
|
||||
await backend.start();
|
||||
expect(yieldedBeforeFinish).toBe(true);
|
||||
expect(inspected).toBeLessThan(totalFiles);
|
||||
} finally {
|
||||
active = false;
|
||||
await backend.close();
|
||||
await observer.close();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test.skipIf(process.platform !== "linux")(
|
||||
"a file written into a newly moved directory during a scan yield is not missed",
|
||||
async () => {
|
||||
const parent = await mkdtemp(join(tmpdir(), "linux-scan-watch-order-"));
|
||||
const root = join(parent, "root");
|
||||
const staged = join(parent, "staged");
|
||||
const moved = join(root, "moved");
|
||||
const lateFile = join(moved, "late.txt");
|
||||
await mkdir(root);
|
||||
await mkdir(staged);
|
||||
const totalFiles = 700;
|
||||
await Promise.all(
|
||||
Array.from({ length: totalFiles }, (_, index) =>
|
||||
writeFile(join(staged, `file-${index}.txt`), "x"),
|
||||
),
|
||||
);
|
||||
|
||||
const paths = createObserverPaths(process.platform);
|
||||
const observer = createFileObserver();
|
||||
let active = true;
|
||||
const delivered = new Set<string>();
|
||||
const movedPrefix = `${moved}${sep}`;
|
||||
let inspectedMoved = 0;
|
||||
let scheduledLateWrite = false;
|
||||
let wroteDuringYield = false;
|
||||
const backend = createLinuxBackend(
|
||||
{
|
||||
root,
|
||||
metrics: observer.getDiagnostics(),
|
||||
isActive: () => active,
|
||||
isIgnored: () => false,
|
||||
isIgnoredRoot: (path) => {
|
||||
if (path.startsWith(movedPrefix)) {
|
||||
inspectedMoved += 1;
|
||||
if (!scheduledLateWrite && inspectedMoved === 260) {
|
||||
scheduledLateWrite = true;
|
||||
const until = performance.now() + 15;
|
||||
while (performance.now() < until) {
|
||||
// Ensure the next stride boundary exceeds the 8 ms slice budget.
|
||||
}
|
||||
setImmediate(() => {
|
||||
if (inspectedMoved < totalFiles) {
|
||||
wroteDuringYield = true;
|
||||
}
|
||||
writeFileSync(lateFile, "after-readdir");
|
||||
});
|
||||
}
|
||||
}
|
||||
return false;
|
||||
},
|
||||
isPathInside: paths.isInside,
|
||||
queueEvent: (_type, path) => {
|
||||
delivered.add(path);
|
||||
},
|
||||
fail: (error) => {
|
||||
throw error;
|
||||
},
|
||||
},
|
||||
paths,
|
||||
);
|
||||
|
||||
try {
|
||||
await backend.start();
|
||||
await rename(staged, moved);
|
||||
await expect.poll(() => wroteDuringYield, { timeout: 5_000 }).toBe(true);
|
||||
await expect.poll(() => delivered.has(lateFile), { timeout: 2_000 }).toBe(true);
|
||||
} finally {
|
||||
active = false;
|
||||
await backend.close();
|
||||
await observer.close();
|
||||
await rm(parent, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test.skipIf(process.platform !== "linux")(
|
||||
"replacing a newly moved directory during its first scan rebinds coverage to the replacement",
|
||||
async () => {
|
||||
const parent = await mkdtemp(join(tmpdir(), "linux-scan-replace-dir-"));
|
||||
const root = join(parent, "root");
|
||||
const first = join(parent, "first");
|
||||
const second = join(parent, "second");
|
||||
const aside = join(parent, "aside");
|
||||
const target = join(root, "target");
|
||||
await mkdir(root);
|
||||
await mkdir(first);
|
||||
await mkdir(second);
|
||||
const totalFiles = 700;
|
||||
await Promise.all(
|
||||
Array.from({ length: totalFiles }, (_, index) =>
|
||||
writeFile(join(first, `file-${index}.txt`), "x"),
|
||||
),
|
||||
);
|
||||
await writeFile(join(second, "initial-replacement.txt"), "v1");
|
||||
|
||||
const paths = createObserverPaths(process.platform);
|
||||
const observer = createFileObserver();
|
||||
let active = true;
|
||||
const delivered = new Set<string>();
|
||||
const targetPrefix = `${target}${sep}`;
|
||||
let inspectedTarget = 0;
|
||||
let scheduledSwap = false;
|
||||
let swappedDuringYield = false;
|
||||
const backend = createLinuxBackend(
|
||||
{
|
||||
root,
|
||||
metrics: observer.getDiagnostics(),
|
||||
isActive: () => active,
|
||||
isIgnored: () => false,
|
||||
isIgnoredRoot: (path) => {
|
||||
if (path.startsWith(targetPrefix)) {
|
||||
inspectedTarget += 1;
|
||||
if (!scheduledSwap && inspectedTarget === 260) {
|
||||
scheduledSwap = true;
|
||||
const until = performance.now() + 15;
|
||||
while (performance.now() < until) {
|
||||
// Ensure the next stride boundary exceeds the 8 ms slice budget.
|
||||
}
|
||||
setImmediate(() => {
|
||||
if (inspectedTarget < totalFiles) {
|
||||
swappedDuringYield = true;
|
||||
}
|
||||
renameSync(target, aside);
|
||||
renameSync(second, target);
|
||||
});
|
||||
}
|
||||
}
|
||||
return false;
|
||||
},
|
||||
isPathInside: paths.isInside,
|
||||
queueEvent: (_type, path) => {
|
||||
delivered.add(path);
|
||||
},
|
||||
fail: (error) => {
|
||||
throw error;
|
||||
},
|
||||
},
|
||||
paths,
|
||||
);
|
||||
|
||||
try {
|
||||
await backend.start();
|
||||
await rename(first, target);
|
||||
await expect.poll(() => swappedDuringYield, { timeout: 5_000 }).toBe(true);
|
||||
await expect
|
||||
.poll(() => backend.getDiagnostics().pendingReconciliationWorkCount, { timeout: 5_000 })
|
||||
.toBe(0);
|
||||
await expect
|
||||
.poll(() => delivered.has(join(target, "initial-replacement.txt")), { timeout: 2_000 })
|
||||
.toBe(true);
|
||||
|
||||
const movedAwayEdit = join(aside, "from-moved-away.txt");
|
||||
const leakedMovedAwayPath = join(target, "from-moved-away.txt");
|
||||
const replacementEdit = join(target, "from-replacement.txt");
|
||||
await writeFile(movedAwayEdit, "old-inode");
|
||||
await writeFile(replacementEdit, "new-inode");
|
||||
|
||||
await expect.poll(() => delivered.has(replacementEdit), { timeout: 2_000 }).toBe(true);
|
||||
expect(delivered.has(leakedMovedAwayPath)).toBe(false);
|
||||
} finally {
|
||||
active = false;
|
||||
await backend.close();
|
||||
await observer.close();
|
||||
await rm(parent, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -4,6 +4,7 @@ import { resolve } from "node:path";
|
||||
import type { BackendDiagnostics, ObservationBackend, ObservationHost } from "./contracts.js";
|
||||
import type { ObserverPaths } from "./paths.js";
|
||||
import { isMissingPathError, toError } from "./paths.js";
|
||||
import { createScanSliceBudget, type ScanSliceBudget } from "./scan-slice.js";
|
||||
|
||||
const MAX_WATCHED_DIRECTORIES = 5_000;
|
||||
const RECONCILIATION_DELAY_MS = 50;
|
||||
@@ -22,17 +23,35 @@ const RECONCILIATION_DELAY_MS = 50;
|
||||
// pathology, not an ordinary large burst.
|
||||
const MAX_CONCURRENT_CLASSIFICATIONS = 32;
|
||||
const MAX_QUEUED_CLASSIFICATIONS = 16_384;
|
||||
const MAX_WATCH_ATTACH_ATTEMPTS = 3;
|
||||
const MAX_DIRECTORY_RESCANS = 3;
|
||||
|
||||
// "baseline" establishes coverage of what already exists when the subscription
|
||||
// starts, so it reports nothing. "changes" scans topology that appeared while
|
||||
// observed, so files found before their directory was covered are creates.
|
||||
type ReconcileMode = "baseline" | "changes";
|
||||
|
||||
interface DirectoryIdentity {
|
||||
dev: bigint;
|
||||
ino: bigint;
|
||||
}
|
||||
|
||||
interface WatchedDirectory {
|
||||
watcher: FSWatcher;
|
||||
identity: DirectoryIdentity;
|
||||
}
|
||||
|
||||
interface DirectorySnapshot {
|
||||
directories: Set<string>;
|
||||
filesDiscoveredBeforeCoverage: Set<string>;
|
||||
}
|
||||
|
||||
type DirectoryScanOutcome = "ok" | "aborted" | "ignored" | "replaced";
|
||||
|
||||
function sameDirectoryIdentity(left: DirectoryIdentity, right: DirectoryIdentity): boolean {
|
||||
return left.dev === right.dev && left.ino === right.ino;
|
||||
}
|
||||
|
||||
type WatchDirectory = (
|
||||
directory: string,
|
||||
listener: (eventType: string, filename: string | null) => void,
|
||||
@@ -49,7 +68,7 @@ export function createLinuxBackend(
|
||||
}
|
||||
|
||||
class LinuxBackend implements ObservationBackend {
|
||||
private readonly watchers = new Map<string, FSWatcher>();
|
||||
private readonly watchers = new Map<string, WatchedDirectory>();
|
||||
private readonly classifications = new Set<Promise<void>>();
|
||||
private readonly classificationQueue: Array<{ path: string }> = [];
|
||||
private readonly pendingScopes = new Set<string>();
|
||||
@@ -66,16 +85,18 @@ class LinuxBackend implements ObservationBackend {
|
||||
) {}
|
||||
|
||||
async start(): Promise<void> {
|
||||
this.watchDirectory(this.host.root);
|
||||
const rootIdentity = await this.statDirectoryIdentity(this.host.root);
|
||||
if (!rootIdentity || !this.host.isActive()) return;
|
||||
this.watchDirectory(this.host.root, rootIdentity);
|
||||
await this.enqueue([this.host.root], "baseline");
|
||||
}
|
||||
|
||||
async updateIgnore(): Promise<void> {
|
||||
this.discardIgnoredClassifications();
|
||||
const inFlight = [...this.classifications];
|
||||
for (const [directory, watcher] of this.watchers) {
|
||||
for (const [directory, entry] of this.watchers) {
|
||||
if (directory !== this.host.root && this.host.isIgnored(directory)) {
|
||||
watcher.close();
|
||||
entry.watcher.close();
|
||||
this.watchers.delete(directory);
|
||||
}
|
||||
}
|
||||
@@ -87,7 +108,7 @@ class LinuxBackend implements ObservationBackend {
|
||||
close(): Promise<void> {
|
||||
if (this.closePromise) return this.closePromise;
|
||||
this.cancelQueued();
|
||||
for (const watcher of this.watchers.values()) watcher.close();
|
||||
for (const entry of this.watchers.values()) entry.watcher.close();
|
||||
this.watchers.clear();
|
||||
this.closePromise = this.finishClose();
|
||||
return this.closePromise;
|
||||
@@ -112,11 +133,18 @@ class LinuxBackend implements ObservationBackend {
|
||||
await this.reconcileTail;
|
||||
this.classificationQueue.length = 0;
|
||||
await Promise.allSettled(this.classifications);
|
||||
for (const watcher of this.watchers.values()) watcher.close();
|
||||
for (const entry of this.watchers.values()) entry.watcher.close();
|
||||
this.watchers.clear();
|
||||
}
|
||||
|
||||
private watchDirectory(directory: string): void {
|
||||
private closeWatcher(directory: string): void {
|
||||
const existing = this.watchers.get(directory);
|
||||
if (!existing) return;
|
||||
existing.watcher.close();
|
||||
this.watchers.delete(directory);
|
||||
}
|
||||
|
||||
private watchDirectory(directory: string, identity: DirectoryIdentity): void {
|
||||
if (!this.host.isActive() || this.watchers.has(directory) || this.host.isIgnored(directory)) {
|
||||
return;
|
||||
}
|
||||
@@ -135,15 +163,15 @@ class LinuxBackend implements ObservationBackend {
|
||||
}
|
||||
if (eventType === "rename" || !filename) this.requestReconcile(path);
|
||||
});
|
||||
this.attachWatcher(directory, watcher);
|
||||
this.attachWatcher(directory, watcher, identity);
|
||||
}
|
||||
|
||||
private attachWatcher(directory: string, watcher: FSWatcher): void {
|
||||
private attachWatcher(directory: string, watcher: FSWatcher, identity: DirectoryIdentity): void {
|
||||
watcher.on("error", (error) => {
|
||||
if (!this.host.isActive()) return;
|
||||
if (this.paths.isExpectedWatchDisappearance(error)) {
|
||||
watcher.close();
|
||||
if (this.watchers.get(directory) === watcher) this.watchers.delete(directory);
|
||||
if (this.watchers.get(directory)?.watcher === watcher) this.watchers.delete(directory);
|
||||
if (directory === this.host.root) {
|
||||
this.host.fail(toError(error));
|
||||
return;
|
||||
@@ -153,7 +181,7 @@ class LinuxBackend implements ObservationBackend {
|
||||
}
|
||||
this.host.fail(toError(error));
|
||||
});
|
||||
this.watchers.set(directory, watcher);
|
||||
this.watchers.set(directory, { watcher, identity });
|
||||
}
|
||||
|
||||
private requestReconcile(scope: string): void {
|
||||
@@ -206,32 +234,29 @@ class LinuxBackend implements ObservationBackend {
|
||||
|
||||
private async reconcile(scopes: string[], mode: ReconcileMode): Promise<void> {
|
||||
for (const scope of scopes) {
|
||||
const snapshot = await this.scan(scope);
|
||||
const snapshot = await this.scan(scope, mode);
|
||||
if (!this.host.isActive()) return;
|
||||
for (const directory of snapshot.directories) {
|
||||
if (!this.watchSnapshotDirectory(directory)) snapshot.directories.delete(directory);
|
||||
}
|
||||
if (mode === "changes") {
|
||||
for (const path of snapshot.filesDiscoveredBeforeCoverage) {
|
||||
this.host.queueEvent("create", path);
|
||||
}
|
||||
}
|
||||
for (const [directory, watcher] of this.watchers) {
|
||||
for (const [directory, entry] of this.watchers) {
|
||||
const disappeared =
|
||||
directory !== this.host.root &&
|
||||
this.host.isPathInside(scope, directory) &&
|
||||
!snapshot.directories.has(directory);
|
||||
if (!disappeared) continue;
|
||||
watcher.close();
|
||||
entry.watcher.close();
|
||||
this.watchers.delete(directory);
|
||||
this.host.queueEvent("delete", directory);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private watchSnapshotDirectory(directory: string): boolean {
|
||||
private watchSnapshotDirectory(directory: string, identity: DirectoryIdentity): boolean {
|
||||
try {
|
||||
this.watchDirectory(directory);
|
||||
this.watchDirectory(directory, identity);
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (!this.paths.isExpectedWatchDisappearance(error) || directory === this.host.root) {
|
||||
@@ -241,51 +266,206 @@ class LinuxBackend implements ObservationBackend {
|
||||
}
|
||||
}
|
||||
|
||||
private async scan(scope: string): Promise<DirectorySnapshot> {
|
||||
let scopeStats;
|
||||
private async statDirectoryIdentity(directory: string): Promise<DirectoryIdentity | null> {
|
||||
try {
|
||||
scopeStats = await stat(scope);
|
||||
const stats = await stat(directory, { bigint: true });
|
||||
if (!stats.isDirectory()) return null;
|
||||
return { dev: stats.dev, ino: stats.ino };
|
||||
} catch (error) {
|
||||
if (!isMissingPathError(error) || scope === this.host.root) throw error;
|
||||
return { directories: new Set(), filesDiscoveredBeforeCoverage: new Set() };
|
||||
if (!isMissingPathError(error)) throw error;
|
||||
if (directory === this.host.root && this.host.isActive()) throw error;
|
||||
return null;
|
||||
}
|
||||
if (!scopeStats.isDirectory()) {
|
||||
}
|
||||
|
||||
// Linux inotify watches are pinned to a directory inode, not its path. Verify
|
||||
// that the live path still resolves to the watched (dev, ino) before reusing
|
||||
// a watcher, and verify after attaching a new watch so concurrent swaps are
|
||||
// never left watching a moved-away directory.
|
||||
private async ensureDirectoryWatch(
|
||||
directory: string,
|
||||
): Promise<{ identity: DirectoryIdentity; discovered: boolean } | null> {
|
||||
for (let attempt = 0; attempt < MAX_WATCH_ATTACH_ATTEMPTS; attempt += 1) {
|
||||
if (!this.host.isActive() || this.host.isIgnored(directory)) return null;
|
||||
const before = await this.statDirectoryIdentity(directory);
|
||||
if (!before || !this.host.isActive() || this.host.isIgnored(directory)) return null;
|
||||
const existing = this.watchers.get(directory);
|
||||
if (existing && sameDirectoryIdentity(existing.identity, before)) {
|
||||
return { identity: before, discovered: false };
|
||||
}
|
||||
if (existing) this.closeWatcher(directory);
|
||||
if (!this.watchSnapshotDirectory(directory, before)) return null;
|
||||
const after = await this.statDirectoryIdentity(directory);
|
||||
if (!after || !this.host.isActive() || this.host.isIgnored(directory)) {
|
||||
this.closeWatcher(directory);
|
||||
return null;
|
||||
}
|
||||
if (sameDirectoryIdentity(before, after)) {
|
||||
return { identity: before, discovered: true };
|
||||
}
|
||||
this.closeWatcher(directory);
|
||||
}
|
||||
this.requestReconcile(directory);
|
||||
return null;
|
||||
}
|
||||
|
||||
private async readDirectoryForScan(directory: string): Promise<{
|
||||
entries: Dirent[];
|
||||
identity: DirectoryIdentity;
|
||||
discovered: boolean;
|
||||
} | null> {
|
||||
// Establish inotify coverage before taking the directory snapshot so files
|
||||
// written during readdir() or mid-directory scan yields are never missed.
|
||||
const watched = await this.ensureDirectoryWatch(directory);
|
||||
if (!watched) return null;
|
||||
try {
|
||||
const entries = await readdir(directory, { withFileTypes: true });
|
||||
return { entries, identity: watched.identity, discovered: watched.discovered };
|
||||
} catch (error) {
|
||||
if (!isMissingPathError(error)) throw error;
|
||||
if (directory === this.host.root && this.host.isActive()) throw error;
|
||||
if (watched.discovered) this.closeWatcher(directory);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private async isDirectoryIdentityCurrent(
|
||||
directory: string,
|
||||
identity: DirectoryIdentity,
|
||||
discovered: boolean,
|
||||
): Promise<boolean> {
|
||||
const current = await this.statDirectoryIdentity(directory);
|
||||
if (current && sameDirectoryIdentity(current, identity)) return true;
|
||||
this.closeWatcher(directory);
|
||||
if (!current && !discovered && directory !== this.host.root) {
|
||||
this.host.queueEvent("delete", directory);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private async scan(scope: string, mode: ReconcileMode): Promise<DirectorySnapshot> {
|
||||
const scopeIdentity = await this.statDirectoryIdentity(scope);
|
||||
if (!scopeIdentity || !this.host.isActive() || this.host.isIgnored(scope)) {
|
||||
return { directories: new Set(), filesDiscoveredBeforeCoverage: new Set() };
|
||||
}
|
||||
const directories = new Set<string>([scope]);
|
||||
const filesDiscoveredBeforeCoverage = new Set<string>();
|
||||
const pending = [scope];
|
||||
const rescanAttempts = new Map<string, number>();
|
||||
const slice = createScanSliceBudget();
|
||||
while (pending.length > 0 && this.host.isActive()) {
|
||||
const directory = pending.pop();
|
||||
if (!directory) continue;
|
||||
let entries: Dirent[];
|
||||
try {
|
||||
entries = await readdir(directory, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
if (!isMissingPathError(error)) throw error;
|
||||
if (directory === this.host.root && this.host.isActive()) throw error;
|
||||
if (this.host.isIgnored(directory)) {
|
||||
directories.delete(directory);
|
||||
continue;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
const child = resolve(directory, entry.name);
|
||||
if (this.host.isIgnored(child)) continue;
|
||||
if (!entry.isDirectory()) {
|
||||
if (!this.watchers.has(directory)) filesDiscoveredBeforeCoverage.add(child);
|
||||
continue;
|
||||
const scanned = await this.readDirectoryForScan(directory);
|
||||
if (!scanned) {
|
||||
directories.delete(directory);
|
||||
continue;
|
||||
}
|
||||
if (!this.host.isActive()) {
|
||||
return { directories, filesDiscoveredBeforeCoverage };
|
||||
}
|
||||
if (this.host.isIgnored(directory)) {
|
||||
directories.delete(directory);
|
||||
continue;
|
||||
}
|
||||
const outcome = await this.scanDirectoryEntries({
|
||||
directory,
|
||||
entries: scanned.entries,
|
||||
identity: scanned.identity,
|
||||
discovered: scanned.discovered,
|
||||
collectDiscoveredFiles: mode === "changes" && scanned.discovered,
|
||||
directories,
|
||||
filesDiscoveredBeforeCoverage,
|
||||
pending,
|
||||
slice,
|
||||
});
|
||||
if (outcome === "aborted") {
|
||||
return { directories, filesDiscoveredBeforeCoverage };
|
||||
}
|
||||
if (outcome === "replaced") {
|
||||
const retries = (rescanAttempts.get(directory) ?? 0) + 1;
|
||||
if (retries <= MAX_DIRECTORY_RESCANS) {
|
||||
rescanAttempts.set(directory, retries);
|
||||
pending.push(directory);
|
||||
} else {
|
||||
directories.delete(directory);
|
||||
this.requestReconcile(directory);
|
||||
}
|
||||
directories.add(child);
|
||||
if (directories.size > MAX_WATCHED_DIRECTORIES) {
|
||||
this.host.metrics.directoryLimitFailureCount += 1;
|
||||
throw new Error(
|
||||
`Recursive file observation exceeded ${MAX_WATCHED_DIRECTORIES} directories under ${this.host.root}`,
|
||||
);
|
||||
}
|
||||
pending.push(child);
|
||||
continue;
|
||||
}
|
||||
if (slice.isExpired()) {
|
||||
await slice.yield();
|
||||
}
|
||||
}
|
||||
return { directories, filesDiscoveredBeforeCoverage };
|
||||
}
|
||||
|
||||
private async scanDirectoryEntries(input: {
|
||||
directory: string;
|
||||
entries: Dirent[];
|
||||
identity: DirectoryIdentity;
|
||||
discovered: boolean;
|
||||
collectDiscoveredFiles: boolean;
|
||||
directories: Set<string>;
|
||||
filesDiscoveredBeforeCoverage: Set<string>;
|
||||
pending: string[];
|
||||
slice: ScanSliceBudget;
|
||||
}): Promise<DirectoryScanOutcome> {
|
||||
const {
|
||||
directory,
|
||||
entries,
|
||||
identity,
|
||||
discovered,
|
||||
collectDiscoveredFiles,
|
||||
directories,
|
||||
filesDiscoveredBeforeCoverage,
|
||||
pending,
|
||||
slice,
|
||||
} = input;
|
||||
const childDirectories: string[] = [];
|
||||
const childFiles: string[] = [];
|
||||
for (const entry of entries) {
|
||||
if (slice.shouldYield()) {
|
||||
await slice.yield();
|
||||
if (!this.host.isActive()) return "aborted";
|
||||
if (this.host.isIgnored(directory)) {
|
||||
directories.delete(directory);
|
||||
return "ignored";
|
||||
}
|
||||
if (!(await this.isDirectoryIdentityCurrent(directory, identity, discovered))) {
|
||||
return "replaced";
|
||||
}
|
||||
}
|
||||
const child = resolve(directory, entry.name);
|
||||
if (this.host.isIgnoredRoot(child)) continue;
|
||||
if (!entry.isDirectory()) {
|
||||
if (collectDiscoveredFiles) childFiles.push(child);
|
||||
continue;
|
||||
}
|
||||
if (directories.size + childDirectories.length + 1 > MAX_WATCHED_DIRECTORIES) {
|
||||
this.host.metrics.directoryLimitFailureCount += 1;
|
||||
throw new Error(
|
||||
`Recursive file observation exceeded ${MAX_WATCHED_DIRECTORIES} directories under ${this.host.root}`,
|
||||
);
|
||||
}
|
||||
childDirectories.push(child);
|
||||
}
|
||||
if (!(await this.isDirectoryIdentityCurrent(directory, identity, discovered))) {
|
||||
return "replaced";
|
||||
}
|
||||
if (!this.host.isActive()) return "aborted";
|
||||
for (const file of childFiles) filesDiscoveredBeforeCoverage.add(file);
|
||||
for (const child of childDirectories) {
|
||||
directories.add(child);
|
||||
pending.push(child);
|
||||
}
|
||||
return "ok";
|
||||
}
|
||||
|
||||
private classify(path: string): void {
|
||||
if (this.classificationQueue.length >= MAX_QUEUED_CLASSIFICATIONS) {
|
||||
// This backend has no file-level inventory and no full-tree safety
|
||||
|
||||
@@ -34,6 +34,7 @@ test.each(["existing", "new"])(
|
||||
metrics: observer.getDiagnostics(),
|
||||
isActive: () => active,
|
||||
isIgnored: () => false,
|
||||
isIgnoredRoot: () => false,
|
||||
isPathInside: paths.isInside,
|
||||
queueEvent: (type, path) => events.push({ type, path }),
|
||||
fail: (error) => {
|
||||
@@ -96,6 +97,7 @@ test("a file announced only as changed remains visible to coalesced deletion sca
|
||||
metrics: observer.getDiagnostics(),
|
||||
isActive: () => active,
|
||||
isIgnored: () => false,
|
||||
isIgnoredRoot: () => false,
|
||||
isPathInside: paths.isInside,
|
||||
queueEvent: (type, path) => events.push({ type, path }),
|
||||
fail: (error) => {
|
||||
@@ -150,6 +152,7 @@ test("a native ignore update drains classifications queued below the new exclude
|
||||
metrics: observer.getDiagnostics(),
|
||||
isActive: () => active,
|
||||
isIgnored: (path) => ignoreGenerated && paths.isInside(ignored, path),
|
||||
isIgnoredRoot: (path) => ignoreGenerated && path === ignored,
|
||||
isPathInside: paths.isInside,
|
||||
queueEvent: (type, path) => {
|
||||
if (type === "create") delivered.push(path);
|
||||
@@ -200,6 +203,7 @@ test("a rename burst does not spawn one stat per event", async () => {
|
||||
metrics: observer.getDiagnostics(),
|
||||
isActive: () => active,
|
||||
isIgnored: () => false,
|
||||
isIgnoredRoot: () => false,
|
||||
isPathInside: paths.isInside,
|
||||
queueEvent: () => {},
|
||||
fail: () => {},
|
||||
@@ -246,6 +250,7 @@ test("a classification shed onto the scoped audit still recovers the file", asyn
|
||||
metrics: observer.getDiagnostics(),
|
||||
isActive: () => active,
|
||||
isIgnored: () => false,
|
||||
isIgnoredRoot: () => false,
|
||||
isPathInside: paths.isInside,
|
||||
queueEvent: (type, path) => events.push({ type, path }),
|
||||
fail: (error) => {
|
||||
@@ -332,6 +337,7 @@ test.each([
|
||||
metrics: observer.getDiagnostics(),
|
||||
isActive: () => active,
|
||||
isIgnored: () => false,
|
||||
isIgnoredRoot: () => false,
|
||||
isPathInside: paths.isInside,
|
||||
queueEvent: (type, path) => events.push({ type, path }),
|
||||
fail: (error) => {
|
||||
@@ -417,6 +423,7 @@ test("a full native inventory audit reports a removed directory", async () => {
|
||||
metrics: observer.getDiagnostics(),
|
||||
isActive: () => true,
|
||||
isIgnored: () => false,
|
||||
isIgnoredRoot: () => false,
|
||||
isPathInside: paths.isInside,
|
||||
queueEvent: (type, path) => events.push({ type, path }),
|
||||
fail: (error) => {
|
||||
@@ -458,6 +465,7 @@ test("a file classified with no parent bucket yet still gets its delete emitted"
|
||||
metrics: observer.getDiagnostics(),
|
||||
isActive: () => active,
|
||||
isIgnored: () => false,
|
||||
isIgnoredRoot: () => false,
|
||||
isPathInside: paths.isInside,
|
||||
queueEvent: (type, path) => events.push({ type, path }),
|
||||
fail: (error) => {
|
||||
@@ -507,3 +515,156 @@ test("a file classified with no parent bucket yet still gets its delete emitted"
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("scanTree yields to the event loop and aborts mid-directory when the observation closes", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "native-scan-yield-"));
|
||||
const totalFiles = 700;
|
||||
await Promise.all(
|
||||
Array.from({ length: totalFiles }, (_, index) =>
|
||||
writeFile(join(root, `file-${index}.txt`), "x"),
|
||||
),
|
||||
);
|
||||
const paths = createObserverPaths(process.platform);
|
||||
const observer = createFileObserver();
|
||||
let active = true;
|
||||
let inspected = 0;
|
||||
let yieldedBeforeFinish = false;
|
||||
let scheduledYieldProbe = false;
|
||||
const backend = createNativeRecursiveBackend(
|
||||
{
|
||||
root,
|
||||
metrics: observer.getDiagnostics(),
|
||||
isActive: () => active,
|
||||
isIgnored: () => false,
|
||||
isIgnoredRoot: () => {
|
||||
inspected += 1;
|
||||
if (!scheduledYieldProbe && inspected === 260) {
|
||||
scheduledYieldProbe = true;
|
||||
// Push past the scan slice budget so the next stride boundary must yield.
|
||||
const until = performance.now() + 15;
|
||||
while (performance.now() < until) {
|
||||
// busy wait
|
||||
}
|
||||
setImmediate(() => {
|
||||
if (inspected < totalFiles) {
|
||||
yieldedBeforeFinish = true;
|
||||
}
|
||||
active = false;
|
||||
});
|
||||
}
|
||||
return false;
|
||||
},
|
||||
isPathInside: paths.isInside,
|
||||
queueEvent: () => {},
|
||||
fail: (error) => {
|
||||
throw error;
|
||||
},
|
||||
},
|
||||
paths,
|
||||
() => ({ close: () => {}, on: () => {} }),
|
||||
);
|
||||
try {
|
||||
await backend.start();
|
||||
expect(yieldedBeforeFinish).toBe(true);
|
||||
expect(inspected).toBeLessThan(totalFiles);
|
||||
expect(backend.getDiagnostics().nativeTrackedFileCount).toBe(0);
|
||||
} finally {
|
||||
active = false;
|
||||
await backend.close();
|
||||
await observer.close();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("readDirectory yields mid-directory and emits no deletes if the directory becomes ignored while yielded", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "native-readdir-yield-"));
|
||||
const sub = join(root, "sub");
|
||||
const childDir = join(sub, "child-dir");
|
||||
await mkdir(childDir, { recursive: true });
|
||||
const totalFiles = 700;
|
||||
await Promise.all(
|
||||
Array.from({ length: totalFiles }, (_, index) =>
|
||||
writeFile(join(sub, `file-${index}.txt`), "x"),
|
||||
),
|
||||
);
|
||||
const paths = createObserverPaths(process.platform);
|
||||
const notifications = new EventEmitter();
|
||||
const observer = createFileObserver();
|
||||
const metrics = observer.getDiagnostics();
|
||||
const events: FileChange[] = [];
|
||||
let active = true;
|
||||
let subIgnored = false;
|
||||
let armProbe = false;
|
||||
let inspected = 0;
|
||||
let yieldedBeforeFinish = false;
|
||||
let scheduledYieldProbe = false;
|
||||
const backend = createNativeRecursiveBackend(
|
||||
{
|
||||
root,
|
||||
metrics,
|
||||
isActive: () => active,
|
||||
isIgnored: (path) => subIgnored && paths.isInside(sub, path),
|
||||
isIgnoredRoot: (path) => {
|
||||
if (armProbe && path.startsWith(sub)) {
|
||||
inspected += 1;
|
||||
if (!scheduledYieldProbe && inspected === 260) {
|
||||
scheduledYieldProbe = true;
|
||||
const until = performance.now() + 15;
|
||||
while (performance.now() < until) {
|
||||
// busy wait
|
||||
}
|
||||
setImmediate(() => {
|
||||
if (inspected < totalFiles) {
|
||||
yieldedBeforeFinish = true;
|
||||
}
|
||||
subIgnored = true;
|
||||
});
|
||||
}
|
||||
}
|
||||
return subIgnored && path === sub;
|
||||
},
|
||||
isPathInside: paths.isInside,
|
||||
queueEvent: (type, path) => events.push({ type, path }),
|
||||
fail: (error) => {
|
||||
throw error;
|
||||
},
|
||||
},
|
||||
paths,
|
||||
(_root, listener) => {
|
||||
notifications.on("change", listener);
|
||||
return {
|
||||
close: () => notifications.removeAllListeners(),
|
||||
on: (event, onError) => notifications.on(event, onError),
|
||||
};
|
||||
},
|
||||
);
|
||||
try {
|
||||
await backend.start();
|
||||
events.length = 0;
|
||||
armProbe = true;
|
||||
// A rename on a known subdirectory queues a local shallow scan (`readDirectory`)
|
||||
// of its parent `sub` on the 500ms mandatory audit timer.
|
||||
notifications.emit("change", "rename", childDir);
|
||||
await expect
|
||||
.poll(
|
||||
() => {
|
||||
const diagnostics = backend.getDiagnostics();
|
||||
return (
|
||||
metrics.nativeShallowScanCount >= 1 &&
|
||||
diagnostics.pendingReconciliationWorkCount === 0 &&
|
||||
!diagnostics.reconciliationInFlight
|
||||
);
|
||||
},
|
||||
{ timeout: 10_000 },
|
||||
)
|
||||
.toBe(true);
|
||||
expect(yieldedBeforeFinish).toBe(true);
|
||||
expect(inspected).toBeLessThan(totalFiles);
|
||||
expect(events.filter((event) => event.type === "delete")).toEqual([]);
|
||||
} finally {
|
||||
active = false;
|
||||
await backend.close();
|
||||
await observer.close();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -4,6 +4,7 @@ import { dirname, join, resolve } from "node:path";
|
||||
import type { BackendDiagnostics, ObservationBackend, ObservationHost } from "./contracts.js";
|
||||
import type { ObserverPaths } from "./paths.js";
|
||||
import { isMissingPathError, toError } from "./paths.js";
|
||||
import { createScanSliceBudget, type ScanSliceBudget } from "./scan-slice.js";
|
||||
|
||||
const MAX_TRACKED_ENTRIES = 250_000;
|
||||
// fs.stat runs on the libuv threadpool, which is four threads and shared by the
|
||||
@@ -236,7 +237,7 @@ class NativeRecursiveBackend implements ObservationBackend {
|
||||
const startedAt = performance.now();
|
||||
try {
|
||||
if (fullAudit) {
|
||||
const next = await this.scanTree(this.host.root);
|
||||
const next = await this.scanTree(this.host.root, generation);
|
||||
if (!this.canCommit(generation)) return;
|
||||
if (emitDiff) {
|
||||
this.queueDiff(next.files, this.files);
|
||||
@@ -267,14 +268,16 @@ class NativeRecursiveBackend implements ObservationBackend {
|
||||
}
|
||||
}
|
||||
|
||||
private async scanTree(root: string): Promise<Inventory> {
|
||||
private async scanTree(root: string, generation: number): Promise<Inventory> {
|
||||
const files = new Set<string>();
|
||||
const directories = new Set<string>();
|
||||
const entries = new Map<string, DirectoryEntry>();
|
||||
const pending = [root];
|
||||
while (pending.length > 0 && this.host.isActive()) {
|
||||
const slice = createScanSliceBudget();
|
||||
while (pending.length > 0 && this.canCommit(generation)) {
|
||||
const directory = pending.pop();
|
||||
if (!directory) continue;
|
||||
if (this.host.isIgnored(directory)) continue;
|
||||
let children: Dirent[];
|
||||
try {
|
||||
children = await readdir(directory, { withFileTypes: true });
|
||||
@@ -285,26 +288,58 @@ class NativeRecursiveBackend implements ObservationBackend {
|
||||
if (!isMissingPathError(error) || directory === this.host.root) throw error;
|
||||
continue;
|
||||
}
|
||||
directories.add(directory);
|
||||
this.assertWithinLimit(files.size + directories.size);
|
||||
const entry: DirectoryEntry = { directories: new Set(), files: new Set() };
|
||||
for (const child of children) {
|
||||
const path = join(directory, child.name);
|
||||
if (this.host.isIgnored(path)) continue;
|
||||
if (child.isDirectory()) {
|
||||
entry.directories.add(path);
|
||||
pending.push(path);
|
||||
} else {
|
||||
entry.files.add(path);
|
||||
files.add(path);
|
||||
this.assertWithinLimit(files.size + directories.size);
|
||||
}
|
||||
if (!this.canCommit(generation)) return { directories, entries, files };
|
||||
if (this.host.isIgnored(directory)) continue;
|
||||
const inventory: Inventory = { directories, entries, files };
|
||||
const keepScanning = await this.scanDirectoryChildren(
|
||||
directory,
|
||||
children,
|
||||
generation,
|
||||
inventory,
|
||||
pending,
|
||||
slice,
|
||||
);
|
||||
if (!keepScanning) return inventory;
|
||||
if (slice.isExpired()) {
|
||||
await slice.yield();
|
||||
}
|
||||
entries.set(directory, entry);
|
||||
}
|
||||
return { directories, entries, files };
|
||||
}
|
||||
|
||||
private async scanDirectoryChildren(
|
||||
directory: string,
|
||||
children: Dirent[],
|
||||
generation: number,
|
||||
inventory: Inventory,
|
||||
pending: string[],
|
||||
slice: ScanSliceBudget,
|
||||
): Promise<boolean> {
|
||||
const baseCount = inventory.files.size + inventory.directories.size + 1;
|
||||
this.assertWithinLimit(baseCount);
|
||||
const entry: DirectoryEntry = { directories: new Set(), files: new Set() };
|
||||
for (const child of children) {
|
||||
if (slice.shouldYield()) {
|
||||
await slice.yield();
|
||||
if (!this.canCommit(generation)) return false;
|
||||
if (this.host.isIgnored(directory)) return true;
|
||||
}
|
||||
const path = join(directory, child.name);
|
||||
if (this.host.isIgnoredRoot(path)) continue;
|
||||
if (child.isDirectory()) {
|
||||
entry.directories.add(path);
|
||||
} else {
|
||||
entry.files.add(path);
|
||||
this.assertWithinLimit(baseCount + entry.files.size);
|
||||
}
|
||||
}
|
||||
inventory.directories.add(directory);
|
||||
for (const file of entry.files) inventory.files.add(file);
|
||||
for (const childDir of entry.directories) pending.push(childDir);
|
||||
inventory.entries.set(directory, entry);
|
||||
return true;
|
||||
}
|
||||
|
||||
private async reconcileScopes(
|
||||
localScopes: string[],
|
||||
changeScopes: string[],
|
||||
@@ -344,9 +379,13 @@ class NativeRecursiveBackend implements ObservationBackend {
|
||||
await this.reconcileUnknownSubtree(directory, generation);
|
||||
return;
|
||||
}
|
||||
const next = await this.readDirectory(directory);
|
||||
const next = await this.readDirectory(directory, generation);
|
||||
if (!this.canCommit(generation)) return;
|
||||
if (!next) {
|
||||
if (this.host.isIgnored(directory)) {
|
||||
this.removeSubtree(directory, false);
|
||||
return;
|
||||
}
|
||||
this.removeSubtree(directory, true);
|
||||
return;
|
||||
}
|
||||
@@ -372,7 +411,7 @@ class NativeRecursiveBackend implements ObservationBackend {
|
||||
}
|
||||
for (const path of next.directories) {
|
||||
if (previous.directories.has(path)) continue;
|
||||
const inventory = await this.scanTree(path);
|
||||
const inventory = await this.scanTree(path, generation);
|
||||
if (!this.canCommit(generation)) return;
|
||||
if (!inventory.directories.has(path)) {
|
||||
next.directories.delete(path);
|
||||
@@ -386,7 +425,7 @@ class NativeRecursiveBackend implements ObservationBackend {
|
||||
}
|
||||
|
||||
private async reconcileUnknownSubtree(directory: string, generation: number): Promise<void> {
|
||||
const inventory = await this.scanTree(directory);
|
||||
const inventory = await this.scanTree(directory, generation);
|
||||
if (!this.canCommit(generation)) return;
|
||||
if (!inventory.directories.has(directory)) {
|
||||
this.removeSubtree(directory, true);
|
||||
@@ -396,7 +435,10 @@ class NativeRecursiveBackend implements ObservationBackend {
|
||||
this.mergeInventory(inventory, true);
|
||||
}
|
||||
|
||||
private async readDirectory(directory: string): Promise<DirectoryEntry | null> {
|
||||
private async readDirectory(
|
||||
directory: string,
|
||||
generation: number,
|
||||
): Promise<DirectoryEntry | null> {
|
||||
this.host.metrics.nativeShallowScanCount += 1;
|
||||
let children: Dirent[];
|
||||
try {
|
||||
@@ -405,10 +447,16 @@ class NativeRecursiveBackend implements ObservationBackend {
|
||||
if (!isMissingPathError(error) || directory === this.host.root) throw error;
|
||||
return null;
|
||||
}
|
||||
if (!this.canCommit(generation) || this.host.isIgnored(directory)) return null;
|
||||
const entry: DirectoryEntry = { directories: new Set(), files: new Set() };
|
||||
const slice = createScanSliceBudget();
|
||||
for (const child of children) {
|
||||
if (slice.shouldYield()) {
|
||||
await slice.yield();
|
||||
if (!this.canCommit(generation) || this.host.isIgnored(directory)) return null;
|
||||
}
|
||||
const path = join(directory, child.name);
|
||||
if (this.host.isIgnored(path)) continue;
|
||||
if (this.host.isIgnoredRoot(path)) continue;
|
||||
if (child.isDirectory()) entry.directories.add(path);
|
||||
else entry.files.add(path);
|
||||
}
|
||||
@@ -417,7 +465,7 @@ class NativeRecursiveBackend implements ObservationBackend {
|
||||
|
||||
private async reconcileSubtree(directory: string, generation: number): Promise<void> {
|
||||
if (!this.directories.has(directory) || this.host.isIgnored(directory)) return;
|
||||
const inventory = await this.scanTree(directory);
|
||||
const inventory = await this.scanTree(directory, generation);
|
||||
if (!this.canCommit(generation)) return;
|
||||
const previousFiles = new Set<string>();
|
||||
for (const tracked of this.walkSubtree(directory)) {
|
||||
|
||||
@@ -13,6 +13,7 @@ import type {
|
||||
ObservationHost,
|
||||
ObserverMetrics,
|
||||
} from "./contracts.js";
|
||||
import type { PathContainmentMatcher } from "../../../utils/path.js";
|
||||
import type { ObserverPaths } from "./paths.js";
|
||||
import { toError } from "./paths.js";
|
||||
|
||||
@@ -41,6 +42,7 @@ class Observation implements ManagedObservation, ObservationHost {
|
||||
readonly root: string;
|
||||
readonly metrics: ObserverMetrics;
|
||||
private ignoredRoots: string[];
|
||||
private ignoreMatcher: PathContainmentMatcher;
|
||||
private status: "open" | "failed" | "closed" = "open";
|
||||
private readonly backend: ObservationBackend;
|
||||
private readonly pendingEvents = new Map<string, FileChange>();
|
||||
@@ -61,6 +63,7 @@ class Observation implements ManagedObservation, ObservationHost {
|
||||
this.root = input.root;
|
||||
this.metrics = input.metrics;
|
||||
this.ignoredRoots = input.paths.normalizeIgnoredRoots(input.root, input.options.ignore ?? []);
|
||||
this.ignoreMatcher = input.paths.createIgnoreMatcher(this.ignoredRoots);
|
||||
this.backend = input.createBackend(this);
|
||||
}
|
||||
|
||||
@@ -91,6 +94,7 @@ class Observation implements ManagedObservation, ObservationHost {
|
||||
const next = this.input.paths.normalizeIgnoredRoots(this.root, paths);
|
||||
if (samePaths(this.ignoredRoots, next)) return;
|
||||
this.ignoredRoots = next;
|
||||
this.ignoreMatcher = this.input.paths.createIgnoreMatcher(next);
|
||||
for (const path of this.pendingEvents.keys()) {
|
||||
if (this.isIgnored(path)) this.pendingEvents.delete(path);
|
||||
}
|
||||
@@ -122,7 +126,11 @@ class Observation implements ManagedObservation, ObservationHost {
|
||||
}
|
||||
|
||||
isIgnored(path: string): boolean {
|
||||
return this.ignoredRoots.some((root) => this.input.paths.isInside(root, path));
|
||||
return this.ignoreMatcher.matches(path);
|
||||
}
|
||||
|
||||
isIgnoredRoot(path: string): boolean {
|
||||
return this.ignoreMatcher.matchesExact(path);
|
||||
}
|
||||
|
||||
isPathInside(root: string, path: string): boolean {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { win32 } from "node:path";
|
||||
import { posix, win32 } from "node:path";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { createObserverPaths } from "./paths.js";
|
||||
|
||||
@@ -40,3 +40,36 @@ describe("collapse", () => {
|
||||
expect(paths.collapse([parent, sibling, descendant]).sort()).toEqual([parent, sibling].sort());
|
||||
});
|
||||
});
|
||||
|
||||
describe("ignored root matching", () => {
|
||||
test.each(["linux", "win32"] as const)(
|
||||
"matches ancestors, exact roots, and sibling boundaries on %s",
|
||||
(platform) => {
|
||||
const paths = createObserverPaths(platform);
|
||||
const root = platform === "win32" ? "C:\\repo" : "/repo";
|
||||
const api = platform === "win32" ? win32 : posix;
|
||||
const ignored = api.join(root, "output");
|
||||
const matcher = paths.createIgnoreMatcher([ignored]);
|
||||
expect(matcher.matches(ignored)).toBe(true);
|
||||
expect(matcher.matches(api.join(ignored, "nested", "file.txt"))).toBe(true);
|
||||
expect(matcher.matches(api.join(root, "output-sibling", "file.txt"))).toBe(false);
|
||||
expect(matcher.matches(root)).toBe(false);
|
||||
expect(matcher.matches(api.join(root, "src", "file.txt"))).toBe(false);
|
||||
|
||||
expect(matcher.matchesExact(ignored)).toBe(true);
|
||||
expect(matcher.matchesExact(api.join(ignored, "nested"))).toBe(false);
|
||||
expect(matcher.matchesExact(api.join(root, "output-sibling"))).toBe(false);
|
||||
|
||||
if (platform === "win32") {
|
||||
expect(matcher.matches(api.join(ignored, "nested", "file.txt").toUpperCase())).toBe(true);
|
||||
expect(matcher.matchesExact(ignored.toUpperCase())).toBe(true);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("an empty ignore set rejects no paths", () => {
|
||||
const matcher = createObserverPaths("linux").createIgnoreMatcher([]);
|
||||
expect(matcher.matches("/repo/file.txt")).toBe(false);
|
||||
expect(matcher.matchesExact("/repo/file.txt")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { posix, win32 } from "node:path";
|
||||
import { createPathContainmentMatcher, type PathContainmentMatcher } from "../../../utils/path.js";
|
||||
|
||||
export interface ObserverPaths {
|
||||
isInside(root: string, path: string): boolean;
|
||||
normalizeIgnoredRoots(root: string, paths: string[]): string[];
|
||||
collapse(paths: string[]): string[];
|
||||
createIgnoreMatcher(roots: string[]): PathContainmentMatcher;
|
||||
isExpectedWatchDisappearance(error: unknown): boolean;
|
||||
}
|
||||
|
||||
@@ -50,6 +52,9 @@ export function createObserverPaths(platform: NodeJS.Platform): ObserverPaths {
|
||||
return {
|
||||
isInside,
|
||||
collapse,
|
||||
createIgnoreMatcher(roots) {
|
||||
return createPathContainmentMatcher({ roots, compareAsWindows: platform === "win32" });
|
||||
},
|
||||
normalizeIgnoredRoots(root, paths) {
|
||||
const inside = paths
|
||||
.map((path) => pathApi.resolve(path))
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
const SCAN_YIELD_BUDGET_MS = 8;
|
||||
const SCAN_YIELD_CHECK_STRIDE = 256;
|
||||
|
||||
export interface ScanSliceBudget {
|
||||
/** True on a stride boundary once the current event-loop slice budget has elapsed. */
|
||||
shouldYield(): boolean;
|
||||
/** True once the current event-loop slice budget has elapsed (for directory boundaries). */
|
||||
isExpired(): boolean;
|
||||
/** Yield to the event loop via setImmediate and start a fresh slice. */
|
||||
yield(): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cooperative time-slice budget for directory scans. Checking the clock only every
|
||||
* `SCAN_YIELD_CHECK_STRIDE` entries keeps the hot loop free of per-entry allocations
|
||||
* or awaits while bounding uninterrupted main-thread work to roughly one slice.
|
||||
*/
|
||||
export function createScanSliceBudget(): ScanSliceBudget {
|
||||
let sliceStartedAt = performance.now();
|
||||
let entriesSinceCheck = 0;
|
||||
|
||||
return {
|
||||
shouldYield() {
|
||||
entriesSinceCheck += 1;
|
||||
if (entriesSinceCheck < SCAN_YIELD_CHECK_STRIDE) return false;
|
||||
entriesSinceCheck = 0;
|
||||
return performance.now() - sliceStartedAt >= SCAN_YIELD_BUDGET_MS;
|
||||
},
|
||||
isExpired() {
|
||||
return performance.now() - sliceStartedAt >= SCAN_YIELD_BUDGET_MS;
|
||||
},
|
||||
async yield() {
|
||||
entriesSinceCheck = 0;
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
sliceStartedAt = performance.now();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -3,7 +3,11 @@ import { readlink } from "node:fs/promises";
|
||||
import { promisify } from "node:util";
|
||||
import pLimit from "p-limit";
|
||||
import { dirname, resolve as resolvePath, sep } from "node:path";
|
||||
import { looksLikeDefiniteWindowsPath, normalizePathPreservingCase } from "../utils/path.js";
|
||||
import {
|
||||
createPathContainmentMatcher,
|
||||
looksLikeDefiniteWindowsPath,
|
||||
normalizePathPreservingCase,
|
||||
} from "../utils/path.js";
|
||||
|
||||
const nativeRealpath = promisify(realpath.native);
|
||||
const jsRealpath = promisify(realpath);
|
||||
@@ -82,15 +86,15 @@ export class GitObservationPaths {
|
||||
excluded.push(this.windows ? subtree.toLowerCase() : subtree);
|
||||
}
|
||||
}
|
||||
const prefixes = excluded.map((root) => `${root}/`);
|
||||
const excludedMatcher = createPathContainmentMatcher({
|
||||
roots: excluded,
|
||||
compareAsWindows: this.windows,
|
||||
});
|
||||
return (candidate) => {
|
||||
const normalized = this.normalizeEventPath(candidate);
|
||||
const comparable = this.windows ? normalized.toLowerCase() : normalized;
|
||||
if (this.aliases.includes(comparable)) return false;
|
||||
for (let i = 0; i < excluded.length; i++) {
|
||||
if (comparable === excluded[i] || comparable.startsWith(prefixes[i])) return false;
|
||||
}
|
||||
return true;
|
||||
return !excludedMatcher.matches(comparable);
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSy
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { monitorEventLoopDelay } from "node:perf_hooks";
|
||||
import pino from "pino";
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
import {
|
||||
@@ -1578,3 +1579,69 @@ test("a failed parent lookup is not repeated by forced refreshes before the retr
|
||||
|
||||
expect(lookups).toBe(1);
|
||||
}, 30_000);
|
||||
|
||||
test("working-tree observation stays responsive with thousands of ignored directories and wide folders", async () => {
|
||||
const root = realpathSync(mkdtempSync(path.join(tmpdir(), "paseo-large-ignore-")));
|
||||
const repo = path.join(root, "repo");
|
||||
mkdirSync(repo, { recursive: true });
|
||||
cleanup.push(async () => {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
execFileSync("git", ["init", "-b", "main"], { cwd: repo, stdio: "pipe" });
|
||||
execFileSync("git", ["config", "user.email", "test@paseo.local"], { cwd: repo, stdio: "pipe" });
|
||||
execFileSync("git", ["config", "user.name", "Paseo Test"], { cwd: repo, stdio: "pipe" });
|
||||
writeFileSync(path.join(repo, ".gitignore"), "ig-*/\n");
|
||||
const trackedDir = path.join(repo, "wide");
|
||||
mkdirSync(trackedDir, { recursive: true });
|
||||
const trackedFile = path.join(trackedDir, "tracked-0.txt");
|
||||
writeFileSync(trackedFile, "initial\n");
|
||||
execFileSync("git", ["add", ".gitignore", "wide/tracked-0.txt"], { cwd: repo, stdio: "pipe" });
|
||||
execFileSync("git", ["commit", "-m", "init"], { cwd: repo, stdio: "pipe" });
|
||||
|
||||
// 4,000 ignored directories reported individually by `git ls-files -o -i --directory`
|
||||
// plus 3,000 files in one folder (12M pairs under linear matching).
|
||||
for (let i = 0; i < 4_000; i++) {
|
||||
const ignored = path.join(repo, `ig-${i}`);
|
||||
mkdirSync(ignored);
|
||||
writeFileSync(path.join(ignored, "out.bin"), "x");
|
||||
}
|
||||
for (let i = 1; i < 3_000; i++) {
|
||||
writeFileSync(path.join(trackedDir, `file-${i}.txt`), "x");
|
||||
}
|
||||
|
||||
const service = new WorkspaceGitServiceImpl({
|
||||
logger: pino({ enabled: false }),
|
||||
paseoHome: path.join(root, "home"),
|
||||
});
|
||||
cleanup.push(() => service.dispose());
|
||||
|
||||
let notifications = 0;
|
||||
const eld = monitorEventLoopDelay({ resolution: 10 });
|
||||
eld.enable();
|
||||
let watch: Awaited<ReturnType<WorkspaceGitServiceImpl["requestWorkingTreeWatch"]>> | null = null;
|
||||
try {
|
||||
watch = await service.requestWorkingTreeWatch(repo, () => {
|
||||
notifications += 1;
|
||||
});
|
||||
expect(service.getMetrics().fileObserver.activeObservationCount).toBe(1);
|
||||
// Allow one timer tick to capture any event-loop stall from setup.
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 30));
|
||||
eld.disable();
|
||||
|
||||
// Even under CI scheduling jitter, setup must not block the event loop for seconds.
|
||||
expect(eld.max / 1e6).toBeLessThan(1_000);
|
||||
|
||||
// Ignored writes stay silent while tracked writes still notify.
|
||||
notifications = 0;
|
||||
writeFileSync(path.join(repo, "ig-0", "out.bin"), "ignored-change");
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 150));
|
||||
expect(notifications).toBe(0);
|
||||
|
||||
writeFileSync(trackedFile, "updated\n");
|
||||
await expect.poll(() => notifications, { timeout: 5_000 }).toBeGreaterThan(0);
|
||||
} finally {
|
||||
eld.disable();
|
||||
watch?.unsubscribe();
|
||||
}
|
||||
}, 30_000);
|
||||
|
||||
@@ -1757,6 +1757,37 @@ describe("WorkspaceGitServiceImpl", () => {
|
||||
30_000,
|
||||
);
|
||||
|
||||
test("rejects and unsubscribes a watcher subscription that resolves past its deadline before the timeout timer runs", async () => {
|
||||
vi.useFakeTimers();
|
||||
let monotonicMs = 1_000;
|
||||
const lateSubscription = createAsyncSubscription();
|
||||
let attempts = 0;
|
||||
const subscribe = vi.fn(async (directory: string) => {
|
||||
if (directory === REPO_CWD && ++attempts === 1) {
|
||||
// Advance the monotonic clock past the deadline without firing timers, matching a
|
||||
// synchronous stall whose subscribe() resolves in a microtask before setTimeout runs.
|
||||
monotonicMs += WORKSPACE_GIT_WATCHER_SUBSCRIBE_TIMEOUT_MS + 500;
|
||||
return lateSubscription;
|
||||
}
|
||||
return createAsyncSubscription();
|
||||
});
|
||||
const service = createService({ subscribe, monotonicNow: () => monotonicMs });
|
||||
const subscription = service.registerWorkspace({ cwd: REPO_CWD }, vi.fn());
|
||||
try {
|
||||
await settle(() => expect(attempts).toBe(1));
|
||||
await waitForObservationToSettle(service, 1);
|
||||
expect(lateSubscription.unsubscribe).toHaveBeenCalledTimes(1);
|
||||
// Confirm timeout backoff was recorded (first retry waits 30s).
|
||||
await vi.advanceTimersByTimeAsync(29_999);
|
||||
expect(attempts).toBe(1);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
await settle(() => expect(attempts).toBe(2));
|
||||
} finally {
|
||||
subscription.unsubscribe();
|
||||
await service.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
test.each(["repository metadata", "working tree"])(
|
||||
"keeps the %s watcher retry delay when the last observer reconnects",
|
||||
async (kind) => {
|
||||
|
||||
@@ -44,7 +44,11 @@ import {
|
||||
type ForgeResolver,
|
||||
} from "../services/forge-resolver.js";
|
||||
import { parseGitRevParsePath } from "../utils/git-rev-parse-path.js";
|
||||
import { isPathInsideRoot, looksLikeDefiniteWindowsPath } from "../utils/path.js";
|
||||
import {
|
||||
createPathContainmentMatcher,
|
||||
isPathInsideRoot,
|
||||
looksLikeDefiniteWindowsPath,
|
||||
} from "../utils/path.js";
|
||||
import {
|
||||
createRunGitCommand,
|
||||
runGitCommand,
|
||||
@@ -444,6 +448,7 @@ interface WorkspaceGitServiceDependencies {
|
||||
createWatcherLivenessCanary: typeof createWatcherLivenessCanary;
|
||||
workspaceFolderExists: (cwd: string) => Promise<boolean>;
|
||||
now: () => Date;
|
||||
monotonicNow: () => number;
|
||||
}
|
||||
|
||||
interface WorkspaceGitServiceOptions {
|
||||
@@ -649,6 +654,7 @@ function buildDefaultWorkspaceGitServiceDeps(
|
||||
createWatcherLivenessCanary,
|
||||
workspaceFolderExists,
|
||||
now: () => new Date(),
|
||||
monotonicNow: () => performance.now(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1595,6 +1601,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
): Promise<FileObserverSubscription> {
|
||||
this.assertNotDisposed();
|
||||
const signal = this.disposeController.signal;
|
||||
const startedAtMs = this.deps.monotonicNow();
|
||||
let outcome: "pending" | "accepted" | "expired" = "pending";
|
||||
let timeout: NodeJS.Timeout | null = null;
|
||||
let removeAbortListener = () => {};
|
||||
@@ -1655,6 +1662,17 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
await unsubscribePromise;
|
||||
throw signal.reason;
|
||||
}
|
||||
// A synchronous stall can outlive the deadline and resolve `subscriptionPromise` in the
|
||||
// microtask queue before the expired timeout timer fires. Enforce the monotonic deadline
|
||||
// directly so late subscriptions still time out, clean up, and enter backoff.
|
||||
if (this.deps.monotonicNow() - startedAtMs >= WORKSPACE_GIT_WATCHER_SUBSCRIBE_TIMEOUT_MS) {
|
||||
outcome = "expired";
|
||||
const error = new WorkspaceGitWatcherSubscriptionTimeoutError(watchPath);
|
||||
setupController.abort(error);
|
||||
unsubscribePromise ??= this.unsubscribeWatcherSubscription(subscription, watchPath);
|
||||
await unsubscribePromise;
|
||||
throw error;
|
||||
}
|
||||
outcome = "accepted";
|
||||
return subscription;
|
||||
} finally {
|
||||
@@ -2160,14 +2178,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
if (isPathInsideRoot(gitDir, directory)) {
|
||||
continue;
|
||||
}
|
||||
let ignored = false;
|
||||
for (const ignoredDirectory of target.ignoredDirectories) {
|
||||
if (isPathInsideRoot(ignoredDirectory, directory)) {
|
||||
ignored = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (ignored) {
|
||||
if (!target.acceptsEvent(directory)) {
|
||||
continue;
|
||||
}
|
||||
target.knownDirectories.add(directory);
|
||||
@@ -2281,23 +2292,12 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
if (target.ignoredDirectories.size === 0) {
|
||||
return;
|
||||
}
|
||||
const foldCase = looksLikeDefiniteWindowsPath(target.watchPath);
|
||||
const comparable = (path: string) =>
|
||||
foldCase ? path.replaceAll("\\", "/").toLowerCase() : path;
|
||||
const ignoredPrefixes: string[] = [];
|
||||
const foldedIgnoredExact = foldCase ? new Set<string>() : null;
|
||||
for (const ignoredDirectory of target.ignoredDirectories) {
|
||||
const ignored = comparable(ignoredDirectory);
|
||||
ignoredPrefixes.push(`${ignored}/`);
|
||||
foldedIgnoredExact?.add(ignored);
|
||||
}
|
||||
const ignoredMatcher = createPathContainmentMatcher({
|
||||
roots: target.ignoredDirectories,
|
||||
compareAsWindows: looksLikeDefiniteWindowsPath(target.watchPath),
|
||||
});
|
||||
for (const directory of target.knownDirectories) {
|
||||
const comparableDirectory = comparable(directory);
|
||||
const comparableDirectoryWithSep = `${comparableDirectory}/`;
|
||||
const isIgnored =
|
||||
(foldedIgnoredExact ?? target.ignoredDirectories).has(comparableDirectory) ||
|
||||
ignoredPrefixes.some((prefix) => comparableDirectoryWithSep.startsWith(prefix));
|
||||
if (isIgnored) {
|
||||
if (ignoredMatcher.matches(directory)) {
|
||||
target.knownDirectories.delete(directory);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { describe, expect, test } from "vitest";
|
||||
|
||||
import {
|
||||
areEquivalentPaths,
|
||||
createPathContainmentMatcher,
|
||||
createPathEquivalenceMatcher,
|
||||
getRealpathAwareRelativePath,
|
||||
isPathInsideRoot,
|
||||
@@ -97,3 +98,53 @@ describe("path equivalence", () => {
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("indexed path containment", () => {
|
||||
test("preserves POSIX case and component boundaries for ancestor and exact checks", () => {
|
||||
const matcher = createPathContainmentMatcher({
|
||||
roots: ["/repo/Build/", "/repo/cache"],
|
||||
compareAsWindows: false,
|
||||
});
|
||||
expect(matcher.matches("/repo/Build/nested/file")).toBe(true);
|
||||
expect(matcher.matches("/repo/cache")).toBe(true);
|
||||
expect(matcher.matches("/repo/Build-sibling/file")).toBe(false);
|
||||
expect(matcher.matches("/repo/build/file")).toBe(false);
|
||||
expect(matcher.matches("/repo")).toBe(false);
|
||||
|
||||
expect(matcher.matchesExact("/repo/Build")).toBe(true);
|
||||
expect(matcher.matchesExact("/repo/Build/")).toBe(true);
|
||||
expect(matcher.matchesExact("/repo/cache")).toBe(true);
|
||||
expect(matcher.matchesExact("/repo/Build/nested/file")).toBe(false);
|
||||
expect(matcher.matchesExact("/repo/build")).toBe(false);
|
||||
});
|
||||
|
||||
test("normalizes Windows case, separators and extended namespaces", () => {
|
||||
const matcher = createPathContainmentMatcher({
|
||||
roots: ["C:/Repo/Build", String.raw`\\server\share\cache`],
|
||||
compareAsWindows: true,
|
||||
});
|
||||
expect(matcher.matches(String.raw`\\?\C:\REPO\build\file`)).toBe(true);
|
||||
expect(matcher.matches(String.raw`\\?\UNC\SERVER\SHARE\Cache\file`)).toBe(true);
|
||||
expect(matcher.matches("C:/Repo/Build-Sibling/file")).toBe(false);
|
||||
expect(matcher.matches(String.raw`\\server\share\cache-sibling\file`)).toBe(false);
|
||||
|
||||
expect(matcher.matchesExact(String.raw`\\?\C:\REPO\build`)).toBe(true);
|
||||
expect(matcher.matchesExact(String.raw`\\?\UNC\SERVER\SHARE\Cache`)).toBe(true);
|
||||
expect(matcher.matchesExact(String.raw`\\?\C:\REPO\build\file`)).toBe(false);
|
||||
});
|
||||
|
||||
test("handles filesystem roots and empty sets", () => {
|
||||
const posixRoot = createPathContainmentMatcher({ roots: ["/"], compareAsWindows: false });
|
||||
expect(posixRoot.matches("/repo/file")).toBe(true);
|
||||
expect(posixRoot.matchesExact("/")).toBe(true);
|
||||
expect(posixRoot.matchesExact("/repo")).toBe(false);
|
||||
|
||||
const winRoot = createPathContainmentMatcher({ roots: ["C:/"], compareAsWindows: true });
|
||||
expect(winRoot.matches("c:/repo/file")).toBe(true);
|
||||
expect(winRoot.matchesExact("c:\\")).toBe(true);
|
||||
|
||||
const empty = createPathContainmentMatcher({ roots: [], compareAsWindows: false });
|
||||
expect(empty.matches("/repo/file")).toBe(false);
|
||||
expect(empty.matchesExact("/repo/file")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -72,6 +72,62 @@ export function stopPathContainmentMetrics(): number {
|
||||
return checks;
|
||||
}
|
||||
|
||||
export interface PathContainmentOptions {
|
||||
roots: Iterable<string>;
|
||||
compareAsWindows: boolean;
|
||||
}
|
||||
|
||||
export interface PathContainmentMatcher {
|
||||
/** True when `candidate` is one of the compiled roots or lies beneath one. */
|
||||
matches(candidate: string): boolean;
|
||||
/** True only when `candidate` itself is one of the compiled roots (O(1) lookup). */
|
||||
matchesExact(candidate: string): boolean;
|
||||
}
|
||||
|
||||
function toComparableContainmentPath(value: string, compareAsWindows: boolean): string {
|
||||
if (
|
||||
!compareAsWindows &&
|
||||
value.length > 1 &&
|
||||
!value.endsWith("/") &&
|
||||
!value.includes("/.") &&
|
||||
!value.includes("//")
|
||||
) {
|
||||
return value;
|
||||
}
|
||||
return normalizePathForComparison(value, compareAsWindows);
|
||||
}
|
||||
|
||||
/** Compile lexical subtree membership without scanning unrelated roots per candidate. */
|
||||
export function createPathContainmentMatcher({
|
||||
roots,
|
||||
compareAsWindows,
|
||||
}: PathContainmentOptions): PathContainmentMatcher {
|
||||
const pathApi = compareAsWindows ? nodePath.win32 : nodePath.posix;
|
||||
const indexed = new Set(
|
||||
Array.from(roots, (root) => normalizePathForComparison(root, compareAsWindows)),
|
||||
);
|
||||
if (indexed.size === 0) {
|
||||
return {
|
||||
matches: () => false,
|
||||
matchesExact: () => false,
|
||||
};
|
||||
}
|
||||
return {
|
||||
matches(candidate) {
|
||||
let current = toComparableContainmentPath(candidate, compareAsWindows);
|
||||
for (;;) {
|
||||
if (indexed.has(current)) return true;
|
||||
const parent = pathApi.dirname(current);
|
||||
if (parent === current) return false;
|
||||
current = parent;
|
||||
}
|
||||
},
|
||||
matchesExact(candidate) {
|
||||
return indexed.has(toComparableContainmentPath(candidate, compareAsWindows));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function isPathInsideRoot(root: string, candidate: string): boolean {
|
||||
if (pathContainmentChecks !== null) pathContainmentChecks += 1;
|
||||
return getRelativePathInsideRoot(root, candidate) !== null;
|
||||
|
||||
Reference in New Issue
Block a user