GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(server): a slow file read in the search watcher no longer freezes… · incognitojam/styal@bda03b9

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • apps/server/src/workspace
    • WorkspaceEntries.test.ts
    • WorkspaceFinderThread.ts
    • WorkspaceSearchIndex.test.ts
    • WorkspaceSearchIndex.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

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

Copy file name to clipboardExpand all lines: apps/server/src/workspace/WorkspaceEntries.test.ts
+37-34Lines changed: 37 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
// @effect-diagnostics nodeBuiltinImport:off
22
import * as NodeFSP from "node:fs/promises";
33
import * as NodeServices from "@effect/platform-node/NodeServices";
4-
import { FileFinder } from "@ff-labs/fff-node";
54
import { it, afterEach, describe, expect } from "@effect/vitest";
65
import * as Effect from "effect/Effect";
76
import * as FileSystem from "effect/FileSystem";
@@ -13,6 +12,7 @@ import { vi } from "vite-plus/test";
1312
import * as ServerConfig from "../config.ts";
1413
import * as HostProcess from "@t3tools/shared/HostProcess";
1514
import * as VcsProcess from "../vcs/VcsProcess.ts";
15+
import { WorkspaceFinderOpener } from "./WorkspaceFinderThread.ts";
1616
import * as WorkspaceEntries from "./WorkspaceEntries.ts";
1717
import * as WorkspacePaths from "./WorkspacePaths.ts";
1818

