diff --git a/packages/workspace-fs/src/watch-cancellation.test.ts b/packages/workspace-fs/src/watch-cancellation.test.ts index d63ba1ca84b..952a106a6eb 100644 --- a/packages/workspace-fs/src/watch-cancellation.test.ts +++ b/packages/workspace-fs/src/watch-cancellation.test.ts @@ -148,3 +148,74 @@ test("watcher readiness refreshes edits made during the background scan", async expect(entries.map((entry) => entry.name)).toContain("during-scan.txt"); await stream.return?.(); }); + +for (const phase of ["attaching", "attached"] as const) { + test(`close waits for the last aborted listener's ${phase} native watch`, async () => { + const rootPath = await root(); + const controller = new AbortController(); + const entered = deferred(); + const gate = deferred(); + let detached = false; + const manager = new FsWatcherManager({ + backend: { + name: "test", + async subscribe() { + entered.resolve(); + if (phase === "attaching") await gate.promise; + return { + async unsubscribe() { + await gate.promise; + detached = true; + }, + }; + }, + }, + }); + managers.push(manager); + const subscription = manager + .subscribe( + { absolutePath: rootPath, signal: controller.signal }, + () => {}, + ) + .catch((error) => { + if (!(error instanceof Error && error.name === "AbortError")) + throw error; + }); + await entered.promise; + if (phase === "attached") await subscription; + controller.abort(); + const closedAfterDetach = manager.close().then(() => detached); + await new Promise((resolve) => setImmediate(resolve)); + gate.resolve(); + expect(await closedAfterDetach).toBe(true); + await subscription; + }); +} + +test("close does not wait forever for an aborted listener's hung native subscribe", async () => { + const rootPath = await root(); + const controller = new AbortController(); + const entered = deferred(); + const manager = new FsWatcherManager({ + teardownTimeoutMs: 5, + backend: { + name: "test", + subscribe() { + entered.resolve(); + return new Promise(() => {}); + }, + }, + }); + managers.push(manager); + void manager + .subscribe({ absolutePath: rootPath, signal: controller.signal }, () => {}) + .catch(() => {}); + await entered.promise; + controller.abort(); + const hung = new Promise((resolve) => { + setTimeout(() => resolve("hung"), 500).unref?.(); + }); + expect(await Promise.race([manager.close().then(() => "closed"), hung])).toBe( + "closed", + ); +}); diff --git a/packages/workspace-fs/src/watch.ts b/packages/workspace-fs/src/watch.ts index 1b0f833cb75..bad44b53517 100644 --- a/packages/workspace-fs/src/watch.ts +++ b/packages/workspace-fs/src/watch.ts @@ -250,21 +250,31 @@ interface WatcherState { throttler: ThrottledWorker; } +const TEARDOWN_TIMEOUT_MS = 5_000; + +async function settleWithin( + work: Promise, + timeoutMs: number, +): Promise { + await Promise.race([ + work.catch(() => {}), + new Promise((resolve) => { + const timer = setTimeout(resolve, timeoutMs); + timer.unref?.(); + }), + ]); +} + // A dead FSEvents stream's unsubscribe can hang forever (observed after the // watch root is deleted out from under it); never let it block teardown. async function unsubscribeQuietly( subscription: NativeWatchSubscription | null, + timeoutMs = TEARDOWN_TIMEOUT_MS, ): Promise { if (!subscription) { return; } - await Promise.race([ - subscription.unsubscribe().catch(() => {}), - new Promise((resolve) => { - const timer = setTimeout(resolve, 5_000); - timer.unref?.(); - }), - ]); + await settleWithin(subscription.unsubscribe(), timeoutMs); } function internalToFsWatchEvent(event: InternalWatchEvent): FsWatchEvent { @@ -323,6 +333,8 @@ export interface FsWatcherManagerOptions { overflowRescanMaxMs?: number; overflowBackoffResetMs?: number; growthReattachMinMs?: number; + /** Limit on native subscribe and unsubscribe during teardown. Test-only override. */ + teardownTimeoutMs?: number; now?: () => number; } @@ -331,6 +343,8 @@ export class FsWatcherManager { private readonly ignore: string[]; private readonly listGitIgnoredDirs?: FsWatcherManagerOptions["listGitIgnoredDirs"]; private readonly findNestedRoots: typeof findNestedRepoRoots; + // Last-listener cleanup leaves the path maps immediately so it can be rewatched. + private readonly releasing = new Set>(); private readonly pending = new Map< string, { @@ -347,6 +361,7 @@ export class FsWatcherManager { private readonly overflowRescanMaxMs: number; private readonly overflowBackoffResetMs: number; private readonly growthReattachMinMs: number; + private readonly teardownTimeoutMs: number; private readonly now: () => number; private readonly watchers = new Map(); /** @@ -392,6 +407,7 @@ export class FsWatcherManager { options.overflowBackoffResetMs ?? OVERFLOW_BACKOFF_RESET_MS; this.growthReattachMinMs = options.growthReattachMinMs ?? IGNORE_GROWTH_REATTACH_MIN_MS; + this.teardownTimeoutMs = options.teardownTimeoutMs ?? TEARDOWN_TIMEOUT_MS; this.now = options.now ?? Date.now; } @@ -440,11 +456,14 @@ export class FsWatcherManager { if (pending && this.pending.get(absolutePath) === pending) { this.pending.delete(absolutePath); pending.controller.abort(); + await this.trackRelease( + settleWithin(pending.promise, this.teardownTimeoutMs), + ); } const current = this.watchers.get(absolutePath); if (current?.listeners === listeners) { this.watchers.delete(absolutePath); - await this.disposeWatcherState(current); + await this.trackRelease(this.disposeWatcherState(current)); } }; const onAbort = () => { @@ -461,6 +480,15 @@ export class FsWatcherManager { } } + private async trackRelease(work: Promise): Promise { + this.releasing.add(work); + try { + await work; + } finally { + this.releasing.delete(work); + } + } + async close(): Promise { const pending = [...this.pending.values()]; this.pending.clear(); @@ -468,7 +496,10 @@ export class FsWatcherManager { await Promise.allSettled(pending.map((entry) => entry.promise)); const states = Array.from(this.watchers.values()); this.watchers.clear(); - await Promise.all(states.map((state) => this.disposeWatcherState(state))); + await Promise.all([ + ...this.releasing, + ...states.map((state) => this.disposeWatcherState(state)), + ]); } private async disposeWatcherState(state: WatcherState): Promise { @@ -495,7 +526,7 @@ export class FsWatcherManager { state.throttler.dispose(); const subscription = state.subscription; state.subscription = null; - await unsubscribeQuietly(subscription); + await unsubscribeQuietly(subscription, this.teardownTimeoutMs); } /**