Skip to content
Open
128 changes: 128 additions & 0 deletions apps/server/src/workspace/WorkspaceFolders.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
// @effect-diagnostics nodeBuiltinImport:off - a FIFO gate must be released with a synchronous
// open on the main thread, because the Effect FileSystem queues behind the pinned libuv pool.
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
import { assert, it } from "@effect/vitest";
import { ProjectId, type ProjectTrackedFolder } from "@t3tools/contracts";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
import * as TestClock from "effect/testing/TestClock";

import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
import * as SqlitePersistence from "../persistence/Sqlite.ts";
Expand Down Expand Up @@ -245,6 +254,125 @@ it.layer(NodeServices.layer)("WorkspaceFolders", (it) => {
}),
);

// Opening a FIFO waits in `open()` for a writer, like listing a folder behind a macOS privacy
// prompt, and pins a libuv pool thread that interruption cannot free.
it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
"keeps scanning without using up the libuv pool while a folder's listing never returns",
() =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tmp = yield* makeTempDir;
const root = (name: string) => path.join(tmp, name);
const probe = path.join(tmp, "probe");
yield* fileSystem.writeFileString(probe, "free");
for (const folder of ["home/api/.git", "home/Desktop/notes/.git", "other/web/.git"]) {
yield* fileSystem.makeDirectory(path.join(tmp, folder), { recursive: true });
}
const listings = new Map<string, { gate: string; started: Deferred.Deferred<void> }>();
for (const name of ["home", "work", "spare", "extra"]) {
const gate = path.join(tmp, `${name}.gate`);
yield* fileSystem.makeDirectory(path.join(root(name), "Desktop"), { recursive: true });
NodeChildProcess.execFileSync("mkfifo", [gate]);
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
try {
NodeFS.closeSync(
NodeFS.openSync(gate, NodeFS.constants.O_WRONLY | NodeFS.constants.O_NONBLOCK),
);
} catch {
// ENXIO: no reader is waiting.
}
}),
);
listings.set(path.join(root(name), "Desktop"), {
gate,
started: yield* Deferred.make<void>(),
});
}
const hanging = FileSystem.FileSystem.of({
...fileSystem,
readDirectory: (target, options) => {
const listing = listings.get(target);
return listing === undefined
? fileSystem.readDirectory(target, options)
: Deferred.succeed(listing.started, undefined).pipe(
Effect.andThen(fileSystem.readFileString(listing.gate)),
Effect.as([]),
);
},
});
const discover = (workspaceRoot: string) =>
WorkspaceFolders.discoverFolders(workspaceRoot).pipe(
Effect.map((folders) => folders.map((folder) => folder.path)),
Effect.provideService(FileSystem.FileSystem, hanging),
);
const discoverPastDeadline = Effect.fnUntraced(function* (name: string) {
const scan = yield* Effect.forkChild(discover(root(name)));
yield* Deferred.await(listings.get(path.join(root(name), "Desktop"))!.started);
yield* TestClock.adjust("2 seconds");
return yield* Fiber.join(scan);
});

const home = root("home");
const found = [path.join(home, "Desktop", "notes"), path.join(home, "api")];
assert.deepEqual(
(yield* WorkspaceFolders.discoverFolders(home)).map((folder) => folder.path),
found,
);
// The stuck root keeps what it last found, so its repositories do not drop out meanwhile.
assert.deepEqual(yield* discoverPastDeadline("home"), found);
// Each pass would otherwise pin another thread, and four leave the server unanswered.
for (let pass = 0; pass < 4; pass++) assert.deepEqual(yield* discover(home), found);
assert.deepEqual(yield* discover(root("other")), [path.join(root("other"), "web")]);
// Two stuck listings are the most there can be, however many projects hold one. Other
// roots then list nothing either, and keep what they found.
assert.deepEqual(yield* discoverPastDeadline("work"), []);
assert.deepEqual(yield* discover(root("spare")), []);
assert.deepEqual(yield* discover(root("extra")), []);
assert.deepEqual(yield* discover(root("other")), [path.join(root("other"), "web")]);
assert.equal(yield* fileSystem.readFileString(probe), "free");
}),
);

