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

WorkspaceSearchIndex.ts

566 lines18.5 KB

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