Open History to see the last commit
1import {
2 FILESYSTEM_METADATA_BATCH_LIMIT,
3 type EnvironmentId,
4 type FilesystemEntryMetadata,
5 type ProjectEntry,
6 type ScopedThreadRef,
7 type ThreadId,
8 WS_METHODS,
9} from "@t3tools/contracts";
10import { normalizeProjectPathForComparison, resolveWorkspaceFilePath } from "@t3tools/shared/path";
11import * as Clock from "effect/Clock";
12import * as Effect from "effect/Effect";
13import * as Exit from "effect/Exit";
14import * as Request from "effect/Request";
15import * as RequestResolver from "effect/RequestResolver";
16import * as SubscriptionRef from "effect/SubscriptionRef";
17import { Atom, AtomRegistry } from "effect/reactivity";
18
19import * as EnvironmentSupervisor from "../connection/supervisor.ts";
20import type { EnvironmentRegistry } from "../connection/registry.ts";
21import {
22 request,
23 type EnvironmentRpcFailure,
24 EnvironmentRpcUnavailableError,
25} from "../rpc/client.ts";
26import type { RpcSession } from "../rpc/session.ts";
27import { createEnvironmentQueryAtomFamily } from "./runtime.ts";
28
29const METADATA_STALE_TIME_MS = 60_000;
30const METADATA_CACHE_LIMIT = 1024;
31
32interface CachedMetadata {
33 value: FilesystemEntryMetadata | null;
34 expires: number;
35}
36
37type RetainedMetadata = Map<string, CachedMetadata>;
38
39interface FileMetadataInput {
40 path: string;
41 threadId?: ThreadId;
42}
43
44class FileMetadataRequest extends Request.Class<
45 {
46 path: string;
47 session: RpcSession;
48 supervisor: EnvironmentSupervisor.EnvironmentSupervisor["Service"];
49 retained?: RetainedMetadata;
50 },
51 FilesystemEntryMetadata | null,
52 EnvironmentRpcFailure<typeof WS_METHODS.filesystemGetMetadata> | EnvironmentRpcUnavailableError
53> {}
54
55export function createFileMetadataAtoms<R, E>(
56 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
57) {
58 const cache = new WeakMap<RpcSession, Map<string, CachedMetadata>>();
59 const invalidationVersions = new WeakMap<RpcSession, number>();
60 const inFlight = new WeakMap<RpcSession, Map<string, Set<{ valid: boolean }>>>();
61 const retainedThreads = new Map<
62 string,
63 { readers: number; sessions: WeakMap<RpcSession, RetainedMetadata> }
64 >();
65 const threadKey = (ref: ScopedThreadRef) => JSON.stringify([ref.environmentId, ref.threadId]);
66 const retainThreadFamily = Atom.family((key: string) =>
67 Atom.make((get) => {
68 let retained = retainedThreads.get(key);
69 if (!retained) {
70 retained = { readers: 0, sessions: new WeakMap() };
71 retainedThreads.set(key, retained);
72 }
73 retained.readers++;
74 get.addFinalizer(() => {
75 if (--retained.readers === 0) retainedThreads.delete(key);
76 });
77 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`file-metadata-thread:${key}`)),
78 );
79 const revisions = Atom.family((key: string) =>
80 Atom.make(0).pipe(Atom.withLabel(`file-metadata-revision:${key}`)),
81 );
82 const revision = (environmentId: EnvironmentId, path: string) =>
83 revisions(JSON.stringify([environmentId, normalizeProjectPathForComparison(path)]));
84 const knownEntry = (session: RpcSession, path: string, now: number) => {
85 const key = normalizeProjectPathForComparison(path);
86 const cached = cache.get(session)?.get(key);
87 return cached && cached.expires > now ? cached : undefined;
88 };
89 const remember = (
90 session: RpcSession,
91 path: string,
92 value: FilesystemEntryMetadata | null,
93 now: number,
94 partial = false,
95 ) => {
96 let entries = cache.get(session);
97 if (!entries) {
98 entries = new Map();
99 cache.set(session, entries);
100 }
101 const key = normalizeProjectPathForComparison(path);
102 entries.delete(key);
103 const entry = { value, expires: now + METADATA_STALE_TIME_MS };
104 entries.set(key, entry);
105 for (const thread of retainedThreads.values()) {
106 const retained = thread.sessions.get(session);
107 const previous = retained?.get(key);
108 if (retained && previous)
109 retained.set(key, {
110 ...entry,
111 value:
112 partial && value && previous.value?.kind === value.kind
113 ? { ...previous.value, ...value }
114 : value,
115 });
116 }
117 if (entries.size > METADATA_CACHE_LIMIT) {
118 const oldest = entries.keys().next().value;
119 if (oldest !== undefined) entries.delete(oldest);
120 }
121 };
122 const resolver = RequestResolver.makeWith<FileMetadataRequest>({
123 batchKey: (entry) => entry.request.session,
124 delay: Effect.yieldNow,
125 collectWhile: (entries) => entries.size < FILESYSTEM_METADATA_BATCH_LIMIT,
126 runAll: Effect.fnUntraced(function* (entries) {
127 const session = entries[0].request.session;
128 let pending = [...entries];
129 while (pending.length > 0) {
130 const paths = [...new Set(pending.map((entry) => entry.request.path))];
131 let requests = inFlight.get(session);
132 if (!requests) {
133 requests = new Map();
134 inFlight.set(session, requests);
135 }
136 const tokens = new Map(paths.map((path) => [path, { valid: true }]));
137 for (const [path, token] of tokens) {
138 let active = requests.get(path);
139 if (!active) requests.set(path, (active = new Set()));
140 active.add(token);
141 }
142 const activeRequests = requests;
143 pending = yield* Effect.gen(function* () {
144 const result = yield* request(WS_METHODS.filesystemGetMetadata, { paths }).pipe(
145 Effect.provideService(
146 EnvironmentSupervisor.EnvironmentSupervisor,
147 entries[0].request.supervisor,
148 ),
149 );
150 const now = yield* Clock.currentTimeMillis;
151 const byPath = new Map(paths.map((path, index) => [path, result.entries[index] ?? null]));
152 const retry: typeof pending = [];
153 for (const entry of pending) {
154 // Retry only paths invalidated during this request. Never retain the
155 // old response or complete a waiting chip with pre-write metadata.
156 if (!tokens.get(entry.request.path)!.valid) {
157 retry.push(entry);
158 continue;
159 }
160 const value = byPath.get(entry.request.path) ?? null;
161 remember(session, entry.request.path, value, now);
162 entry.request.retained?.set(entry.request.path, {
163 value,
164 expires: now + METADATA_STALE_TIME_MS,
165 });
166 entry.completeUnsafe(Exit.succeed(value));
167 }
168 return retry;
169 }).pipe(
170 Effect.ensuring(
171 Effect.sync(() => {
172 for (const [path, token] of tokens) {
173 const active = activeRequests.get(path);
174 active?.delete(token);
175 if (active?.size === 0) activeRequests.delete(path);
176 }
177 }),
178 ),
179 );
180 }
181 }),
182 });
183
184 const metadataFamily = createEnvironmentQueryAtomFamily(runtime, {
185 label: "environment-data:filesystem:metadata",
186 staleTimeMs: METADATA_STALE_TIME_MS,
187 idleTtlMs: METADATA_STALE_TIME_MS,
188 execute: Effect.fnUntraced(function* (input: FileMetadataInput) {
189 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
190 const session = yield* SubscriptionRef.get(supervisor.session);
191 if (session._tag === "None") return null;
192 const thread = input.threadId
193 ? retainedThreads.get(
194 threadKey({ environmentId: supervisor.target.environmentId, threadId: input.threadId }),
195 )
196 : undefined;
197 let retained = thread?.sessions.get(session.value);
198 if (thread && !retained) {
199 retained = new Map();
200 thread.sessions.set(session.value, retained);
201 }
202 const retainedEntry = retained?.get(input.path);
203 if (retainedEntry) return retainedEntry.value;
204 const now = yield* Clock.currentTimeMillis;
205 const cached = knownEntry(session.value, input.path, now);
206 if (cached) {
207 retained?.set(input.path, cached);
208 return cached.value;
209 }
210 return yield* Effect.request(
211 new FileMetadataRequest({
212 path: input.path,
213 session: session.value,
214 supervisor,
215 ...(retained ? { retained } : {}),
216 }),
217 resolver,
218 );
219 }),
220 refreshTrigger: ({
221 environmentId,
222 input,
223 }: {
224 environmentId: EnvironmentId;
225 input: FileMetadataInput;
226 }) => revision(environmentId, input.path),
227 });
228 const metadata = (target: {
229 environmentId: EnvironmentId;
230 input: { path: string; threadId?: ThreadId };
231 }) =>
232 metadataFamily({
233 ...target,
234 input: { ...target.input, path: normalizeProjectPathForComparison(target.input.path) },
235 });
236
237 const rememberEntries = Effect.fnUntraced(function* (
238 cwd: string,
239 entries: ReadonlyArray<ProjectEntry>,
240 isCurrent?: (session: RpcSession) => boolean,
241 ) {
242 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
243 const session = yield* SubscriptionRef.get(supervisor.session);
244 if (session._tag === "None") return;
245 const now = yield* Clock.currentTimeMillis;
246 if (isCurrent && !isCurrent(session.value)) return;
247 for (const entry of entries) {
248 const path = resolveWorkspaceFilePath(entry.path, cwd);
249 const previous = knownEntry(session.value, path, now);
250 if (previous?.value?.kind === entry.kind) continue;
251 remember(session.value, path, { kind: entry.kind }, now, true);
252 }
253 });
254
255 const invalidate = Effect.fnUntraced(function* (path: string) {
256 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
257 const session = yield* SubscriptionRef.get(supervisor.session);
258 if (session._tag === "Some") {
259 invalidationVersions.set(session.value, (invalidationVersions.get(session.value) ?? 0) + 1);
260 const key = normalizeProjectPathForComparison(path);
261 for (const token of inFlight.get(session.value)?.get(key) ?? []) token.valid = false;
262 cache.get(session.value)?.delete(key);
263 for (const thread of retainedThreads.values())
264 thread.sessions.get(session.value)?.delete(normalizeProjectPathForComparison(path));
265 }
266 });
267
268 const rememberFile = Effect.fnUntraced(function* (
269 cwd: string,
270 file: { relativePath: string; byteLength: number },
271 isCurrent?: (session: RpcSession) => boolean,
272 ) {
273 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
274 const session = yield* SubscriptionRef.get(supervisor.session);
275 if (session._tag === "None") return;
276 const path = resolveWorkspaceFilePath(file.relativePath, cwd);
277 const now = yield* Clock.currentTimeMillis;
278 if (isCurrent && !isCurrent(session.value)) return;
279 const previous = knownEntry(session.value, path, now)?.value;
280 remember(
281 session.value,
282 path,
283 {
284 ...previous,
285 kind: "file",
286 byteLength: file.byteLength,
287 },
288 now,
289 true,
290 );
291 });
292
293 const seedAfterRead =
294 /* Metadata seeding runs on every file read and is covered by the read operation. */
295 Effect.fnUntraced(function* <A, ReadError, ReadServices>(
296 read: Effect.Effect<A, ReadError, ReadServices>,
297 seed: (
298 result: A,
299 isCurrent: (session: RpcSession) => boolean,
300 ) => Effect.Effect<void, never, EnvironmentSupervisor.EnvironmentSupervisor>,
301 ) {
302 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
303 const session = yield* SubscriptionRef.get(supervisor.session);
304 const version = session._tag === "Some" ? (invalidationVersions.get(session.value) ?? 0) : 0;
305 const result = yield* read;
306 // Seeding is optional. Any intervening invalidation or reconnect makes
307 // the old response unsuitable for the current metadata cache.
308 yield* seed(
309 result,
310 (current) =>
311 session._tag === "Some" &&
312 current === session.value &&
313 (invalidationVersions.get(current) ?? 0) === version,
314 );
315 return result;
316 });
317
318 const refreshPath = (
319 environmentId: EnvironmentId,
320 path: string,
321 registry: AtomRegistry.AtomRegistry,
322 ) => {
323 const signal = revision(environmentId, path);
324 registry.set(signal, registry.get(signal) + 1);
325 };
326
327 return {
328 metadata,
329 retainThread: (ref: ScopedThreadRef) => retainThreadFamily(threadKey(ref)),
330 rememberEntries,
331 rememberFile,
332 seedAfterRead,
333 invalidate,
334 refreshPath,
335 };
336}