Skip to content

Commit 684daee

Browse files
committed
fix(server): bound folder reads and close interrupted directory searches
1 parent da81dcd commit 684daee

3 files changed

Lines changed: 110 additions & 21 deletions

File tree

‎apps/server/src/workspace/WorkspaceEntries.test.ts‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,7 @@ function makeHang<A>(value: A) {
9898
});
9999
return {
100100
called,
101+
promise,
101102
hang: () => {
102103
markCalled();
103104
return promise;
@@ -1513,6 +1514,58 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => {
15131514
}).pipe(Effect.provide(TestClock.layer()), Effect.ensuring(Effect.sync(read.release)));
15141515
}),
15151516
);
1517+
it.effect("bounds stalled browse reads while callers can still join an existing read", () =>
1518+
Effect.gen(function* () {
1519+
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
1520+
const firstPath = yield* appendSeparator(yield* makeTempDir());
1521+
const secondPath = yield* appendSeparator(yield* makeTempDir());
1522+
const availablePath = yield* appendSeparator(yield* makeTempDir());
1523+
const first = makeHang<Awaited<ReturnType<typeof NodeFSP.readdir>>>([]);
1524+
const second = makeHang<Awaited<ReturnType<typeof NodeFSP.readdir>>>([]);
1525+
const readdir = vi.mocked(NodeFSP.readdir);
1526+
readdir.mockClear();
1527+
readdir
1528+
.mockImplementationOnce(first.hang as unknown as typeof NodeFSP.readdir)
1529+
.mockImplementationOnce(second.hang as unknown as typeof NodeFSP.readdir);
1530+
const browse = (partialPath: string) => workspaceEntries.browse({ partialPath });
1531+
1532+
yield* Effect.gen(function* () {
1533+
const firstCaller = yield* Effect.forkChild(browse(firstPath).pipe(Effect.flip));
1534+
yield* Effect.promise(() => first.called);
1535+
const secondCaller = yield* Effect.forkChild(browse(secondPath).pipe(Effect.flip));
1536+
yield* Effect.promise(() => second.called);
1537+
yield* TestClock.adjust("5 seconds");
1538+
1539+
for (const caller of [firstCaller, secondCaller]) {
1540+
expect(yield* Fiber.join(caller)).toMatchObject({
1541+
_tag: "WorkspaceEntriesReadDirectoryError",
1542+
cause: { reason: { _tag: "TimedOut" } },
1543+
});
1544+
}
1545+
expect(yield* browse(availablePath).pipe(Effect.flip)).toMatchObject({
1546+
_tag: "WorkspaceEntriesReadDirectoryError",
1547+
cause: { reason: { _tag: "TimedOut" } },
1548+
});
1549+
1550+
const joinedCaller = yield* Effect.forkChild(browse(firstPath));
1551+
yield* TestClock.adjust(0);
1552+
first.release();
1553+
expect(yield* Fiber.join(joinedCaller)).toMatchObject({ entries: [] });
1554+
expect(readdir).toHaveBeenCalledTimes(2);
1555+
1556+
expect(yield* browse(availablePath)).toMatchObject({ entries: [] });
1557+
expect(readdir).toHaveBeenCalledTimes(3);
1558+
}).pipe(
1559+
Effect.provide(TestClock.layer()),
1560+
Effect.ensuring(
1561+
Effect.sync(() => {
1562+
first.release();
1563+
second.release();
1564+
}),
1565+
),
1566+
);
1567+
}),
1568+
);
15161569
});
15171570

15181571
describe("places", () => {
@@ -1956,6 +2009,30 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => {
19562009
}),
19572010
);
19582011