it.effect("does not count waiting behind a slow listing against the deadline", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tmp = yield* makeTempDir;
const slow = ["a", "b", "c"].map((name) => path.join(tmp, name));
for (const folder of slow) {
yield* fileSystem.makeDirectory(path.join(folder, "repo", ".git"), { recursive: true });
}
const started = yield* Queue.unbounded<string>();
const slowFileSystem = FileSystem.FileSystem.of({
...fileSystem,
readDirectory: (target, options) =>
slow.includes(target)
? Queue.offer(started, target).pipe(
Effect.andThen(Effect.sleep("1 second")),
Effect.andThen(fileSystem.readDirectory(target)),
)
: fileSystem.readDirectory(target, options),
});
const discovering = yield* Effect.forkChild(
WorkspaceFolders.discoverFolders(tmp).pipe(
Effect.map((folders) => folders.map((folder) => folder.path)),
Effect.provideService(FileSystem.FileSystem, slowFileSystem),
),
);
// The listings run one at a time, so the last waits two seconds before its own read starts.
for (const _ of slow) {
yield* Queue.take(started);
yield* TestClock.adjust("1 second");
}
assert.deepEqual(
yield* Fiber.join(discovering),
slow.map((folder) => path.join(folder, "repo")),
);
}),
);

it.effect("keeps the folders someone added when a project holds more than fit", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
Expand Down
121 changes: 104 additions & 17 deletions apps/server/src/workspace/WorkspaceFolders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,17 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import { T3_PROJECT_FILE_NAME } from "@t3tools/contracts";
import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";

import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
import { isWithinRoot } from "./KnownWorkspaces.ts";
Expand Down Expand Up @@ -111,6 +115,80 @@ export const parseGitmodulesPaths = (text: string): ReadonlyArray<string> =>
return normalized === "" ? [] : [normalized];
});

// A listing behind a macOS privacy prompt or a hung mount can pin one of libuv's 4 shared threads
// for good. So listings run one at a time per root and two overall, holding their slots until
// `open()` returns; a root whose read passes the deadline, or every root once both have, lists
// nothing more until it returns. The deadline starts with the read, so queueing never counts.
const LISTING_DEADLINE = "2 seconds";
const MAX_LISTINGS = 2;
const listingSlots = Semaphore.makeUnsafe(MAX_LISTINGS);
let overdueListings = 0;
/** Completes when every slot holds an overdue read; replaced once one returns. */
let saturated = Deferred.makeUnsafe<void>();
const rootListings = new Map<
string,
{
readonly slot: Semaphore.Semaphore;
users: number;
overdue: boolean;
/** Completes when the running read passes the deadline; replaced once it returns. */
stuck: Deferred.Deferred<void>;
}
>();

