Open History to see the last commit
1import { FileFinder, type MixedItem, type MixedSearchResult } from "@ff-labs/fff-node";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as LayerMap from "effect/LayerMap";
6import * as Schedule from "effect/Schedule";
7import * as Schema from "effect/Schema";
8
9import type {
10 ProjectEntry,
11 ProjectListEntriesResult,
12 ProjectSearchEntriesResult,
13} from "@t3tools/contracts";
14
15const WORKSPACE_INDEX_MAX_ENTRIES = 25_000;
16const WORKSPACE_INDEX_PAGE_SIZE = WORKSPACE_INDEX_MAX_ENTRIES + 2;
17const WORKSPACE_INDEX_SCAN_TIMEOUT = "15 seconds";
18const WORKSPACE_INDEX_IDLE_TTL = "15 minutes";
19const WORKSPACE_INDEX_SCAN_POLL_INTERVAL = "50 millis";
20
21export class WorkspaceSearchIndexCreateFailed extends Schema.TaggedErrorClass<WorkspaceSearchIndexCreateFailed>()(
22 "WorkspaceSearchIndexCreateFailed",
23 {
24 cwd: Schema.String,
25 reason: Schema.String,
26 cause: Schema.optional(Schema.Defect()),
27 },
28) {
29 override get message(): string {
30 return `Failed to create the workspace search index for '${this.cwd}'.`;
31 }
32}
33
34export class WorkspaceSearchIndexScanTimedOut extends Schema.TaggedErrorClass<WorkspaceSearchIndexScanTimedOut>()(
35 "WorkspaceSearchIndexScanTimedOut",
36 {
37 cwd: Schema.String,
38 timeout: Schema.String,
39 },
40) {
41 override get message(): string {
42 return `Workspace search index for '${this.cwd}' did not finish scanning within ${this.timeout}`;
43 }
44}
45
46export class WorkspaceSearchIndexSearchFailed extends Schema.TaggedErrorClass<WorkspaceSearchIndexSearchFailed>()(
47 "WorkspaceSearchIndexSearchFailed",
48 {
49 cwd: Schema.String,
50 queryLength: Schema.Number,
51 pageSize: Schema.Number,
52 reason: Schema.String,
53 cause: Schema.optional(Schema.Defect()),
54 },
55) {
56 override get message(): string {
57 return `Workspace search failed for '${this.cwd}'.`;
58 }
59}
60
61export class WorkspaceSearchIndexRefreshFailed extends Schema.TaggedErrorClass<WorkspaceSearchIndexRefreshFailed>()(
62 "WorkspaceSearchIndexRefreshFailed",
63 {
64 cwd: Schema.String,
65 reason: Schema.String,
66 cause: Schema.optional(Schema.Defect()),
67 },
68) {
69 override get message(): string {
70 return `Failed to refresh the workspace search index for '${this.cwd}'.`;
71 }
72}
73
74export class WorkspaceSearchIndexDestroyFailed extends Schema.TaggedErrorClass<WorkspaceSearchIndexDestroyFailed>()(
75 "WorkspaceSearchIndexDestroyFailed",
76 {
77 cwd: Schema.String,
78 cause: Schema.Defect(),
79 },
80) {
81 override get message(): string {
82 return `Failed to destroy the workspace search index for '${this.cwd}'.`;
83 }
84}
85
86export type WorkspaceSearchIndexError =
87 | WorkspaceSearchIndexCreateFailed
88 | WorkspaceSearchIndexScanTimedOut
89 | WorkspaceSearchIndexSearchFailed
90 | WorkspaceSearchIndexRefreshFailed;
91
92export class WorkspaceSearchIndex extends Context.Service<
93 WorkspaceSearchIndex,
94 {
95 readonly list: () => Effect.Effect<ProjectListEntriesResult, WorkspaceSearchIndexSearchFailed>;
96 readonly search: (
97 query: string,
98 limit: number,
99 ) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceSearchIndexSearchFailed>;
100 readonly refresh: () => Effect.Effect<
101 void,
102 WorkspaceSearchIndexRefreshFailed | WorkspaceSearchIndexScanTimedOut
103 >;
104 }
105>()("t3/workspace/WorkspaceSearchIndex") {}
106
107function toPosixPath(input: string): string {
108 return input.replaceAll("\\", "/");
109}
110
111function trimDirectorySeparator(input: string): string {
112 return input.endsWith("/") ? input.slice(0, -1) : input;
113}
114
115function parentPathOf(input: string): string | undefined {
116 const separatorIndex = input.lastIndexOf("/");
117 return separatorIndex === -1 ? undefined : input.slice(0, separatorIndex);
118}
119
120function toProjectEntry(item: MixedItem): ProjectEntry | null {
121 const normalizedPath = trimDirectorySeparator(toPosixPath(item.item.relativePath));
122 if (!normalizedPath) {
123 return null;
124 }
125
126 return {
127 path: normalizedPath,
128 kind: item.type,
129 };
130}
131
132function mapMixedSearchResult(
133 result: MixedSearchResult,
134 limit: number,
135): { readonly entries: ProjectEntry[]; readonly truncated: boolean } {
136 const entries: ProjectEntry[] = [];
137 for (const item of result.items) {
138 const entry = toProjectEntry(item);
139 if (entry) {
140 entries.push(entry);
141 }
142 if (entries.length >= limit) {
143 break;
144 }
145 }
146
147 const rootDirectoryCount = result.items.some(
148 (item) => item.type === "directory" && item.item.relativePath.length === 0,
149 )
150 ? 1
151 : 0;
152 return {
153 entries,
154 truncated: result.totalMatched - rootDirectoryCount > limit,
155 };
156}
157
158function withDirectoryAncestors(entries: ReadonlyArray<ProjectEntry>): ProjectEntry[] {
159 const entryByPath = new Map(entries.map((entry) => [entry.path, entry]));
160 for (const entry of entries) {
161 let parentPath = parentPathOf(entry.path);
162 while (parentPath) {
163 if (!entryByPath.has(parentPath)) {
164 entryByPath.set(parentPath, { path: parentPath, kind: "directory" });
165 }
166 parentPath = parentPathOf(parentPath);
167 }
168 }
169 return [...entryByPath.values()];
170}
171
172const createFinder = Effect.fn("WorkspaceSearchIndex.createFinder")(function* (cwd: string) {
173 const result = yield* Effect.try({
174 try: () =>
175 FileFinder.create({
176 basePath: cwd,
177 disableMmapCache: true,
178 disableContentIndexing: true,
179 aiMode: false,
180 enableFsRootScanning: true,
181 enableHomeDirScanning: true,
182 }),
183 catch: (cause) =>
184 new WorkspaceSearchIndexCreateFailed({
185 cwd,
186 reason: "FileFinder.create threw unexpectedly.",
187 cause,
188 }),
189 });
190 if (result.ok) return result.value;
191 return yield* new WorkspaceSearchIndexCreateFailed({
192 cwd,
193 reason: result.error,
194 });
195});
196
197const waitForScan = <E>(cwd: string, finder: FileFinder, onFailure: (cause: unknown) => E) =>
198 Effect.try({
199 try: () => finder.isScanning(),
200 catch: onFailure,
201 }).pipe(
202 Effect.repeat({
203 while: (scanning) => scanning,
204 schedule: Schedule.spaced(WORKSPACE_INDEX_SCAN_POLL_INTERVAL),
205 }),
206 Effect.timeoutOrElse({
207 duration: WORKSPACE_INDEX_SCAN_TIMEOUT,
208 orElse: () =>
209 new WorkspaceSearchIndexScanTimedOut({ cwd, timeout: WORKSPACE_INDEX_SCAN_TIMEOUT }),
210 }),
211 Effect.withSpan("WorkspaceSearchIndex.waitForScan"),
212 );
213
214export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (cwd: string) {
215 const finder = yield* Effect.acquireRelease(createFinder(cwd), (finder) =>
216 Effect.try({
217 try: () => finder.destroy(),
218 catch: (cause) => new WorkspaceSearchIndexDestroyFailed({ cwd, cause }),
219 }).pipe(Effect.orDie),
220 );
221 yield* waitForScan(
222 cwd,
223 finder,
224 (cause) =>
225 new WorkspaceSearchIndexCreateFailed({
226 cwd,
227 reason: "FileFinder.isScanning threw while creating the index.",
228 cause,
229 }),
230 );
231
232 const runMixedSearch = Effect.fn("WorkspaceSearchIndex.runMixedSearch")(function* (
233 query: string,
234 pageSize: number,
235 ) {
236 const result = yield* Effect.try({
237 try: () => finder.mixedSearch(query, { pageSize }),
238 catch: (cause) =>
239 new WorkspaceSearchIndexSearchFailed({
240 cwd,
241 queryLength: query.length,
242 pageSize,
243 reason: "FileFinder.mixedSearch threw unexpectedly.",
244 cause,
245 }),
246 });
247 if (!result.ok) {
248 return yield* new WorkspaceSearchIndexSearchFailed({
249 cwd,
250 queryLength: query.length,
251 pageSize,
252 reason: result.error,
253 });
254 }
255 return result.value;
256 });
257
258 const refresh: WorkspaceSearchIndex["Service"]["refresh"] = Effect.fn(
259 "WorkspaceSearchIndex.refresh",
260 )(function* () {
261 const result = yield* Effect.try({
262 try: () => finder.scanFiles(),
263 catch: (cause) =>
264 new WorkspaceSearchIndexRefreshFailed({
265 cwd,
266 reason: "FileFinder.scanFiles threw unexpectedly.",
267 cause,
268 }),
269 });
270 if (!result.ok) {
271 return yield* new WorkspaceSearchIndexRefreshFailed({
272 cwd,
273 reason: result.error,
274 });
275 }
276 yield* waitForScan(
277 cwd,
278 finder,
279 (cause) =>
280 new WorkspaceSearchIndexRefreshFailed({
281 cwd,
282 reason: "FileFinder.isScanning threw while refreshing the index.",
283 cause,
284 }),
285 );
286 });
287
288 const list: WorkspaceSearchIndex["Service"]["list"] = Effect.fn("WorkspaceSearchIndex.list")(
289 function* () {
290 const result = yield* runMixedSearch("", WORKSPACE_INDEX_PAGE_SIZE);
291 const mapped = mapMixedSearchResult(result, WORKSPACE_INDEX_MAX_ENTRIES);
292 const sortedEntries = withDirectoryAncestors(mapped.entries).toSorted((left, right) =>
293 left.path.localeCompare(right.path),
294 );
295 const entries = sortedEntries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES);
296 return {
297 entries,
298 truncated: mapped.truncated || entries.length < sortedEntries.length,
299 };
300 },
301 );
302
303 const search: WorkspaceSearchIndex["Service"]["search"] = Effect.fn(
304 "WorkspaceSearchIndex.search",
305 )(function* (query, limit) {
306 const result = yield* runMixedSearch(query, Math.max(1, limit + 1));
307 return mapMixedSearchResult(result, limit);
308 });
309
310 return WorkspaceSearchIndex.of({ list, refresh, search });
311});
312
313/**
314 * A layer factory is required because every index is scoped to a concrete
315 * workspace root. WorkspaceSearchIndexMap owns memoization and idle cleanup;
316 * using a default cwd here would mix resources from different workspaces.
317 */
318export const layer = (cwd: string) => Layer.effect(WorkspaceSearchIndex, make(cwd));
319
320export class WorkspaceSearchIndexMap extends LayerMap.Service<WorkspaceSearchIndexMap>()(
321 "t3/workspace/WorkspaceSearchIndexMap",
322 {
323 lookup: layer,
324 idleTimeToLive: WORKSPACE_INDEX_IDLE_TTL,
325 },
326) {}