2012+
it.effect("closes a folder handle that opens after search interruption", () =>
2013+
Effect.gen(function* () {
2014+
const { root, canonicalRoot } = yield* makeTree([]);
2015+
const actualOpendir = NodeFSP.opendir;
2016+
const { close } = makeClose();
2017+
const read = vi.fn(() => Promise.resolve(null));
2018+
const opening = makeHang({ read, close });
2019+
vi.spyOn(NodeFSP, "opendir").mockImplementation(((target, options) =>
2020+
target === canonicalRoot
2021+
? opening.hang()
2022+
: actualOpendir(target, options)) as typeof NodeFSP.opendir);
2023+
2024+
const search = yield* Effect.forkChild(searchDirectories({ rootPath: root, query: "x" }));
2025+
yield* Effect.promise(() => opening.called);
2026+
yield* Fiber.interrupt(search);
2027+
expect(close).not.toHaveBeenCalled();
2028+
2029+
opening.release();
2030+
yield* Effect.promise(() => opening.promise);
2031+
expect(close).toHaveBeenCalledTimes(1);
2032+
expect(read).not.toHaveBeenCalled();
2033+
}),
2034+
);
2035+
19592036
it.effect("counts root checks against the search deadline", () =>
19602037
Effect.gen(function* () {
19612038
const { root, canonicalRoot } = yield* makeTree(["app"]);

‎apps/server/src/workspace/WorkspaceEntries.ts‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,10 @@ const MAX_PENDING_SYMLINK_TARGET_STATS = 2;
256256
const MAX_CONCURRENT_BOUNDED_FS_CALLS = 2;
257257
// Long enough for a slow disk to spin up, short enough that a hung mount fails visibly.
258258
const BROWSE_READ_DIRECTORY_TIMEOUT = Duration.seconds(5);
259+
const MAX_PENDING_BROWSE_READS = 2;
260+
261+
const browseReadTimeout = (directory: string) =>
262+
boundedFsCallError("readdir", directory, { status: "busy" });
259263

260264
const readDirents = (directory: string) => NodeFSP.readdir(directory, { withFileTypes: true });
261265

@@ -339,12 +343,13 @@ export const make = Effect.gen(function* () {
339343
const readBrowseDirectory = (directory: string) => {
340344
const pending = pendingBrowseReads.get(directory);
341345
if (pending !== undefined) return pending;
342-
const read = readDirents(directory);
346+
if (pendingBrowseReads.size >= MAX_PENDING_BROWSE_READS) {
347+
return Promise.reject(browseReadTimeout(directory));
348+
}
349+
const read = readDirents(directory).finally(() => {
350+
pendingBrowseReads.delete(directory);
351+
});
343352
pendingBrowseReads.set(directory, read);
344-
const forget = () => {
345-
if (pendingBrowseReads.get(directory) === read) pendingBrowseReads.delete(directory);
346-
};
347-
void read.then(forget, forget);
348353
return read;
349354
};
350355

@@ -368,8 +373,7 @@ export const make = Effect.gen(function* () {
368373
}).pipe(
369374
Effect.timeoutOrElse({
370375
duration: BROWSE_READ_DIRECTORY_TIMEOUT,
371-
orElse: () =>
372-
Effect.fail(readError(boundedFsCallError("readdir", parentPath, { status: "busy" }))),
376+
orElse: () => Effect.fail(readError(browseReadTimeout(parentPath))),
373377
}),
374378
Effect.catchIf(
375379
(error) => {

‎apps/server/src/workspace/directorySearch.ts‎

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -123,20 +123,28 @@ const readDirectoryInBatches = Effect.fnUntraced(function* (
123123
const openTimeout = yield* callTimeout;
124124
if (openTimeout <= 0) return outOfTime("opendir");
125125
let opening: Promise<NodeFS.Dir> | undefined;
126-
const opened = yield* boundedFsCall(() => {
127-
opening = NodeFSP.opendir(absolutePath, { bufferSize: READ_BATCH_SIZE });
128-
return opening;
129-
}, Duration.millis(openTimeout));
130-
if (opened.status !== "done") {
131-
// A handle that opens after the timeout must still be closed.
132-
if (opening !== undefined) void opening.then(closeQuietly, () => undefined);
133-
return { complete: false, error: boundedFsCallError("opendir", absolutePath, opened) };
134-
}
135-
136-
const dir = opened.value;
126+
let cleanupStarted = false;
137127
// A Dir cannot close while a read is pending, so closing waits for the last batch.
138-
let lastRead: Promise<unknown> = Promise.resolve();
128+
let lastRead: ReturnType<typeof readBatch> | undefined;
129+
const closeAfterRead = (dir: NodeFS.Dir) => {
130+
const close = () => closeQuietly(dir);
131+
return lastRead === undefined ? close() : lastRead.then(close, close);
132+
};
139133
return yield* Effect.gen(function* () {
134+
const opened = yield* boundedFsCall(() => {
135+
opening = NodeFSP.opendir(absolutePath, { bufferSize: READ_BATCH_SIZE });
136+
// The limiter can schedule the open just before the search is interrupted.
137+
if (cleanupStarted) void opening.then(closeAfterRead, () => undefined);
138+
return opening;
139+
}, Duration.millis(openTimeout));
140+
if (opened.status !== "done") {
141+
return {
142+
complete: false,
143+
error: boundedFsCallError("opendir", absolutePath, opened),
144+
} satisfies DirectoryReadResult;
145+
}
146+
147+
const dir = opened.value;
140148
while (true) {
141149
const readTimeout = yield* callTimeout;
142150
if (readTimeout <= 0) return outOfTime("readdir");
@@ -157,8 +165,8 @@ const readDirectoryInBatches = Effect.fnUntraced(function* (
157165
}).pipe(
158166
Effect.ensuring(
159167
Effect.sync(() => {
160-
const close = () => closeQuietly(dir);
161-
void lastRead.then(close, close);
168+
cleanupStarted = true;
169+
void opening?.then(closeAfterRead, () => undefined);
162170
}),
163171
),
164172
);

0 commit comments

Comments
 (0)