const listFolder = Effect.fnUntraced(function* (root: string, folder: string) {
const fileSystem = yield* FileSystem.FileSystem;
const entry = rootListings.get(root) ?? {
slot: Semaphore.makeUnsafe(1),
users: 0,
overdue: false,
stuck: Deferred.makeUnsafe<void>(),
};
if (entry.overdue || overdueListings >= MAX_LISTINGS) {
return yield* new Cause.TimeoutError(`Listings for ${root} are overdue.`);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
rootListings.set(root, entry);
entry.users += 1;
const stuck = entry.stuck;
const full = saturated;
const read = Effect.gen(function* () {
const reading = yield* Effect.forkChild(fileSystem.readDirectory(folder));
const early = yield* Fiber.await(reading).pipe(Effect.timeoutOption(LISTING_DEADLINE));
if (Option.isSome(early)) return yield* early.value;
entry.overdue = true;
Deferred.doneUnsafe(entry.stuck, Effect.void);
overdueListings += 1;
if (overdueListings === MAX_LISTINGS) Deferred.doneUnsafe(saturated, Effect.void);
const late = yield* Fiber.await(reading);
if (overdueListings === MAX_LISTINGS) saturated = Deferred.makeUnsafe();
overdueListings -= 1;
entry.overdue = false;
entry.stuck = Deferred.makeUnsafe();
return yield* late;
}).pipe(Effect.uninterruptible);
const listing = yield* entry.slot.withPermit(listingSlots.withPermit(read)).pipe(
Effect.ensuring(
Effect.sync(() => {
entry.users -= 1;
if (entry.users === 0) rootListings.delete(root);
}),
),
Effect.forkDetach,
);
const names = yield* Effect.raceFirst(
Effect.asSome(Fiber.join(listing)),
Effect.as(Effect.raceFirst(Deferred.await(stuck), Deferred.await(full)), Option.none()),
).pipe(Effect.ensuring(Effect.sync(() => listing.interruptUnsafe())));
if (Option.isSome(names)) return names.value;
return yield* new Cause.TimeoutError(`Listing ${folder} took too long.`);
});

// A stuck listing may never return (a privacy prompt nobody can see on a service host), so while a
// root lists nothing, its last discovery stands in rather than dropping its repositories everywhere.
const lastDiscovered = new Map<string, ReadonlyArray<ProjectTrackedFolder>>();
const listingsRefused = (root: string) =>
rootListings.get(root)?.overdue === true || overdueListings >= MAX_LISTINGS;

// Built once per operation: the probes share the caller's file system and path services.
const folderProbes = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
Expand Down Expand Up @@ -139,8 +217,8 @@ const folderProbes = Effect.gen(function* () {
Effect.orElseSucceed(() => false),
);

const childFolders = (folder: string) =>
fileSystem.readDirectory(folder).pipe(
const childFolders = (root: string, folder: string) =>
listFolder(root, folder).pipe(
Effect.orElseSucceed((): ReadonlyArray<string> => []),
Effect.map((names) =>
names
Expand Down Expand Up @@ -193,13 +271,11 @@ const scanFolders = Effect.fn("WorkspaceFolders.scan")(function* (
const root = path.resolve(
expandHomePath(input.workspaceRoot.trim(), yield* HostProcess.HomeDirectory),
);
const names = (yield* fileSystem
.readDirectory(root)
.pipe(
Effect.mapError(
() => new WorkspaceFoldersError({ operation: "scan", detail: `Could not read ${root}.` }),
),
)).toSorted();
const names = (yield* listFolder(root, root).pipe(
Effect.mapError(
() => new WorkspaceFoldersError({ operation: "scan", detail: `Could not read ${root}.` }),
),
)).toSorted();
const codeWorkspaceFile = names.find((name) => name.endsWith(CODE_WORKSPACE_EXTENSION)) ?? null;
const listed =
codeWorkspaceFile === null ? null : yield* readCodeWorkspaceFolders(root, codeWorkspaceFile);
Expand All @@ -213,7 +289,7 @@ const scanFolders = Effect.fn("WorkspaceFolders.scan")(function* (
return Effect.gen(function* () {
if (yield* ownsHistory(folderPath)) return [{ path: folderPath, name: boundedName(name) }];
if (yield* exists(path.join(folderPath, ".git"))) return [];
const nested = yield* Effect.filter(yield* childFolders(folderPath), ownsHistory, {
const nested = yield* Effect.filter(yield* childFolders(root, folderPath), ownsHistory, {
concurrency: DETECTION_CONCURRENCY,
});
return nested.map((nestedPath) => ({
Expand Down Expand Up @@ -293,16 +369,19 @@ export const discoverFolders = Effect.fn("WorkspaceFolders.discover")(function*
).map((entry) => path.resolve(root, entry));
// Everything the scan could find would be dropped, so skip the walk.
if (ignored.some((entry) => isWithinRoot(path, root, entry))) return [];
const isIgnored = (folderPath: string) =>
ignored.some((entry) => folderPath === entry || isWithinRoot(path, folderPath, entry));
// A scan that met a stuck listing missed what lies behind it.
const previous = () =>
listingsRefused(root)
? lastDiscovered.get(root)?.filter((folder) => !isIgnored(folder.path))
: undefined;
// Uncapped: the folders outside the project are dropped below, and must not use up the room.
const scan = yield* scanFolders({ workspaceRoot }, Number.POSITIVE_INFINITY).pipe(Effect.option);
if (Option.isNone(scan)) return [];
if (Option.isNone(scan)) return previous() ?? [];
const realRoot = yield* realPath(root);
const inside = yield* Effect.filter(
scan.value.folders.filter(
(folder) =>
folder.isGitRepository &&
!ignored.some((entry) => folder.path === entry || isWithinRoot(path, folder.path, entry)),
),
scan.value.folders.filter((folder) => folder.isGitRepository && !isIgnored(folder.path)),
// A link to a repository elsewhere is not inside the project, whatever its name says, and a
// worktree a workspace file lists follows another repository.
(folder) =>
Expand All @@ -313,7 +392,15 @@ export const discoverFolders = Effect.fn("WorkspaceFolders.discover")(function*
),
{ concurrency: DETECTION_CONCURRENCY },
);
return inside.map((folder) => ({ path: folder.path, name: folder.name, discovered: true }));
const kept = previous();
if (kept !== undefined) return kept;
const found = inside.map((folder) => ({
path: folder.path,
name: folder.name,
discovered: true,
}));
lastDiscovered.set(root, found);
Comment thread
tomasmach marked this conversation as resolved.
Resolved
return found;
});

/**
Expand Down
Loading