Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

WorkspaceSearchIndex.ts

584 lines19.5 KB

1import * as NodeModule from "node:module";
2​
3import type {
4 DirItem,
5 DirSearchResult,
6 FileItem,
7 FileFinder as FileFinderType,
8 GrepCursor,
9 MixedItem,
10 MixedSearchResult,
11 Result,
12 SearchResult,
13} from "@ff-labs/fff-node";
14import * as Context from "effect/Context";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17import * as LayerMap from "effect/LayerMap";
18import * as Schema from "effect/Schema";
19​
20import type {
21 ProjectEntry,
22 ProjectEntryKind,
23 ProjectListEntriesResult,
24 ProjectSearchContentsInput,
25 ProjectSearchContentsResult,
26 ProjectSearchEntriesResult,
27} from "@t3tools/contracts";
28import { isProjectFaviconPath } from "@t3tools/shared/projectFavicon";
29​
30// fff-node's native library stays external; single-executables require disk packages instead of importing them.
31const requireForFff = NodeModule.createRequire(import.meta.url);
32const { FileFinder } = requireForFff("@ff-labs/fff-node") as typeof import("@ff-labs/fff-node");
33​
34const WORKSPACE_INDEX_MAX_ENTRIES = 25_000;
35const WORKSPACE_INDEX_PAGE_SIZE = WORKSPACE_INDEX_MAX_ENTRIES + 2;
36const WORKSPACE_INDEX_SCAN_TIMEOUT = "15 seconds";
37const WORKSPACE_INDEX_SCAN_TIMEOUT_MS = 15_000;
38const WORKSPACE_INDEX_IDLE_TTL = "15 minutes";
39const CONTENT_SEARCH_TIME_BUDGET_MS = 250;
40const CONTENT_SEARCH_MAX_MATCHES_PER_FILE = 100;
41​
42export class WorkspaceSearchIndexCreateFailed extends Schema.TaggedError<WorkspaceSearchIndexCreateFailed>()(
43 "WorkspaceSearchIndexCreateFailed",
44 {
45 cwd: Schema.String,
46 reason: Schema.String,
47 cause: Schema.optional(Schema.Defect()),
48 },
49) {
50 override get message(): string {
51 return `Failed to create the workspace search index for '${this.cwd}'.`;
52 }
54​
55export class WorkspaceSearchIndexScanTimedOut extends Schema.TaggedError<WorkspaceSearchIndexScanTimedOut>()(
56 "WorkspaceSearchIndexScanTimedOut",
57 {
58 cwd: Schema.String,
59 timeout: Schema.String,
60 },
61) {
62 override get message(): string {
63 return `Workspace search index for '${this.cwd}' did not finish scanning within ${this.timeout}`;
64 }
66​
67export class WorkspaceSearchIndexSearchFailed extends Schema.TaggedError<WorkspaceSearchIndexSearchFailed>()(
68 "WorkspaceSearchIndexSearchFailed",
69 {
70 cwd: Schema.String,
71 queryLength: Schema.Number,
72 pageSize: Schema.Number,
73 reason: Schema.String,
74 cause: Schema.optional(Schema.Defect()),
75 },
76) {
77 override get message(): string {
78 return `Workspace search failed for '${this.cwd}'.`;
79 }
81​
82export class WorkspaceSearchIndexRefreshFailed extends Schema.TaggedError<WorkspaceSearchIndexRefreshFailed>()(
83 "WorkspaceSearchIndexRefreshFailed",
84 {
85 cwd: Schema.String,
86 reason: Schema.String,
87 cause: Schema.optional(Schema.Defect()),
88 },
89) {
90 override get message(): string {
91 return `Failed to refresh the workspace search index for '${this.cwd}'.`;
92 }
94​
95export class WorkspaceSearchIndexDestroyFailed extends Schema.TaggedError<WorkspaceSearchIndexDestroyFailed>()(
96 "WorkspaceSearchIndexDestroyFailed",
97 {
98 cwd: Schema.String,
99 cause: Schema.Defect(),
100 },
101) {
102 override get message(): string {
103 return `Failed to destroy the workspace search index for '${this.cwd}'.`;
104 }
106​
107export class WorkspaceSearchIndex extends Context.Service<
108 WorkspaceSearchIndex,
109 {
110 readonly list: () => Effect.Effect<ProjectListEntriesResult, WorkspaceSearchIndexSearchFailed>;
111 readonly search: (
112 query: string,
113 limit: number,
114 kind?: ProjectEntryKind,
115 imageOnly?: boolean,
116 ) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceSearchIndexSearchFailed>;
117 readonly searchContents: (
118 input: Omit<ProjectSearchContentsInput, "cwd">,
119 ) => Effect.Effect<ProjectSearchContentsResult, WorkspaceSearchIndexSearchFailed>;
120 readonly refresh: () => Effect.Effect<void, WorkspaceSearchIndexRefreshFailed>;
121 }
122>()("t3/workspace/WorkspaceSearchIndex") {}
123​
124function toPosixPath(input: string): string {
125 return input.replaceAll("\\", "/");
127​
128function trimDirectorySeparator(input: string): string {
129 return input.endsWith("/") ? input.slice(0, -1) : input;
131​
132function parentPathOf(input: string): string | undefined {
133 const separatorIndex = input.lastIndexOf("/");
134 return separatorIndex === -1 ? undefined : input.slice(0, separatorIndex);
136​
137function toProjectEntry(item: MixedItem): ProjectEntry | null {
138 const normalizedPath = trimDirectorySeparator(toPosixPath(item.item.relativePath));
139 if (!normalizedPath) {
140 return null;
141 }
142​
143 return {
144 path: normalizedPath,
145 kind: item.type,
146 };
148​
149function toFileEntry(item: FileItem): ProjectEntry | null {
150 const normalizedPath = trimDirectorySeparator(toPosixPath(item.relativePath));
151 return normalizedPath ? { path: normalizedPath, kind: "file" } : null;
153​
154function toDirectoryEntry(item: DirItem): ProjectEntry | null {
155 const normalizedPath = trimDirectorySeparator(toPosixPath(item.relativePath));
156 return normalizedPath ? { path: normalizedPath, kind: "directory" } : null;
158​
159function mapFileSearchResult(
160 result: SearchResult,
161 limit: number,
162 imageOnly = false,
163): ProjectSearchEntriesResult {
164 const entries = result.items.flatMap((item) => {
165 const entry = toFileEntry(item);
166 return entry && (!imageOnly || isProjectFaviconPath(entry.path)) ? [entry] : [];
167 });
168 return {
169 entries: entries.slice(0, limit),
170 truncated: entries.length > limit || result.totalMatched > result.items.length,
171 };
173​
174function mapDirectorySearchResult(
175 result: DirSearchResult,
176 limit: number,
177): ProjectSearchEntriesResult {
178 const entries = result.items.flatMap((item) => {
179 const entry = toDirectoryEntry(item);
180 return entry ? [entry] : [];
181 });
182 const rootDirectoryCount = result.items.some((item) => item.relativePath.length === 0) ? 1 : 0;
183 return {
184 entries: entries.slice(0, limit),
185 truncated: result.totalMatched - rootDirectoryCount > limit,
186 };
188​
189function mapMixedSearchResult(
190 result: MixedSearchResult,
191 limit: number,
192): { readonly entries: ProjectEntry[]; readonly truncated: boolean } {
193 const entries: ProjectEntry[] = [];
194 for (const item of result.items) {
195 const entry = toProjectEntry(item);
196 if (entry) {
197 entries.push(entry);
198 }
199 if (entries.length >= limit) {
200 break;
201 }
202 }
203​
204 const rootDirectoryCount = result.items.some(
205 (item) => item.type === "directory" && item.item.relativePath.length === 0,
206 )
207 ? 1
208 : 0;
209 return {
210 entries,
211 truncated: result.totalMatched - rootDirectoryCount > limit,
212 };
214​
215const WORD_CHARACTER = /[\p{Letter}\p{Mark}\p{Number}_]/u;
216​
217function codePointAt(line: string, index: number): string | undefined {
218 const codePoint = line.codePointAt(index);
219 return codePoint === undefined ? undefined : String.fromCodePoint(codePoint);
221​
222function codePointBefore(line: string, index: number): string | undefined {
223 if (index <= 0) return undefined;
224 const previousCodeUnit = line.charCodeAt(index - 1);
225 const previousIndex =
226 previousCodeUnit >= 0xdc00 && previousCodeUnit <= 0xdfff ? index - 2 : index - 1;
227 return codePointAt(line, previousIndex);
229​
230function buildContentSearchQuery(input: Omit<ProjectSearchContentsInput, "cwd">): {
231 readonly searchQuery: string;
232 readonly regexMode: boolean;
233} {
234 if (input.caseSensitive) {
235 return { searchQuery: input.query, regexMode: input.useRegex };
236 }
237 return input.useRegex
238 ? { searchQuery: `(?i)${input.query}`, regexMode: true }
239 : { searchQuery: input.query.toLowerCase(), regexMode: false };
241​
242function mapContentMatchRanges(
243 line: string,
244 byteRanges: ReadonlyArray<readonly [number, number]>,
245): Array<{ readonly start: number; readonly end: number }> {
246 const lineBytes = Buffer.from(line);
247 const toStringIndex = (byteOffset: number) => lineBytes.subarray(0, byteOffset).toString().length;
248 return byteRanges.map(([startByte, endByte]) => ({
249 start: toStringIndex(startByte),
250 end: toStringIndex(endByte),
251 }));
253​
254// Post-filter whole words: consuming boundary regexes swallow adjacent separators and widen ranges; \b misses punctuation edges.
255function isWholeWordRange(
256 line: string,
257 range: { readonly start: number; readonly end: number },
258): boolean {
259 if (range.end <= range.start) return false;
260 const isWord = (character: string | undefined) =>
261 character !== undefined && WORD_CHARACTER.test(character);
262 const leftIsBoundary =
263 range.start === 0 ||
264 !isWord(codePointBefore(line, range.start)) ||
265 !isWord(codePointAt(line, range.start));
266 const rightIsBoundary =
267 range.end >= line.length ||
268 !isWord(codePointAt(line, range.end)) ||
269 !isWord(codePointBefore(line, range.end));
270 return leftIsBoundary && rightIsBoundary;
272​
273function withDirectoryAncestors(entries: ReadonlyArray<ProjectEntry>): ProjectEntry[] {
274 const entryByPath = new Map(entries.map((entry) => [entry.path, entry]));
275 for (const entry of entries) {
276 let parentPath = parentPathOf(entry.path);
277 while (parentPath) {
278 if (!entryByPath.has(parentPath)) {
279 entryByPath.set(parentPath, { path: parentPath, kind: "directory" });
280 }
281 parentPath = parentPathOf(parentPath);
282 }
283 }
284 return [...entryByPath.values()];
286​
287const createFinder = Effect.fn("WorkspaceSearchIndex.createFinder")(function* (
288 cwd: string,
289 variant: WorkspaceSearchIndexVariant,
290) {
291 const result = yield* Effect.try({
292 try: () =>
293 FileFinder.create({
294 basePath: cwd,
295 disableMmapCache: true,
296 // Content indexing costs CPU/memory; path-only consumers use the lightweight index.
297 disableContentIndexing: variant !== "content",
298 aiMode: false,
299 }),
300 catch: (cause) =>
301 new WorkspaceSearchIndexCreateFailed({
302 cwd,
303 reason: "FileFinder.create threw unexpectedly.",
304 cause,
305 }),
306 });
307 if (result.ok) return result.value;
308 return yield* new WorkspaceSearchIndexCreateFailed({
309 cwd,
310 reason: result.error,
311 });
312});
313​
314const waitForIndexReady = Effect.fn("WorkspaceSearchIndex.waitForIndexReady")(function* <E>(
315 cwd: string,
316 finder: FileFinderType,
317 onFailure: (input: { readonly reason: string; readonly cause?: unknown }) => E,
318): Effect.fn.Return<void, E | WorkspaceSearchIndexScanTimedOut> {
319 const result = yield* Effect.tryPromise({
320 try: () => finder.waitForIndexReady(WORKSPACE_INDEX_SCAN_TIMEOUT_MS),
321 catch: (cause) =>
322 onFailure({
323 reason: "FileFinder.waitForIndexReady rejected unexpectedly.",
324 cause,
325 }),
326 });
327 if (!result.ok) {
328 return yield* Effect.fail(onFailure({ reason: result.error }));
329 }
330 if (!result.value) {
331 return yield* new WorkspaceSearchIndexScanTimedOut({
332 cwd,
333 timeout: WORKSPACE_INDEX_SCAN_TIMEOUT,
334 });
335 }
336});
337​
338export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (
339 cwd: string,
340 variant: WorkspaceSearchIndexVariant = "paths",
341) {
342 const finder = yield* Effect.acquireRelease(createFinder(cwd, variant), (finder) =>
343 Effect.try({
344 try: () => finder.destroy(),
345 catch: (cause) => new WorkspaceSearchIndexDestroyFailed({ cwd, cause }),
346 }).pipe(Effect.orDie),
347 );
348 let initialScanTimedOut = false;
349 yield* waitForIndexReady(
350 cwd,
351 finder,
352 ({ reason, cause }) =>
353 new WorkspaceSearchIndexCreateFailed({
354 cwd,
355 reason,
356 cause,
357 }),
358 ).pipe(
359 Effect.catchTags({
360 WorkspaceSearchIndexScanTimedOut: (error) =>
361 variant === "paths"
362 ? Effect.sync(() => {
363 initialScanTimedOut = true;
364 })
365 : Effect.fail(error),
366 }),
367 );
368​
369 const hasIncompleteInitialScan = () => initialScanTimedOut && finder.isScanning();
370​
371 const runSearch = Effect.fn("WorkspaceSearchIndex.runSearch")(function* <A>(
372 query: string,
373 pageSize: number,
374 operation: "directorySearch" | "fileSearch" | "grep" | "mixedSearch",
375 execute: () => Result<A>,
376 ): Effect.fn.Return<A, WorkspaceSearchIndexSearchFailed> {
377 const result = yield* Effect.try({
378 try: execute,
379 catch: (cause) =>
380 new WorkspaceSearchIndexSearchFailed({
381 cwd,
382 queryLength: query.length,
383 pageSize,
384 reason: `FileFinder.${operation} threw unexpectedly.`,
385 cause,
386 }),
387 });
388 if (!result.ok) {
389 return yield* new WorkspaceSearchIndexSearchFailed({
390 cwd,
391 queryLength: query.length,
392 pageSize,
393 reason: result.error,
394 });
395 }
396 return result.value;
397 });
398​
399 const refresh: WorkspaceSearchIndex["Service"]["refresh"] = Effect.fn(
400 "WorkspaceSearchIndex.refresh",
401 )(function* () {
402 // scanFiles waits on fff's picker lock, which its watcher can hold for seconds.
403 const result = yield* Effect.tryPromise({
404 try: () => finder.scanFilesAsync(),
405 catch: (cause) =>
406 new WorkspaceSearchIndexRefreshFailed({
407 cwd,
408 reason: "FileFinder.scanFilesAsync rejected unexpectedly.",
409 cause,
410 }),
411 });
412 if (!result.ok) {
413 return yield* new WorkspaceSearchIndexRefreshFailed({
414 cwd,
415 reason: result.error,
416 });
417 }
418 // A rescan that outlasts the wait keeps running, and the finder answers
419 // from its previous index until it finishes, so the index stays usable.
420 yield* waitForIndexReady(
421 cwd,
422 finder,
423 ({ reason, cause }) =>
424 new WorkspaceSearchIndexRefreshFailed({
425 cwd,
426 reason,
427 cause,
428 }),
429 ).pipe(Effect.catchTags({ WorkspaceSearchIndexScanTimedOut: () => Effect.void }));
430 });
431​
432 const list: WorkspaceSearchIndex["Service"]["list"] = Effect.fn("WorkspaceSearchIndex.list")(
433 function* () {
434 const incompleteBeforeQuery = hasIncompleteInitialScan();
435 const result = yield* runSearch("", WORKSPACE_INDEX_PAGE_SIZE, "mixedSearch", () =>
436 finder.mixedSearch("", { pageSize: WORKSPACE_INDEX_PAGE_SIZE }),
437 );
438 const mapped = mapMixedSearchResult(result, WORKSPACE_INDEX_MAX_ENTRIES);
439 const sortedEntries = withDirectoryAncestors(mapped.entries).toSorted((left, right) =>
440 left.path.localeCompare(right.path),
441 );
442 const entries = sortedEntries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES);
443 return {
444 entries,
445 truncated:
446 incompleteBeforeQuery || mapped.truncated || entries.length < sortedEntries.length,
447 };
448 },
449 );
450​
451 const searchNames = Effect.fn("WorkspaceSearchIndex.searchNames")(function* (
452 query: string,
453 limit: number,
454 kind: ProjectEntryKind | undefined,
455 imageOnly: boolean | undefined,
456 ) {
457 const pageSize = imageOnly ? WORKSPACE_INDEX_PAGE_SIZE : Math.max(1, limit + 1);
458 if (kind === "file" || imageOnly) {
459 const result = yield* runSearch(query, pageSize, "fileSearch", () =>
460 finder.fileSearch(query, { pageSize }),
461 );
462 return mapFileSearchResult(result, limit, imageOnly);
463 }
464 if (kind === "directory") {
465 const result = yield* runSearch(query, pageSize, "directorySearch", () =>
466 finder.directorySearch(query, { pageSize }),
467 );
468 return mapDirectorySearchResult(result, limit);
469 }
470 const result = yield* runSearch(query, pageSize, "mixedSearch", () =>
471 finder.mixedSearch(query, { pageSize }),
472 );
473 return mapMixedSearchResult(result, limit);
474 });
475​
476 const search: WorkspaceSearchIndex["Service"]["search"] = Effect.fn(
477 "WorkspaceSearchIndex.search",
478 )(function* (rawQuery, limit, kind, imageOnly) {
479 // fff parses any word containing "[" or "{" as a glob and has no escape for them; fuzzy
480 // matching is subsequence-based, so dropping them still matches "[id]" and "a{b}" paths.
481 // "{" is dropped only when the query finds nothing as a glob, so "*.{ts,tsx}" keeps working.
482 const query = rawQuery.replaceAll("[", "");
483 const incompleteBeforeQuery = hasIncompleteInitialScan();
484 let mapped = yield* searchNames(query, limit, kind, imageOnly);
485 if (mapped.entries.length === 0 && query.includes("{")) {
486 mapped = yield* searchNames(query.replaceAll("{", ""), limit, kind, imageOnly);
487 }
488 return { ...mapped, truncated: incompleteBeforeQuery || mapped.truncated };
489 });
490​
491 const searchContents: WorkspaceSearchIndex["Service"]["searchContents"] = Effect.fn(
492 "WorkspaceSearchIndex.searchContents",
493 )(function* (input) {
494 let { searchQuery, regexMode } = buildContentSearchQuery(input);
495 const deadline = performance.now() + CONTENT_SEARCH_TIME_BUDGET_MS;
496 // Grep cursors advance per file; whole-word filtering needs enough raw candidates before advancing.
497 const rawPageSize = input.wholeWord
498 ? Math.max(input.limit, CONTENT_SEARCH_MAX_MATCHES_PER_FILE)
499 : input.limit;
500 const matches: Array<ProjectSearchContentsResult["matches"][number]> = [];
501 let nextCursor: GrepCursor | null = null;
502 let regexFallbackError: string | undefined;
503 let retryLiterally = false;
504​
505 do {
506 const remainingTimeBudgetMs = Math.max(1, Math.ceil(deadline - performance.now()));
507 const result = yield* runSearch(input.query, input.limit, "grep", () =>
508 finder.grep(searchQuery, {
509 mode: regexMode ? "regex" : "plain",
510 smartCase: !input.caseSensitive && !regexMode,
511 maxMatchesPerFile: Math.min(CONTENT_SEARCH_MAX_MATCHES_PER_FILE, rawPageSize),
512 pageSize: rawPageSize,
513 cursor: nextCursor,
514 timeBudgetMs: remainingTimeBudgetMs,
515 }),
516 );
517 // fff searches an invalid pattern as a literal, which would keep the `(?i)` prefix.
518 retryLiterally = regexMode && !input.caseSensitive && result.regexFallbackError !== undefined;
519 if (retryLiterally) {
520 regexFallbackError = result.regexFallbackError;
521 ({ searchQuery, regexMode } = buildContentSearchQuery({ ...input, useRegex: false }));
522 continue;
523 }
524​
525 for (const match of result.items) {
526 const matchRanges = mapContentMatchRanges(match.lineContent, match.matchRanges).filter(
527 (range) => !input.wholeWord || isWholeWordRange(match.lineContent, range),
528 );
529 // fff reports hits past its 512-char lineContent cap with no ranges, so whole words can't be verified there.
530 if (input.wholeWord && matchRanges.length === 0) continue;
531 matches.push({
532 path: toPosixPath(match.relativePath),
533 lineNumber: match.lineNumber,
534 lineContent: match.lineContent,
535 matchRanges,
536 });
537 }
538 nextCursor = result.nextCursor;
539 regexFallbackError ??= result.regexFallbackError;
540 } while (
541 retryLiterally ||
542 (matches.length < input.limit && nextCursor !== null && performance.now() < deadline)
543 );
544​
545 return {
546 matches: matches.slice(0, input.limit),
547 truncated: matches.length > input.limit || nextCursor !== null,
548 ...(regexFallbackError !== undefined ? { regexFallbackError } : {}),
549 };
550 });
551​
552 return WorkspaceSearchIndex.of({ list, refresh, search, searchContents });
553});
554​
555export const WORKSPACE_SEARCH_INDEX_VARIANTS = ["paths", "content"] as const;
556export type WorkspaceSearchIndexVariant = (typeof WORKSPACE_SEARCH_INDEX_VARIANTS)[number];
557​
558export const workspaceSearchIndexKey = (cwd: string, variant: WorkspaceSearchIndexVariant) =>
559 `${variant}\n${cwd}`;
560​
561function parseWorkspaceSearchIndexKey(key: string): {
562 readonly cwd: string;
563 readonly variant: WorkspaceSearchIndexVariant;
564} {
565 const separatorIndex = key.indexOf("\n");
566 return {
567 variant: key.slice(0, separatorIndex) as WorkspaceSearchIndexVariant,
568 cwd: key.slice(separatorIndex + 1),
569 };
571​
572/** @public */
573export const layer = (key: string) => {
574 const { cwd, variant } = parseWorkspaceSearchIndexKey(key);
575 return Layer.effect(WorkspaceSearchIndex, make(cwd, variant));
576};
577​
578export class WorkspaceSearchIndexMap extends LayerMap.Service<WorkspaceSearchIndexMap>()(
579 "t3/workspace/WorkspaceSearchIndexMap",
580 {
581 lookup: layer,
582 idleTimeToLive: WORKSPACE_INDEX_IDLE_TTL,
583 },
584) {}