Open History to see the last commit
1import type { EnvironmentId, ProjectSearchEntriesResult } from "@t3tools/contracts";
2import * as Clock from "effect/Clock";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Fiber from "effect/Fiber";
6import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
7
8export interface ComposerPathSearchEntry {
9 readonly path: string;
10 readonly kind: "file" | "directory";
11 readonly parentPath?: string;
12}
13
14export interface ComposerPathSearchState {
15 readonly entries: ReadonlyArray<ComposerPathSearchEntry>;
16 readonly isPending: boolean;
17 readonly error: string | null;
18}
19
20export interface ComposerPathSearchTarget {
21 readonly environmentId: EnvironmentId | null;
22 readonly cwd: string | null;
23 readonly query: string | null;
24}
25
26export interface ComposerPathSearchClient {
27 readonly searchEntries: (input: {
28 readonly cwd: string;
29 readonly query: string;
30 readonly limit: number;
31 }) => Promise<ProjectSearchEntriesResult>;
32}
33
34interface WatchedEntry {
35 refCount: number;
36 target: ComposerPathSearchTarget & {
37 readonly environmentId: EnvironmentId;
38 readonly cwd: string;
39 };
40 teardown: () => void;
41}
42
43export const EMPTY_COMPOSER_PATH_SEARCH_STATE = Object.freeze<ComposerPathSearchState>({
44 entries: [],
45 isPending: false,
46 error: null,
47});
48
49const PENDING_COMPOSER_PATH_SEARCH_STATE = Object.freeze<ComposerPathSearchState>({
50 entries: [],
51 isPending: true,
52 error: null,
53});
54
55const NOOP: () => void = () => undefined;
56const DEFAULT_DEBOUNCE_MS = 200;
57const DEFAULT_LIMIT = 20;
58
59export const composerPathSearchStateAtom = Atom.family((key: string) =>
60 Atom.make(EMPTY_COMPOSER_PATH_SEARCH_STATE).pipe(
61 Atom.keepAlive,
62 Atom.withLabel(`composer-path-search:${key}`),
63 ),
64);
65
66export const EMPTY_COMPOSER_PATH_SEARCH_ATOM = Atom.make(EMPTY_COMPOSER_PATH_SEARCH_STATE).pipe(
67 Atom.keepAlive,
68 Atom.withLabel("composer-path-search:null"),
69);
70
71export function normalizeComposerPathSearchQuery(query: string | null): string {
72 return query?.trim() ?? "";
73}
74
75export function getComposerPathSearchTargetKey(target: ComposerPathSearchTarget): string | null {
76 const query = normalizeComposerPathSearchQuery(target.query);
77 if (target.environmentId === null || target.cwd === null || query.length === 0) {
78 return null;
79 }
80
81 return `${target.environmentId}:${target.cwd}:${query}`;
82}
83
84function toSearchEntries(
85 entries: ProjectSearchEntriesResult["entries"],
86): ReadonlyArray<ComposerPathSearchEntry> {
87 return entries.map((entry) => ({
88 path: entry.path,
89 kind: entry.kind === "directory" ? "directory" : "file",
90 ...(entry.parentPath !== undefined ? { parentPath: entry.parentPath } : {}),
91 }));
92}
93
94export function createComposerPathSearchManager(config: {
95 readonly getRegistry: () => AtomRegistry.AtomRegistry;
96 readonly getClient: (environmentId: EnvironmentId) => ComposerPathSearchClient | null;
97 readonly subscribeClientChanges?: (listener: () => void) => () => void;
98 readonly debounceMs?: number;
99 readonly limit?: number;
100 readonly staleTimeMs?: number;
101}) {
102 const watched = new Map<string, WatchedEntry>();
103 const versions = new Map<string, number>();
104 const timers = new Map<string, Fiber.Fiber<void, never>>();
105 const lastLoadedAt = new Map<string, number>();
106 const debounceMs = config.debounceMs ?? DEFAULT_DEBOUNCE_MS;
107 const limit = config.limit ?? DEFAULT_LIMIT;
108
109 function bumpVersion(targetKey: string): number {
110 const next = (versions.get(targetKey) ?? 0) + 1;
111 versions.set(targetKey, next);
112 return next;
113 }
114
115 function setState(targetKey: string, state: ComposerPathSearchState): void {
116 config.getRegistry().set(composerPathSearchStateAtom(targetKey), state);
117 }
118
119 function clearTimer(targetKey: string): void {
120 const fiber = timers.get(targetKey);
121 if (fiber) {
122 Effect.runFork(Fiber.interrupt(fiber));
123 timers.delete(targetKey);
124 }
125 }
126
127 function getSnapshot(target: ComposerPathSearchTarget): ComposerPathSearchState {
128 const targetKey = getComposerPathSearchTargetKey(target);
129 return targetKey === null
130 ? EMPTY_COMPOSER_PATH_SEARCH_STATE
131 : config.getRegistry().get(composerPathSearchStateAtom(targetKey));
132 }
133
134 function runSearch(
135 targetKey: string,
136 target: ComposerPathSearchTarget & {
137 readonly environmentId: EnvironmentId;
138 readonly cwd: string;
139 },
140 client: ComposerPathSearchClient,
141 version: number,
142 ): void {
143 void client
144 .searchEntries({
145 cwd: target.cwd,
146 query: normalizeComposerPathSearchQuery(target.query),
147 limit,
148 })
149 .then((result) => {
150 if (versions.get(targetKey) !== version) {
151 return;
152 }
153 setState(targetKey, {
154 entries: toSearchEntries(result.entries),
155 isPending: false,
156 error: null,
157 });
158 lastLoadedAt.set(targetKey, Effect.runSync(Clock.currentTimeMillis));
159 })
160 .catch((error: unknown) => {
161 if (versions.get(targetKey) !== version) {
162 return;
163 }
164 const current = config.getRegistry().get(composerPathSearchStateAtom(targetKey));
165 setState(targetKey, {
166 entries: current.entries,
167 isPending: false,
168 error: error instanceof Error ? error.message : "Failed to search project files.",
169 });
170 });
171 }
172
173 function search(
174 target: ComposerPathSearchTarget,
175 client?: ComposerPathSearchClient,
176 options?: { readonly force?: boolean },
177 ): void {
178 const targetKey = getComposerPathSearchTargetKey(target);
179 if (targetKey === null || target.environmentId === null || target.cwd === null) {
180 return;
181 }
182
183 const resolved = client ?? config.getClient(target.environmentId);
184 if (!resolved) {
185 setState(targetKey, {
186 entries: [],
187 isPending: false,
188 error: "Remote connection is not ready.",
189 });
190 return;
191 }
192
193 const lastLoaded = lastLoadedAt.get(targetKey);
194 if (
195 !options?.force &&
196 lastLoaded !== undefined &&
197 config.staleTimeMs !== undefined &&
198 Effect.runSync(Clock.currentTimeMillis) - lastLoaded < config.staleTimeMs
199 ) {
200 return;
201 }
202
203 const version = bumpVersion(targetKey);
204 clearTimer(targetKey);
205 const current = config.getRegistry().get(composerPathSearchStateAtom(targetKey));
206 setState(
207 targetKey,
208 current.entries.length === 0
209 ? PENDING_COMPOSER_PATH_SEARCH_STATE
210 : { ...current, isPending: true, error: null },
211 );
212
213 const readyTarget = {
214 ...target,
215 environmentId: target.environmentId,
216 cwd: target.cwd,
217 };
218
219 if (debounceMs <= 0) {
220 runSearch(targetKey, readyTarget, resolved, version);
221 return;
222 }
223
224 const fiber = Effect.runFork(
225 Effect.sleep(Duration.millis(debounceMs)).pipe(
226 Effect.andThen(
227 Effect.sync(() => {
228 timers.delete(targetKey);
229 runSearch(targetKey, readyTarget, resolved, version);
230 }),
231 ),
232 ),
233 );
234 timers.set(targetKey, fiber);
235 }
236
237 function watch(target: ComposerPathSearchTarget): () => void {
238 const targetKey = getComposerPathSearchTargetKey(target);
239 if (targetKey === null || target.environmentId === null || target.cwd === null) {
240 return NOOP;
241 }
242
243 const readyTarget = {
244 ...target,
245 environmentId: target.environmentId,
246 cwd: target.cwd,
247 };
248
249 const existing = watched.get(targetKey);
250 if (existing) {
251 existing.refCount += 1;
252 return () => unwatch(targetKey);
253 }
254
255 let currentClient: ComposerPathSearchClient | null = null;
256 const sync = () => {
257 const client = config.getClient(target.environmentId!);
258 if (!client) {
259 currentClient = null;
260 setState(targetKey, {
261 entries: [],
262 isPending: false,
263 error: "Remote connection is not ready.",
264 });
265 return;
266 }
267
268 if (currentClient === client) {
269 return;
270 }
271
272 currentClient = client;
273 search(readyTarget, client);
274 };
275
276 const unsubscribe = config.subscribeClientChanges?.(sync) ?? NOOP;
277 sync();
278
279 watched.set(targetKey, {
280 refCount: 1,
281 target: readyTarget,
282 teardown: () => {
283 unsubscribe();
284 clearTimer(targetKey);
285 bumpVersion(targetKey);
286 },
287 });
288
289 return () => unwatch(targetKey);
290 }
291
292 function unwatch(targetKey: string): void {
293 const entry = watched.get(targetKey);
294 if (!entry) {
295 return;
296 }
297
298 entry.refCount -= 1;
299 if (entry.refCount > 0) {
300 return;
301 }
302
303 entry.teardown();
304 watched.delete(targetKey);
305 }
306
307 function reset(): void {
308 for (const entry of watched.values()) {
309 entry.teardown();
310 }
311 watched.clear();
312 versions.clear();
313 for (const targetKey of timers.keys()) {
314 clearTimer(targetKey);
315 }
316 lastLoadedAt.clear();
317 }
318
319 function invalidate(target?: ComposerPathSearchTarget): void {
320 if (target) {
321 const targetKey = getComposerPathSearchTargetKey(target);
322 if (targetKey === null) {
323 return;
324 }
325 lastLoadedAt.delete(targetKey);
326 const watchedEntry = watched.get(targetKey);
327 if (watchedEntry) {
328 search(watchedEntry.target, undefined, { force: true });
329 }
330 return;
331 }
332
333 lastLoadedAt.clear();
334 for (const watchedEntry of watched.values()) {
335 search(watchedEntry.target, undefined, { force: true });
336 }
337 }
338
339 return {
340 invalidate,
341 getSnapshot,
342 search,
343 watch,
344 reset,
345 };
346}