@@ -793,39 +793,42 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => {
793793
let scansOutlastWait = false;
794794
let finders = 0;
795795
let rescans = 0;
796-
const createFinder = FileFinder.create.bind(FileFinder);
797-
vi.spyOn(FileFinder, "create").mockImplementation((options) => {
798-
const created = createFinder(options);
799-
if (created.ok) {
800-
const finder = created.value;
801-
finders += 1;
802-
const scanFiles = finder.scanFiles.bind(finder);
803-
finder.scanFiles = () => {
804-
rescans += 1;
805-
return scanFiles();
806-
};
807-
const waitForIndexReady = finder.waitForIndexReady.bind(finder);
808-
finder.waitForIndexReady = (timeoutMs) =>
809-
scansOutlastWait
810-
? Promise.resolve({ ok: true, value: false })
811-
: waitForIndexReady(timeoutMs);
812-
}
813-
return created;
814-
});
815-
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
816-
const searchNeedle = workspaceEntries.searchContents({
817-
cwd,
818-
query: "needle",
819-
limit: 100,
820-
caseSensitive: true,
821-
wholeWord: false,
822-
useRegex: false,
823-
});
824-
yield* searchNeedle;
825-
826-
scansOutlastWait = true;
827-
yield* workspaceEntries.refresh(cwd);
828-
const result = yield* searchNeedle;
796+
const openFinder = yield* WorkspaceFinderOpener;
797+
const countingOpener: typeof openFinder = async (options) => {
798+
const opened = await openFinder(options);
799+
if (!opened.ok) return opened;
800+
finders += 1;
801+
const call: typeof opened.value.call = (method, ...args) => {
802+
if (method === "scanFiles") rescans += 1;
803+
if (method === "waitForIndexReady" && scansOutlastWait) {
804+
return Promise.resolve({ ok: true, value: false } as never);
805+
}
806+
return opened.value.call(method, ...args);
807+
};
808+
return { ok: true, value: { ...opened.value, call } };
809+
};
810+
const result = yield* Effect.gen(function* () {
811+
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
812+
const searchNeedle = workspaceEntries.searchContents({
813+
cwd,
814+
query: "needle",
815+
limit: 100,
816+
caseSensitive: true,
817+
wholeWord: false,
818+
useRegex: false,
819+
});
820+
yield* searchNeedle;
821+
822+
scansOutlastWait = true;
823+
yield* workspaceEntries.refresh(cwd);
824+
return yield* searchNeedle;
825+
}).pipe(
826+
Effect.provide(
827+
Layer.fresh(WorkspaceEntries.layer).pipe(
828+
Layer.provide(Layer.succeed(WorkspaceFinderOpener, countingOpener)),
829+
),
830+
),
831+
);
829832

830833
expect(result.matches.map((match) => match.path)).toEqual(["src/notes.ts"]);
831834
// The second search ran on the rescanned live finder, not a rebuild.
Collapse file

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

Copy file name to clipboard
+116Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
// @effect-diagnostics nodeBuiltinImport:off -- fff's native calls block their thread, so each finder owns a Node worker.
2+
import * as NodeModule from "node:module";
3+
import * as NodeWorkerThreads from "node:worker_threads";
4+
5+
import type { FileFinder, InitOptions, Result } from "@ff-labs/fff-node";
6+
import * as Context from "effect/Context";
7+
8+
type FinderMethod =
9+
| "destroy"
10+
| "directorySearch"
11+
| "fileSearch"
12+
| "grep"
13+
| "isScanning"
14+
| "mixedSearch"
15+
| "scanFiles"
16+
| "waitForIndexReady";
17+
18+
export interface ThreadedFinder {
19+
readonly call: <M extends FinderMethod>(
20+
method: M,
21+
...args: Parameters<FileFinder[M]>
22+
) => Promise<Awaited<ReturnType<FileFinder[M]>>>;
23+
/** Stops the thread once any native call in flight returns; call `destroy` first. */
24+
readonly close: () => Promise<void>;
25+
}
26+
27+
export type OpenFinder = (options: InitOptions) => Promise<Result<ThreadedFinder>>;
28+
29+
// An inline worker needs no extra build entry, so src, dist, the single executable and Electron all load it.
30+
// Eval workers define a global `__dirname` of ".", which fff-node would use to look for its native library.
31+
const FINDER_WORKER_SOURCE = `
32+
delete globalThis.__dirname;
33+
delete globalThis.__filename;
34+
const { parentPort, workerData } = require("node:worker_threads");
35+
const { FileFinder } = require(workerData.fffEntryPath);
36+
const created = FileFinder.create(workerData.options);
37+
parentPort.postMessage({ created: created.ok ? { ok: true } : created });
38+
if (created.ok) {
39+
const finder = created.value;
40+
parentPort.on("message", async ({ id, method, args }) => {
41+
try {
42+
parentPort.postMessage({ id, value: await finder[method](...args) });
43+
} catch (cause) {
44+
parentPort.postMessage({ id, failed: true, cause });
45+
}
46+
});
47+
}
48+
`;
49+
50+
// Node's watch mode posts its own `watch:require` messages on the same port, so every reply is tagged.
51+
type WorkerMessage =
52+
| { readonly created: Result<undefined> }
53+
| { readonly id: number; readonly value: unknown }
54+
| { readonly id: number; readonly failed: true; readonly cause: unknown };
55+
56+
// fff-node's native library stays external; single-executables require disk packages instead of importing them.
57+
const requireForFff = NodeModule.createRequire(import.meta.url);
58+
const fffEntryPath = requireForFff.resolve("@ff-labs/fff-node");
59+
// ffi-rs crashes the process when the first thread that loaded it exits, so the main thread loads it first.
60+
requireForFff(fffEntryPath);
61+
62+
const openWorkerFinder: OpenFinder = (options) =>
63+
new Promise((resolve, reject) => {
64+
const worker = new NodeWorkerThreads.Worker(FINDER_WORKER_SOURCE, {
65+
eval: true,
66+
workerData: { fffEntryPath, options },
67+
});
68+
worker.unref();
69+
const pending = new Map<
70+
number,
71+
{ readonly resolve: (value: never) => void; readonly reject: (cause: unknown) => void }
72+
>();
73+
let nextId = 0;
74+
let failure: unknown;
75+
const fail = (cause: unknown) => {
76+
failure ??= cause;
77+
reject(failure);
78+
for (const request of pending.values()) request.reject(failure);
79+
pending.clear();
80+
};
81+
worker.on("error", fail);
82+
worker.on("exit", (code) => fail(new Error(`The fff worker exited with code ${code}.`)));
83+
84+
const call: ThreadedFinder["call"] = (method, ...args) =>
85+
new Promise((resolveCall, rejectCall) => {
86+
if (failure !== undefined) {
87+
rejectCall(failure);
88+
return;
89+
}
90+
const id = nextId++;
91+
pending.set(id, { resolve: resolveCall, reject: rejectCall });
92+
worker.postMessage({ id, method, args });
93+
});
94+
95+
worker.on("message", (message: WorkerMessage) => {
96+
if ("created" in message) {
97+
resolve(
98+
message.created.ok
99+
? { ok: true, value: { call, close: () => worker.terminate().then(() => undefined) } }
100+
: message.created,
101+
);
102+
return;
103+
}
104+
const request = pending.get(message.id);
105+
if (!request) return;
106+
pending.delete(message.id);
107+
if ("failed" in message) request.reject(message.cause);
108+
else request.resolve(message.value as never);
109+
});
110+
});
111+
112+
/** Opens fff finders off the server's event loop, where a native call can block for as long as a file read. */
113+
export const WorkspaceFinderOpener = Context.Reference<OpenFinder>(
114+
"t3/workspace/WorkspaceFinderThread/WorkspaceFinderOpener",
115+
{ defaultValue: () => openWorkerFinder },
116+
);
Collapse file

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

Copy file name to clipboardExpand all lines: apps/server/src/workspace/WorkspaceSearchIndex.test.ts
+18-11Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,4 @@
1-
import {
2-
FileFinder,
3-
type FileItem,
4-
type GrepCursor,
5-
type GrepOptions,
6-
type GrepResult,
7-
} from "@ff-labs/fff-node";
1+
import type { FileFinder, FileItem, GrepCursor, GrepOptions, GrepResult } from "@ff-labs/fff-node";
82
import * as NodeServices from "@effect/platform-node/NodeServices";
93
import { afterEach, expect, it } from "@effect/vitest";
104
import * as HostProcess from "@t3tools/shared/HostProcess";
@@ -13,12 +7,23 @@ import * as FileSystem from "effect/FileSystem";
137
import * as Path from "effect/Path";
148
import { vi } from "vite-plus/test";
159

10+
import { WorkspaceFinderOpener } from "./WorkspaceFinderThread.ts";
1611
import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts";
1712

1813
afterEach(() => {
1914
vi.restoreAllMocks();
2015
});
2116

17+
const withInProcessFinder = (finder: FileFinder) =>
18+
Effect.provideService(WorkspaceFinderOpener, async () => ({
19+
ok: true as const,
20+
value: {
21+
call: async (method, ...args) =>
22+
(finder[method] as (...input: typeof args) => never)(...args),
23+
close: async () => undefined,
24+
},
25+
}));
26+
2227
function fileItem(relativePath: string): FileItem {
2328
return {
2429
relativePath,
@@ -53,9 +58,10 @@ it.effect("filters image searches before applying the result limit", () =>
5358
waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
5459
fileSearch,
5560
} as unknown as FileFinder;
56-
vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
5761

58-
const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project");
62+
const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project").pipe(
63+
withInProcessFinder(finder),
64+
);
5965
const resultWithoutKind = yield* searchIndex.search("", 200, undefined, true);
6066
const resultWithDirectoryKind = yield* searchIndex.search("", 200, "directory", true);
6167

@@ -116,9 +122,10 @@ it.effect("continues whole-word searches after a filtered grep page", () =>
116122
waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
117123
grep,
118124
} as unknown as FileFinder;
119-
vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
120125

121-
const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project", "content");
126+
const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project", "content").pipe(
127+
withInProcessFinder(finder),
128+
);
122129
const result = yield* searchIndex.searchContents({
123130
query: "needle",
124131
limit: 1,

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.