GeezerVison is showing github.com — fix(server): a slow file read in the search watcher no longer freezes… · incognitojam/styal@bda03b9
File treeExpand file treeCollapse file tree Open diff view settings apps/server/src/workspace
Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: apps/server/src/workspace/WorkspaceEntries.test.ts +37-34Lines changed: 37 additions & 34 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 1 | 1 | // @effect-diagnostics nodeBuiltinImport:off | 2 | 2 | import * as NodeFSP from "node:fs/promises"; | 3 | 3 | import * as NodeServices from "@effect/platform-node/NodeServices"; | 4 | | -import { FileFinder } from "@ff-labs/fff-node"; | 5 | 4 | import { it, afterEach, describe, expect } from "@effect/vitest"; | 6 | 5 | import * as Effect from "effect/Effect"; | 7 | 6 | import * as FileSystem from "effect/FileSystem"; | @@ -13,6 +12,7 @@ import { vi } from "vite-plus/test"; | 13 | 12 | import * as ServerConfig from "../config.ts"; | 14 | 13 | import * as HostProcess from "@t3tools/shared/HostProcess"; | 15 | 14 | import * as VcsProcess from "../vcs/VcsProcess.ts"; | | 15 | +import { WorkspaceFinderOpener } from "./WorkspaceFinderThread.ts"; | 16 | 16 | import * as WorkspaceEntries from "./WorkspaceEntries.ts"; | 17 | 17 | import * as WorkspacePaths from "./WorkspacePaths.ts"; | 18 | 18 |
| @@ -793,39 +793,42 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { | 793 | 793 | let scansOutlastWait = false; | 794 | 794 | let finders = 0; | 795 | 795 | 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 | + ); | 829 | 832 |
| 830 | 833 | expect(result.matches.map((match) => match.path)).toEqual(["src/notes.ts"]); | 831 | 834 | // The second search ran on the rescanned live finder, not a rebuild. | |
Collapse file Copy file name to clipboard +116Lines changed: 116 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 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 Copy file name to clipboardExpand all lines: apps/server/src/workspace/WorkspaceSearchIndex.test.ts +18-11Lines changed: 18 additions & 11 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 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"; | 8 | 2 | import * as NodeServices from "@effect/platform-node/NodeServices"; | 9 | 3 | import { afterEach, expect, it } from "@effect/vitest"; | 10 | 4 | import * as HostProcess from "@t3tools/shared/HostProcess"; | @@ -13,12 +7,23 @@ import * as FileSystem from "effect/FileSystem"; | 13 | 7 | import * as Path from "effect/Path"; | 14 | 8 | import { vi } from "vite-plus/test"; | 15 | 9 |
| | 10 | +import { WorkspaceFinderOpener } from "./WorkspaceFinderThread.ts"; | 16 | 11 | import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts"; | 17 | 12 |
| 18 | 13 | afterEach(() => { | 19 | 14 | vi.restoreAllMocks(); | 20 | 15 | }); | 21 | 16 |
| | 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 | + | 22 | 27 | function fileItem(relativePath: string): FileItem { | 23 | 28 | return { | 24 | 29 | relativePath, | @@ -53,9 +58,10 @@ it.effect("filters image searches before applying the result limit", () => | 53 | 58 | waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), | 54 | 59 | fileSearch, | 55 | 60 | } as unknown as FileFinder; | 56 | | - vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder }); | 57 | 61 |
| 58 | | - const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project"); | | 62 | + const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project").pipe( | | 63 | + withInProcessFinder(finder), | | 64 | + ); | 59 | 65 | const resultWithoutKind = yield* searchIndex.search("", 200, undefined, true); | 60 | 66 | const resultWithDirectoryKind = yield* searchIndex.search("", 200, "directory", true); | 61 | 67 |
| @@ -116,9 +122,10 @@ it.effect("continues whole-word searches after a filtered grep page", () => | 116 | 122 | waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), | 117 | 123 | grep, | 118 | 124 | } as unknown as FileFinder; | 119 | | - vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder }); | 120 | 125 |
| 121 | | - const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project", "content"); | | 126 | + const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project", "content").pipe( | | 127 | + withInProcessFinder(finder), | | 128 | + ); | 122 | 129 | const result = yield* searchIndex.searchContents({ | 123 | 130 | query: "needle", | 124 | 131 | limit: 1, | |
|