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