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

WorkspaceSearchIndex.ts

577 lines19.1 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 { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
29​
30// fff-node stays external to the CLI bundle because it dlopens a native
31// library. A static `import` of an external package is a hard error inside a
32// Node single-executable (only built-ins resolve there), so load it through
33// `require`, which reads from the real filesystem in every runtime.
34const requireForFff = NodeModule.createRequire(import.meta.url);
35const { FileFinder } = requireForFff("@ff-labs/fff-node") as typeof import("@ff-labs/fff-node");
36​
37const WORKSPACE_INDEX_MAX_ENTRIES = 25_000;
38const WORKSPACE_INDEX_PAGE_SIZE = WORKSPACE_INDEX_MAX_ENTRIES + 2;
39const WORKSPACE_INDEX_SCAN_TIMEOUT = "15 seconds";
40const WORKSPACE_INDEX_SCAN_TIMEOUT_MS = 15_000;
41const WORKSPACE_INDEX_IDLE_TTL = "15 minutes";
42const CONTENT_SEARCH_TIME_BUDGET_MS = 250;
43const CONTENT_SEARCH_MAX_MATCHES_PER_FILE = 100;
44​
45export class WorkspaceSearchIndexCreateFailed extends Schema.TaggedError<WorkspaceSearchIndexCreateFailed>()(
46 "WorkspaceSearchIndexCreateFailed",
47 {
48 cwd: Schema.String,
49 reason: Schema.String,
50 cause: Schema.optional(Schema.Defect()),
51 },
52) {
53 override get message(): string {
54 return `Failed to create the workspace search index for '${this.cwd}'.`;
55 }
57​
58export class WorkspaceSearchIndexScanTimedOut extends Schema.TaggedError<WorkspaceSearchIndexScanTimedOut>()(
59 "WorkspaceSearchIndexScanTimedOut",
60 {
61 cwd: Schema.String,
62 timeout: Schema.String,
63 },
64) {
65 override get message(): string {
66 return `Workspace search index for '${this.cwd}' did not finish scanning within ${this.timeout}`;
67 }
69​
70export class WorkspaceSearchIndexSearchFailed extends Schema.TaggedError<WorkspaceSearchIndexSearchFailed>()(
71 "WorkspaceSearchIndexSearchFailed",
72 {
73 cwd: Schema.String,
74 queryLength: Schema.Number,
75 pageSize: Schema.Number,
76 reason: Schema.String,
77 cause: Schema.optional(Schema.Defect()),
78 },
79) {
80 override get message(): string {
81 return `Workspace search failed for '${this.cwd}'.`;
82 }
84​
85export class WorkspaceSearchIndexRefreshFailed extends Schema.TaggedError<WorkspaceSearchIndexRefreshFailed>()(
86 "WorkspaceSearchIndexRefreshFailed",
87 {
88 cwd: Schema.String,
89 reason: Schema.String,
90 cause: Schema.optional(Schema.Defect()),
91 },
92) {
93 override get message(): string {
94 return `Failed to refresh the workspace search index for '${this.cwd}'.`;
95 }
97​
98export class WorkspaceSearchIndexDestroyFailed extends Schema.TaggedError<WorkspaceSearchIndexDestroyFailed>()(
99 "WorkspaceSearchIndexDestroyFailed",
100 {
101 cwd: Schema.String,
102 cause: Schema.Defect(),
103 },
104) {
105 override get message(): string {
106 return `Failed to destroy the workspace search index for '${this.cwd}'.`;
107 }
109​
110export type WorkspaceSearchIndexError =
111 | WorkspaceSearchIndexCreateFailed
112 | WorkspaceSearchIndexScanTimedOut
113 | WorkspaceSearchIndexSearchFailed
114 | WorkspaceSearchIndexRefreshFailed;
115​
116export class WorkspaceSearchIndex extends Context.Service<
117 WorkspaceSearchIndex,
118 {
119 readonly list: () => Effect.Effect<ProjectListEntriesResult, WorkspaceSearchIndexSearchFailed>;
120 readonly search: (
121 query: string,
122 limit: number,
123 kind?: ProjectEntryKind,
124 imageOnly?: boolean,
125 ) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceSearchIndexSearchFailed>;
126 readonly searchContents: (
127 input: Omit<ProjectSearchContentsInput, "cwd">,
128 ) => Effect.Effect<ProjectSearchContentsResult, WorkspaceSearchIndexSearchFailed>;
129 readonly refresh: () => Effect.Effect<
130 void,
131 WorkspaceSearchIndexRefreshFailed | WorkspaceSearchIndexScanTimedOut
132 >;
133 }
134>()("t3/workspace/WorkspaceSearchIndex") {}
135​
136function toPosixPath(input: string): string {
137 return input.replaceAll("\\", "/");
139​
140function trimDirectorySeparator(input: string): string {
141 return input.endsWith("/") ? input.slice(0, -1) : input;
143​
144function parentPathOf(input: string): string | undefined {
145 const separatorIndex = input.lastIndexOf("/");
146 return separatorIndex === -1 ? undefined : input.slice(0, separatorIndex);
148​
149function toProjectEntry(item: MixedItem): ProjectEntry | null {
150 const normalizedPath = trimDirectorySeparator(toPosixPath(item.item.relativePath));
151 if (!normalizedPath) {
152 return null;
153 }
154​
155 return {
156 path: normalizedPath,
157 kind: item.type,
158 };
160​
161function toFileEntry(item: FileItem): ProjectEntry | null {
162 const normalizedPath = trimDirectorySeparator(toPosixPath(item.relativePath));
163 return normalizedPath ? { path: normalizedPath, kind: "file" } : null;
165​
166function toDirectoryEntry(item: DirItem): ProjectEntry | null {
167 const normalizedPath = trimDirectorySeparator(toPosixPath(item.relativePath));
168 return normalizedPath ? { path: normalizedPath, kind: "directory" } : null;
170​
171function mapFileSearchResult(
172 result: SearchResult,
173 limit: number,
174 imageOnly = false,
175): ProjectSearchEntriesResult {
176 const entries = result.items.flatMap((item) => {
177 const entry = toFileEntry(item);
178 return entry && (!imageOnly || isWorkspaceImagePreviewPath(entry.path)) ? [entry] : [];
179 });
180 return {
181 entries: entries.slice(0, limit),
182 truncated: entries.length > limit || result.totalMatched > result.items.length,
183 };
185​
186function mapDirectorySearchResult(
187 result: DirSearchResult,
188 limit: number,
189): ProjectSearchEntriesResult {
190 const entries = result.items.flatMap((item) => {
191 const entry = toDirectoryEntry(item);
192 return entry ? [entry] : [];
193 });
194 const rootDirectoryCount = result.items.some((item) => item.relativePath.length === 0) ? 1 : 0;
195 return {
196 entries: entries.slice(0, limit),
197 truncated: result.totalMatched - rootDirectoryCount > limit,
198 };
200​
201function mapMixedSearchResult(
202 result: MixedSearchResult,
203 limit: number,
204): { readonly entries: ProjectEntry[]; readonly truncated: boolean } {
205 const entries: ProjectEntry[] = [];
206 for (const item of result.items) {
207 const entry = toProjectEntry(item);
208 if (entry) {
209 entries.push(entry);
210 }
211 if (entries.length >= limit) {
212 break;
213 }
214 }
215​
216 const rootDirectoryCount = result.items.some(
217 (item) => item.type === "directory" && item.item.relativePath.length === 0,
218 )
219 ? 1
220 : 0;
221 return {
222 entries,
223 truncated: result.totalMatched - rootDirectoryCount > limit,
224 };
226​
227const WORD_CHARACTER = /[\p{Letter}\p{Mark}\p{Number}_]/u;
228​
229function codePointAt(line: string, index: number): string | undefined {
230 const codePoint = line.codePointAt(index);
231 return codePoint === undefined ? undefined : String.fromCodePoint(codePoint);
233​
234function codePointBefore(line: string, index: number): string | undefined {
235 if (index <= 0) return undefined;
236 const previousCodeUnit = line.charCodeAt(index - 1);
237 const previousIndex =
238 previousCodeUnit >= 0xdc00 && previousCodeUnit <= 0xdfff ? index - 2 : index - 1;
239 return codePointAt(line, previousIndex);
241​
242function buildContentSearchQuery(input: Omit<ProjectSearchContentsInput, "cwd">): {
243 readonly searchQuery: string;
244 readonly regexMode: boolean;
245} {
246 if (input.caseSensitive) {
247 return { searchQuery: input.query, regexMode: input.useRegex };
248 }
249 // Plain mode relies on smart case: an all-lowercase needle matches
250 // case-insensitively. Regex mode needs an explicit inline flag instead.
251 return input.useRegex
252 ? { searchQuery: `(?i)${input.query}`, regexMode: true }
253 : { searchQuery: input.query.toLowerCase(), regexMode: false };
255​
256function mapContentMatchRanges(
257 line: string,
258 byteRanges: ReadonlyArray<readonly [number, number]>,
259): Array<{ readonly start: number; readonly end: number }> {
260 const lineBytes = Buffer.from(line);
261 const toStringIndex = (byteOffset: number) => lineBytes.subarray(0, byteOffset).toString().length;
262 return byteRanges.map(([startByte, endByte]) => ({
263 start: toStringIndex(startByte),
264 end: toStringIndex(endByte),
265 }));
267​
268/**
269 * Whole-word filtering happens after the grep rather than by wrapping the
270 * pattern in boundary regex: consuming boundaries such as `(?:^|\W)` swallow
271 * the separator between adjacent matches and widen the reported ranges, and
272 * `\b` cannot match punctuation-edged queries at all. Matching VS Code, a
273 * match edge is a word boundary when it touches the line edge, the
274 * neighbouring character is not a word character, or the match's own edge
275 * character is not a word character.
276 */
277function isWholeWordRange(
278 line: string,
279 range: { readonly start: number; readonly end: number },
280): boolean {
281 if (range.end <= range.start) return false;
282 const isWord = (character: string | undefined) =>
283 character !== undefined && WORD_CHARACTER.test(character);
284 const leftIsBoundary =
285 range.start === 0 ||
286 !isWord(codePointBefore(line, range.start)) ||
287 !isWord(codePointAt(line, range.start));
288 const rightIsBoundary =
289 range.end >= line.length ||
290 !isWord(codePointAt(line, range.end)) ||
291 !isWord(codePointBefore(line, range.end));
292 return leftIsBoundary && rightIsBoundary;
294​
295function withDirectoryAncestors(entries: ReadonlyArray<ProjectEntry>): ProjectEntry[] {
296 const entryByPath = new Map(entries.map((entry) => [entry.path, entry]));
297 for (const entry of entries) {
298 let parentPath = parentPathOf(entry.path);
299 while (parentPath) {
300 if (!entryByPath.has(parentPath)) {
301 entryByPath.set(parentPath, { path: parentPath, kind: "directory" });
302 }
303 parentPath = parentPathOf(parentPath);
304 }
305 }
306 return [...entryByPath.values()];
308​
309const createFinder = Effect.fn("WorkspaceSearchIndex.createFinder")(function* (
310 cwd: string,
311 variant: WorkspaceSearchIndexVariant,
312) {
313 const result = yield* Effect.try({
314 try: () =>
315 FileFinder.create({
316 basePath: cwd,
317 disableMmapCache: true,
318 // Content indexing costs scan CPU and memory, so only the on-demand
319 // content-search index pays for it; path-only consumers (file tree,
320 // composer path search, file picker) keep the lightweight index.
321 disableContentIndexing: variant !== "content",
322 aiMode: false,
323 enableFsRootScanning: true,
324 enableHomeDirScanning: true,
325 }),
326 catch: (cause) =>
327 new WorkspaceSearchIndexCreateFailed({
328 cwd,
329 reason: "FileFinder.create threw unexpectedly.",
330 cause,
331 }),
332 });
333 if (result.ok) return result.value;
334 return yield* new WorkspaceSearchIndexCreateFailed({
335 cwd,
336 reason: result.error,
337 });
338});
339​
340const waitForIndexReady = Effect.fn("WorkspaceSearchIndex.waitForIndexReady")(function* <E>(
341 cwd: string,
342 finder: FileFinderType,
343 onFailure: (input: { readonly reason: string; readonly cause?: unknown }) => E,
344): Effect.fn.Return<void, E | WorkspaceSearchIndexScanTimedOut> {
345 const result = yield* Effect.tryPromise({
346 try: () => finder.waitForIndexReady(WORKSPACE_INDEX_SCAN_TIMEOUT_MS),
347 catch: (cause) =>
348 onFailure({
349 reason: "FileFinder.waitForIndexReady rejected unexpectedly.",
350 cause,
351 }),
352 });
353 if (!result.ok) {
354 return yield* Effect.fail(onFailure({ reason: result.error }));
355 }
356 if (!result.value) {
357 return yield* new WorkspaceSearchIndexScanTimedOut({
358 cwd,
359 timeout: WORKSPACE_INDEX_SCAN_TIMEOUT,
360 });
361 }
362});
363​
364export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (
365 cwd: string,
366 variant: WorkspaceSearchIndexVariant = "paths",
367) {
368 const finder = yield* Effect.acquireRelease(createFinder(cwd, variant), (finder) =>
369 Effect.try({
370 try: () => finder.destroy(),
371 catch: (cause) => new WorkspaceSearchIndexDestroyFailed({ cwd, cause }),
372 }).pipe(Effect.orDie),
373 );
374 yield* waitForIndexReady(
375 cwd,
376 finder,
377 ({ reason, cause }) =>
378 new WorkspaceSearchIndexCreateFailed({
379 cwd,
380 reason,
381 cause,
382 }),
383 );
384​
385 const runSearch = Effect.fn("WorkspaceSearchIndex.runSearch")(function* <A>(
386 query: string,
387 pageSize: number,
388 operation: "directorySearch" | "fileSearch" | "grep" | "mixedSearch",
389 execute: () => Result<A>,
390 ): Effect.fn.Return<A, WorkspaceSearchIndexSearchFailed> {
391 const result = yield* Effect.try({
392 try: execute,
393 catch: (cause) =>
394 new WorkspaceSearchIndexSearchFailed({
395 cwd,
396 queryLength: query.length,
397 pageSize,
398 reason: `FileFinder.${operation} threw unexpectedly.`,
399 cause,
400 }),
401 });
402 if (!result.ok) {
403 return yield* new WorkspaceSearchIndexSearchFailed({
404 cwd,
405 queryLength: query.length,
406 pageSize,
407 reason: result.error,
408 });
409 }
410 return result.value;
411 });
412​
413 const refresh: WorkspaceSearchIndex["Service"]["refresh"] = Effect.fn(
414 "WorkspaceSearchIndex.refresh",
415 )(function* () {
416 const result = yield* Effect.try({
417 try: () => finder.scanFiles(),
418 catch: (cause) =>
419 new WorkspaceSearchIndexRefreshFailed({
420 cwd,
421 reason: "FileFinder.scanFiles threw unexpectedly.",
422 cause,
423 }),
424 });
425 if (!result.ok) {
426 return yield* new WorkspaceSearchIndexRefreshFailed({
427 cwd,
428 reason: result.error,
429 });
430 }
431 yield* waitForIndexReady(
432 cwd,
433 finder,
434 ({ reason, cause }) =>
435 new WorkspaceSearchIndexRefreshFailed({
436 cwd,
437 reason,
438 cause,
439 }),
440 );
441 });
442​
443 const list: WorkspaceSearchIndex["Service"]["list"] = Effect.fn("WorkspaceSearchIndex.list")(
444 function* () {
445 const result = yield* runSearch("", WORKSPACE_INDEX_PAGE_SIZE, "mixedSearch", () =>
446 finder.mixedSearch("", { pageSize: WORKSPACE_INDEX_PAGE_SIZE }),
447 );
448 const mapped = mapMixedSearchResult(result, WORKSPACE_INDEX_MAX_ENTRIES);
449 const sortedEntries = withDirectoryAncestors(mapped.entries).toSorted((left, right) =>
450 left.path.localeCompare(right.path),
451 );
452 const entries = sortedEntries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES);
453 return {
454 entries,
455 truncated: mapped.truncated || entries.length < sortedEntries.length,
456 };
457 },
458 );
459​
460 const search: WorkspaceSearchIndex["Service"]["search"] = Effect.fn(
461 "WorkspaceSearchIndex.search",
462 )(function* (query, limit, kind, imageOnly) {
463 const pageSize = imageOnly ? WORKSPACE_INDEX_PAGE_SIZE : Math.max(1, limit + 1);
464 if (kind === "file" || imageOnly) {
465 const result = yield* runSearch(query, pageSize, "fileSearch", () =>
466 finder.fileSearch(query, { pageSize }),
467 );
468 return mapFileSearchResult(result, limit, imageOnly);
469 }
470 if (kind === "directory") {
471 const result = yield* runSearch(query, pageSize, "directorySearch", () =>
472 finder.directorySearch(query, { pageSize }),
473 );
474 return mapDirectorySearchResult(result, limit);
475 }
476 const result = yield* runSearch(query, pageSize, "mixedSearch", () =>
477 finder.mixedSearch(query, { pageSize }),
478 );
479 return mapMixedSearchResult(result, limit);
480 });
481​
482 const searchContents: WorkspaceSearchIndex["Service"]["searchContents"] = Effect.fn(
483 "WorkspaceSearchIndex.searchContents",
484 )(function* (input) {
485 const { searchQuery, regexMode } = buildContentSearchQuery(input);
486 const deadline = performance.now() + CONTENT_SEARCH_TIME_BUDGET_MS;
487 // Grep cursors advance by file, so whole-word post-filtering needs enough
488 // raw candidates from the current file before moving to the next one.
489 const rawPageSize = input.wholeWord
490 ? Math.max(input.limit, CONTENT_SEARCH_MAX_MATCHES_PER_FILE)
491 : input.limit;
492 const matches: Array<ProjectSearchContentsResult["matches"][number]> = [];
493 let nextCursor: GrepCursor | null = null;
494 let regexFallbackError: string | undefined;
495​
496 do {
497 const remainingTimeBudgetMs = Math.max(1, Math.ceil(deadline - performance.now()));
498 const result = yield* runSearch(input.query, input.limit, "grep", () =>
499 finder.grep(searchQuery, {
500 mode: regexMode ? "regex" : "plain",
501 smartCase: !input.caseSensitive && !regexMode,
502 // A single dense file must not consume the whole result page.
503 maxMatchesPerFile: Math.min(CONTENT_SEARCH_MAX_MATCHES_PER_FILE, rawPageSize),
504 pageSize: rawPageSize,
505 cursor: nextCursor,
506 timeBudgetMs: remainingTimeBudgetMs,
507 }),
508 );
509​
510 for (const match of result.items) {
511 const matchRanges = mapContentMatchRanges(match.lineContent, match.matchRanges).filter(
512 (range) => !input.wholeWord || isWholeWordRange(match.lineContent, range),
513 );
514 if (matchRanges.length === 0) continue;
515 matches.push({
516 path: toPosixPath(match.relativePath),
517 lineNumber: match.lineNumber,
518 lineContent: match.lineContent,
519 matchRanges,
520 });
521 }
522 nextCursor = result.nextCursor;
523 regexFallbackError ??= result.regexFallbackError;
524 } while (matches.length < input.limit && nextCursor !== null && performance.now() < deadline);
525​
526 return {
527 matches: matches.slice(0, input.limit),
528 truncated: matches.length > input.limit || nextCursor !== null,
529 ...(regexFallbackError !== undefined ? { regexFallbackError } : {}),
530 };
531 });
532​
533 return WorkspaceSearchIndex.of({ list, refresh, search, searchContents });
534});
535​
536export const WORKSPACE_SEARCH_INDEX_VARIANTS = ["paths", "content"] as const;
537export type WorkspaceSearchIndexVariant = (typeof WORKSPACE_SEARCH_INDEX_VARIANTS)[number];
538​
539/**
540 * Composite LayerMap key so the lightweight path index and the on-demand
541 * content-search index of the same workspace are separate resources with
542 * independent lifecycles. "\n" cannot appear in a filesystem path.
543 */
544export const workspaceSearchIndexKey = (cwd: string, variant: WorkspaceSearchIndexVariant) =>
545 `${variant}\n${cwd}`;
546​
547function parseWorkspaceSearchIndexKey(key: string): {
548 readonly cwd: string;
549 readonly variant: WorkspaceSearchIndexVariant;
550} {
551 const separatorIndex = key.indexOf("\n");
552 return {
553 variant: key.slice(0, separatorIndex) as WorkspaceSearchIndexVariant,
554 cwd: key.slice(separatorIndex + 1),
555 };
557​
558/**
559 * A layer factory is required because every index is scoped to a concrete
560 * workspace root and variant. WorkspaceSearchIndexMap owns memoization and
561 * idle cleanup; using a default cwd here would mix resources from different
562 * workspaces.
563 *
564 * @public Service construction is part of the canonical Effect module API.
565 */
566export const layer = (key: string) => {
567 const { cwd, variant } = parseWorkspaceSearchIndexKey(key);
568 return Layer.effect(WorkspaceSearchIndex, make(cwd, variant));
569};
570​
571export class WorkspaceSearchIndexMap extends LayerMap.Service<WorkspaceSearchIndexMap>()(
572 "t3/workspace/WorkspaceSearchIndexMap",
573 {
574 lookup: layer,
575 idleTimeToLive: WORKSPACE_INDEX_IDLE_TTL,
576 },
577) {}