Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions packages/workspace-fs/src/watch-cancellation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>();
const gate = deferred<void>();
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<void>((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<void>();
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<string>((resolve) => {
setTimeout(() => resolve("hung"), 500).unref?.();
});
expect(await Promise.race([manager.close().then(() => "closed"), hung])).toBe(
"closed",
);
});
51 changes: 41 additions & 10 deletions packages/workspace-fs/src/watch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,21 +250,31 @@ interface WatcherState {
throttler: ThrottledWorker<FsWatchEvent>;
}

const TEARDOWN_TIMEOUT_MS = 5_000;

async function settleWithin(
work: Promise<unknown>,
timeoutMs: number,
): Promise<void> {
await Promise.race([
work.catch(() => {}),
new Promise<void>((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<void> {
if (!subscription) {
return;
}
await Promise.race([
subscription.unsubscribe().catch(() => {}),
new Promise<void>((resolve) => {
const timer = setTimeout(resolve, 5_000);
timer.unref?.();
}),
]);
await settleWithin(subscription.unsubscribe(), timeoutMs);
}

function internalToFsWatchEvent(event: InternalWatchEvent): FsWatchEvent {
Expand Down Expand Up @@ -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;
}

Expand All @@ -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<Promise<unknown>>();
private readonly pending = new Map<
string,
{
Expand All @@ -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<string, WatcherState>();
/**
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -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 = () => {
Expand All @@ -461,14 +480,26 @@ export class FsWatcherManager {
}
}

private async trackRelease(work: Promise<unknown>): Promise<void> {
this.releasing.add(work);
try {
await work;
} finally {
this.releasing.delete(work);
}
}

async close(): Promise<void> {
const pending = [...this.pending.values()];
this.pending.clear();
for (const entry of pending) entry.controller.abort();
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<void> {
Expand All @@ -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);
}

/**
Expand Down
Loading