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

ProjectEnrichmentService.ts

353 lines12.8 KB

1import type { RepositoryIdentity } from "@t3tools/contracts";
2import * as Cache from "effect/Cache";
3import * as Cause from "effect/Cause";
4import * as Context from "effect/Context";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as Exit from "effect/Exit";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as PubSub from "effect/PubSub";
11import * as Queue from "effect/Queue";
12import * as Ref from "effect/Ref";
13import type * as Scope from "effect/Scope";
14​
15import * as ProjectFaviconResolver from "./ProjectFaviconResolver.ts";
16import * as RepositoryIdentityResolver from "./RepositoryIdentityResolver.ts";
17​
18const DEFAULT_CACHE_CAPACITY = 512;
19const DEFAULT_MAX_PENDING = 512;
20const DEFAULT_CONCURRENCY = 4;
21const DEFAULT_SUCCESS_TTL = Duration.minutes(1);
22// Frequent shell reads scan ~20 files per project; icons change rarely, so cache longer than identities.
23const DEFAULT_FAVICON_TTL = Duration.minutes(15);
24const DEFAULT_FAILURE_TTL = Duration.seconds(5);
25​
26export interface ProjectEnrichment {
27 readonly repositoryIdentity: RepositoryIdentity | null;
28 readonly faviconPath: string | null;
29 readonly repositoryIdentityResolved: boolean;
31​
32export interface ProjectEnrichmentChange {
33 readonly workspaceRoot: string;
34 readonly enrichment: ProjectEnrichment;
35 readonly repositoryIdentityResolved: boolean;
37​
38export interface ProjectEnrichmentServiceOptions {
39 readonly cacheCapacity?: number;
40 readonly maxPending?: number;
41 readonly concurrency?: number;
43​
44export class ProjectEnrichmentService extends Context.Service<
45 ProjectEnrichmentService,
46 {
47 readonly peek: (workspaceRoot: string) => Effect.Effect<ProjectEnrichment>;
48 readonly request: (workspaceRoot: string) => Effect.Effect<void>;
49 readonly getAvailable: (workspaceRoot: string) => Effect.Effect<ProjectEnrichment>;
50 readonly readRepositoryIdentity: (
51 workspaceRoot: string,
52 ) => Effect.Effect<RepositoryIdentity | null>;
53 readonly invalidate: (workspaceRoots: Iterable<string>) => Effect.Effect<void>;
54 readonly subscribeChanges: Effect.Effect<
55 PubSub.Subscription<ProjectEnrichmentChange>,
56 never,
57 Scope.Scope
58 >;
59 }
60>()("t3/project/ProjectEnrichmentService") {}
61​
62function availableValue<A, E>(cached: Option.Option<Exit.Exit<A, E>>): A | null {
63 return Option.match(cached, {
64 onNone: () => null,
65 onSome: (exit) =>
66 Exit.match(exit, {
67 onFailure: () => null,
68 onSuccess: (value) => value,
69 }),
70 });
72​
73function isSuccessfullyResolved<A, E>(cached: Option.Option<Exit.Exit<A, E>>): boolean {
74 return Option.match(cached, {
75 onNone: () => false,
76 onSome: (exit) => Exit.isSuccess(exit),
77 });
79​
80interface EnrichmentWorkLane {
81 readonly pendingRoots: Ref.Ref<ReadonlySet<string>>;
82 readonly queue: Queue.Queue<string>;
84​
85export const make = Effect.fn("ProjectEnrichmentService.make")(function* (
86 options: ProjectEnrichmentServiceOptions = {},
87) {
88 const repositoryIdentityResolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
89 const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
90 const cacheCapacity = Math.max(1, options.cacheCapacity ?? DEFAULT_CACHE_CAPACITY);
91 const maxPending = Math.max(1, options.maxPending ?? DEFAULT_MAX_PENDING);
92 const concurrency = Math.max(1, options.concurrency ?? DEFAULT_CONCURRENCY);
93​
94 // Outlives the cache entry so an expired or refreshing identity still reads as its last value.
95 const lastRepositoryIdentities = new Map<string, RepositoryIdentity>();
96 // `invalidate` drops a root's in-flight lookup so its late result cannot overwrite a newer one.
97 const lookupsInFlight = new Map<string, object>();
98 const rememberRepositoryIdentity = (
99 workspaceRoot: string,
100 repositoryIdentity: RepositoryIdentity | null,
101 ) => {
102 lastRepositoryIdentities.delete(workspaceRoot);
103 if (repositoryIdentity === null) return;
104 if (lastRepositoryIdentities.size >= cacheCapacity) {
105 const oldestRoot = lastRepositoryIdentities.keys().next().value;
106 if (oldestRoot !== undefined) lastRepositoryIdentities.delete(oldestRoot);
107 }
108 lastRepositoryIdentities.set(workspaceRoot, repositoryIdentity);
109 };
110​
111 const repositoryIdentityCache = yield* Cache.makeWith(
112 (workspaceRoot: string) =>
113 Effect.suspend(() => {
114 const lookup = {};
115 lookupsInFlight.set(workspaceRoot, lookup);
116 const isCurrent = () => lookupsInFlight.get(workspaceRoot) === lookup;
117 return Effect.exit(repositoryIdentityResolver.resolve(workspaceRoot)).pipe(
118 Effect.tap((result) =>
119 Effect.sync(() => {
120 if (Exit.isSuccess(result) && isCurrent()) {
121 rememberRepositoryIdentity(workspaceRoot, result.value);
122 }
123 }),
124 ),
125 Effect.ensuring(
126 Effect.sync(() => {
127 if (isCurrent()) lookupsInFlight.delete(workspaceRoot);
128 }),
129 ),
130 );
131 }),
132 {
133 capacity: cacheCapacity,
134 timeToLive: Exit.match({
135 onFailure: () => DEFAULT_FAILURE_TTL,
136 onSuccess: (result) => (Exit.isSuccess(result) ? DEFAULT_SUCCESS_TTL : DEFAULT_FAILURE_TTL),
137 }),
138 },
139 );
140 const faviconCache = yield* Cache.makeWith(
141 (workspaceRoot: string) => Effect.exit(faviconResolver.resolvePath(workspaceRoot)),
142 {
143 capacity: cacheCapacity,
144 timeToLive: Exit.match({
145 onFailure: () => DEFAULT_FAILURE_TTL,
146 onSuccess: (result) => (Exit.isSuccess(result) ? DEFAULT_FAVICON_TTL : DEFAULT_FAILURE_TTL),
147 }),
148 },
149 );
150 const makeWorkLane = Effect.gen(function* () {
151 const pendingRoots = yield* Ref.make<ReadonlySet<string>>(new Set());
152 const queue = yield* Effect.acquireRelease(Queue.dropping<string>(maxPending), (queue) =>
153 Queue.shutdown(queue),
154 );
155 return { pendingRoots, queue } satisfies EnrichmentWorkLane;
156 });
157 const repositoryIdentityLane = yield* makeWorkLane;
158 const faviconLane = yield* makeWorkLane;
159 const changes = yield* Effect.acquireRelease(
160 PubSub.sliding<ProjectEnrichmentChange>(256),
161 (pubsub) => PubSub.shutdown(pubsub),
162 );
163​
164 const removePending = (lane: EnrichmentWorkLane, workspaceRoot: string) =>
165 Ref.update(lane.pendingRoots, (current) => {
166 if (!current.has(workspaceRoot)) return current;
167 const next = new Set(current);
168 next.delete(workspaceRoot);
169 return next;
170 });
171​
172 const reservePending = (lane: EnrichmentWorkLane, workspaceRoot: string) =>
173 Ref.modify(lane.pendingRoots, (current) => {
174 if (current.has(workspaceRoot) || current.size >= maxPending) {
175 return [false, current] as const;
176 }
177 const next = new Set(current);
178 next.add(workspaceRoot);
179 return [true, next] as const;
180 });
181​
182 const logFailure = <A, E>(
183 workspaceRoot: string,
184 field: "repositoryIdentity" | "faviconPath",
185 result: Exit.Exit<A, E>,
186 ) =>
187 Exit.isFailure(result)
188 ? Effect.logWarning("Failed to enrich optional project metadata", {
189 workspaceRoot,
190 field,
191 cause: Cause.pretty(result.cause),
192 })
193 : Effect.void;
194​
195 const resolveRepositoryIdentity = Effect.fn("ProjectEnrichmentService.resolveRepositoryIdentity")(
196 function* (workspaceRoot: string) {
197 const repositoryIdentity = yield* Cache.get(repositoryIdentityCache, workspaceRoot);
198 yield* logFailure(workspaceRoot, "repositoryIdentity", repositoryIdentity);
199 const faviconPath = yield* Cache.getSuccess(faviconCache, workspaceRoot);
200 const repositoryIdentityResolved = Exit.isSuccess(repositoryIdentity);
201 yield* PubSub.publish(changes, {
202 workspaceRoot,
203 repositoryIdentityResolved,
204 enrichment: {
205 repositoryIdentity: availableValue(Option.some(repositoryIdentity)),
206 faviconPath: availableValue(faviconPath),
207 repositoryIdentityResolved,
208 },
209 });
210 },
211 );
212​
213 const resolveFavicon = Effect.fn("ProjectEnrichmentService.resolveFavicon")(function* (
214 workspaceRoot: string,
215 ) {
216 const faviconPath = yield* Cache.get(faviconCache, workspaceRoot);
217 const isMissingWorkspaceRoot = Option.exists(
218 Exit.findErrorOption(faviconPath),
219 ProjectFaviconResolver.isMissingWorkspaceRoot,
220 );
221 if (isMissingWorkspaceRoot) {
222 return;
223 }
224 yield* logFailure(workspaceRoot, "faviconPath", faviconPath);
225 });
226​
227 const startWorkers = (
228 lane: EnrichmentWorkLane,
229 resolve: (workspaceRoot: string) => Effect.Effect<void>,
230 ) => {
231 const worker = Queue.take(lane.queue).pipe(
232 Effect.flatMap((workspaceRoot) =>
233 resolve(workspaceRoot).pipe(Effect.ensuring(removePending(lane, workspaceRoot))),
234 ),
235 Effect.forever,
236 );
237 return Effect.forEach(Array.from({ length: concurrency }), () => Effect.forkScoped(worker), {
238 discard: true,
239 });
240 };
241 yield* Effect.all(
242 [
243 startWorkers(repositoryIdentityLane, resolveRepositoryIdentity),
244 startWorkers(faviconLane, resolveFavicon),
245 ],
246 { concurrency: "unbounded", discard: true },
247 );
248​
249 // Every project read lands here; only an actual enqueue gets a span, the resolve workers trace the work.
250 const requestLane = Effect.fnUntraced(function* (
251 lane: EnrichmentWorkLane,
252 workspaceRoot: string,
253 field: "repositoryIdentity" | "faviconPath",
254 ) {
255 if (!(yield* reservePending(lane, workspaceRoot))) return;
256 yield* Effect.gen(function* () {
257 if (!(yield* Queue.offer(lane.queue, workspaceRoot))) {
258 yield* removePending(lane, workspaceRoot);
259 yield* Effect.logWarning("Project metadata enrichment queue is full", {
260 workspaceRoot,
261 field,
262 });
263 }
264 }).pipe(Effect.withSpan("ProjectEnrichmentService.requestLane"));
265 });
266​
267 // peek/request/getAvailable run per project on every shell read, inside the caller's span; own spans were ~0ms noise.
268 const peek: ProjectEnrichmentService["Service"]["peek"] = Effect.fnUntraced(
269 function* (workspaceRoot) {
270 const [repositoryIdentity, faviconPath] = yield* Effect.all(
271 [
272 Cache.getSuccess(repositoryIdentityCache, workspaceRoot),
273 Cache.getSuccess(faviconCache, workspaceRoot),
274 ] as const,
275 { concurrency: "unbounded" },
276 );
277 const repositoryIdentityResolved = isSuccessfullyResolved(repositoryIdentity);
278 return {
279 repositoryIdentity: repositoryIdentityResolved
280 ? availableValue(repositoryIdentity)
281 : (lastRepositoryIdentities.get(workspaceRoot) ?? null),
282 faviconPath: availableValue(faviconPath),
283 repositoryIdentityResolved,
284 };
285 },
286 );
287​
288 const request: ProjectEnrichmentService["Service"]["request"] = Effect.fnUntraced(
289 function* (workspaceRoot) {
290 const [hasRepositoryIdentity, hasFaviconPath] = yield* Effect.all(
291 [Cache.has(repositoryIdentityCache, workspaceRoot), Cache.has(faviconCache, workspaceRoot)],
292 { concurrency: "unbounded" },
293 );
294 yield* Effect.all(
295 [
296 hasRepositoryIdentity
297 ? Effect.void
298 : requestLane(repositoryIdentityLane, workspaceRoot, "repositoryIdentity"),
299 hasFaviconPath ? Effect.void : requestLane(faviconLane, workspaceRoot, "faviconPath"),
300 ],
301 { concurrency: "unbounded", discard: true },
302 );
303 },
304 );
305​
306 const getAvailable: ProjectEnrichmentService["Service"]["getAvailable"] = Effect.fnUntraced(
307 function* (workspaceRoot) {
308 const available = yield* peek(workspaceRoot);
309 yield* request(workspaceRoot);
310 return available;
311 },
312 );
313​
314 const readRepositoryIdentity: ProjectEnrichmentService["Service"]["readRepositoryIdentity"] =
315 Effect.fn("ProjectEnrichmentService.readRepositoryIdentity")(function* (workspaceRoot) {
316 const resolved = yield* Cache.get(repositoryIdentityCache, workspaceRoot);
317 return Exit.isSuccess(resolved) ? resolved.value : null;
318 });
319​
320 const invalidate: ProjectEnrichmentService["Service"]["invalidate"] = Effect.fn(
321 "ProjectEnrichmentService.invalidate",
322 )(function* (workspaceRoots) {
323 yield* Effect.forEach(
324 new Set(workspaceRoots),
325 (workspaceRoot) =>
326 Effect.all(
327 [
328 Cache.invalidate(repositoryIdentityCache, workspaceRoot),
329 Effect.sync(() => {
330 lookupsInFlight.delete(workspaceRoot);
331 lastRepositoryIdentities.delete(workspaceRoot);
332 }),
333 Cache.invalidate(faviconCache, workspaceRoot),
334 // The resolver keeps its own misses, which would outlive a clone filling the folder.
335 faviconResolver.invalidate(workspaceRoot),
336 ],
337 { concurrency: "unbounded", discard: true },
338 ),
339 { discard: true },
340 );
341 });
342​
343 return ProjectEnrichmentService.of({
344 peek,
345 request,
346 getAvailable,
347 readRepositoryIdentity,
348 invalidate,
349 subscribeChanges: PubSub.subscribe(changes),
350 });
351});
352​
353export const layer = Layer.effect(ProjectEnrichmentService, make());