Open History to see the last commit
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;
30}
31
32export interface ProjectEnrichmentChange {
33 readonly workspaceRoot: string;
34 readonly enrichment: ProjectEnrichment;
35 readonly repositoryIdentityResolved: boolean;
36}
37
38export interface ProjectEnrichmentServiceOptions {
39 readonly cacheCapacity?: number;
40 readonly maxPending?: number;
41 readonly concurrency?: number;
42}
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 });
71}
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 });
78}
79
80interface EnrichmentWorkLane {
81 readonly pendingRoots: Ref.Ref<ReadonlySet<string>>;
82 readonly queue: Queue.Queue<string>;
83}
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 const repositoryIdentityCache = yield* Cache.makeWith(
95 (workspaceRoot: string) => Effect.exit(repositoryIdentityResolver.resolve(workspaceRoot)),
96 {
97 capacity: cacheCapacity,
98 timeToLive: Exit.match({
99 onFailure: () => DEFAULT_FAILURE_TTL,
100 onSuccess: (result) => (Exit.isSuccess(result) ? DEFAULT_SUCCESS_TTL : DEFAULT_FAILURE_TTL),
101 }),
102 },
103 );
104 const faviconCache = yield* Cache.makeWith(
105 (workspaceRoot: string) => Effect.exit(faviconResolver.resolvePath(workspaceRoot)),
106 {
107 capacity: cacheCapacity,
108 timeToLive: Exit.match({
109 onFailure: () => DEFAULT_FAILURE_TTL,
110 onSuccess: (result) => (Exit.isSuccess(result) ? DEFAULT_FAVICON_TTL : DEFAULT_FAILURE_TTL),
111 }),
112 },
113 );
114 const makeWorkLane = Effect.gen(function* () {
115 const pendingRoots = yield* Ref.make<ReadonlySet<string>>(new Set());
116 const queue = yield* Effect.acquireRelease(Queue.dropping<string>(maxPending), (queue) =>
117 Queue.shutdown(queue),
118 );
119 return { pendingRoots, queue } satisfies EnrichmentWorkLane;
120 });
121 const repositoryIdentityLane = yield* makeWorkLane;
122 const faviconLane = yield* makeWorkLane;
123 const changes = yield* Effect.acquireRelease(
124 PubSub.sliding<ProjectEnrichmentChange>(256),
125 (pubsub) => PubSub.shutdown(pubsub),
126 );
127
128 const removePending = (lane: EnrichmentWorkLane, workspaceRoot: string) =>
129 Ref.update(lane.pendingRoots, (current) => {
130 if (!current.has(workspaceRoot)) return current;
131 const next = new Set(current);
132 next.delete(workspaceRoot);
133 return next;
134 });
135
136 const reservePending = (lane: EnrichmentWorkLane, workspaceRoot: string) =>
137 Ref.modify(lane.pendingRoots, (current) => {
138 if (current.has(workspaceRoot) || current.size >= maxPending) {
139 return [false, current] as const;
140 }
141 const next = new Set(current);
142 next.add(workspaceRoot);
143 return [true, next] as const;
144 });
145
146 const logFailure = <A, E>(
147 workspaceRoot: string,
148 field: "repositoryIdentity" | "faviconPath",
149 result: Exit.Exit<A, E>,
150 ) =>
151 Exit.isFailure(result)
152 ? Effect.logWarning("Failed to enrich optional project metadata", {
153 workspaceRoot,
154 field,
155 cause: Cause.pretty(result.cause),
156 })
157 : Effect.void;
158
159 const resolveRepositoryIdentity = Effect.fn("ProjectEnrichmentService.resolveRepositoryIdentity")(
160 function* (workspaceRoot: string) {
161 const repositoryIdentity = yield* Cache.get(repositoryIdentityCache, workspaceRoot);
162 yield* logFailure(workspaceRoot, "repositoryIdentity", repositoryIdentity);
163 const faviconPath = yield* Cache.getSuccess(faviconCache, workspaceRoot);
164 const repositoryIdentityResolved = Exit.isSuccess(repositoryIdentity);
165 yield* PubSub.publish(changes, {
166 workspaceRoot,
167 repositoryIdentityResolved,
168 enrichment: {
169 repositoryIdentity: availableValue(Option.some(repositoryIdentity)),
170 faviconPath: availableValue(faviconPath),
171 repositoryIdentityResolved,
172 },
173 });
174 },
175 );
176
177 const resolveFavicon = Effect.fn("ProjectEnrichmentService.resolveFavicon")(function* (
178 workspaceRoot: string,
179 ) {
180 const faviconPath = yield* Cache.get(faviconCache, workspaceRoot);
181 const isMissingWorkspaceRoot = Option.exists(
182 Exit.findErrorOption(faviconPath),
183 ProjectFaviconResolver.isMissingWorkspaceRoot,
184 );
185 if (isMissingWorkspaceRoot) {
186 return;
187 }
188 yield* logFailure(workspaceRoot, "faviconPath", faviconPath);
189 });
190
191 const startWorkers = (
192 lane: EnrichmentWorkLane,
193 resolve: (workspaceRoot: string) => Effect.Effect<void>,
194 ) => {
195 const worker = Queue.take(lane.queue).pipe(
196 Effect.flatMap((workspaceRoot) =>
197 resolve(workspaceRoot).pipe(Effect.ensuring(removePending(lane, workspaceRoot))),
198 ),
199 Effect.forever,
200 );
201 return Effect.forEach(Array.from({ length: concurrency }), () => Effect.forkScoped(worker), {
202 discard: true,
203 });
204 };
205 yield* Effect.all(
206 [
207 startWorkers(repositoryIdentityLane, resolveRepositoryIdentity),
208 startWorkers(faviconLane, resolveFavicon),
209 ],
210 { concurrency: "unbounded", discard: true },
211 );
212
213 // Every project read lands here; only an actual enqueue gets a span, the resolve workers trace the work.
214 const requestLane = Effect.fnUntraced(function* (
215 lane: EnrichmentWorkLane,
216 workspaceRoot: string,
217 field: "repositoryIdentity" | "faviconPath",
218 ) {
219 if (!(yield* reservePending(lane, workspaceRoot))) return;
220 yield* Effect.gen(function* () {
221 if (!(yield* Queue.offer(lane.queue, workspaceRoot))) {
222 yield* removePending(lane, workspaceRoot);
223 yield* Effect.logWarning("Project metadata enrichment queue is full", {
224 workspaceRoot,
225 field,
226 });
227 }
228 }).pipe(Effect.withSpan("ProjectEnrichmentService.requestLane"));
229 });
230
231 // peek/request/getAvailable run per project on every shell read, inside the caller's span; own spans were ~0ms noise.
232 const peek: ProjectEnrichmentService["Service"]["peek"] = Effect.fnUntraced(
233 function* (workspaceRoot) {
234 const [repositoryIdentity, faviconPath] = yield* Effect.all(
235 [
236 Cache.getSuccess(repositoryIdentityCache, workspaceRoot),
237 Cache.getSuccess(faviconCache, workspaceRoot),
238 ] as const,
239 { concurrency: "unbounded" },
240 );
241 return {
242 repositoryIdentity: availableValue(repositoryIdentity),
243 faviconPath: availableValue(faviconPath),
244 repositoryIdentityResolved: isSuccessfullyResolved(repositoryIdentity),
245 };
246 },
247 );
248
249 const request: ProjectEnrichmentService["Service"]["request"] = Effect.fnUntraced(
250 function* (workspaceRoot) {
251 const [hasRepositoryIdentity, hasFaviconPath] = yield* Effect.all(
252 [Cache.has(repositoryIdentityCache, workspaceRoot), Cache.has(faviconCache, workspaceRoot)],
253 { concurrency: "unbounded" },
254 );
255 yield* Effect.all(
256 [
257 hasRepositoryIdentity
258 ? Effect.void
259 : requestLane(repositoryIdentityLane, workspaceRoot, "repositoryIdentity"),
260 hasFaviconPath ? Effect.void : requestLane(faviconLane, workspaceRoot, "faviconPath"),
261 ],
262 { concurrency: "unbounded", discard: true },
263 );
264 },
265 );
266
267 const getAvailable: ProjectEnrichmentService["Service"]["getAvailable"] = Effect.fnUntraced(
268 function* (workspaceRoot) {
269 const available = yield* peek(workspaceRoot);
270 yield* request(workspaceRoot);
271 return available;
272 },
273 );
274
275 const readRepositoryIdentity: ProjectEnrichmentService["Service"]["readRepositoryIdentity"] =
276 Effect.fn("ProjectEnrichmentService.readRepositoryIdentity")(function* (workspaceRoot) {
277 const resolved = yield* Cache.get(repositoryIdentityCache, workspaceRoot);
278 return Exit.isSuccess(resolved) ? resolved.value : null;
279 });
280
281 const invalidate: ProjectEnrichmentService["Service"]["invalidate"] = Effect.fn(
282 "ProjectEnrichmentService.invalidate",
283 )(function* (workspaceRoots) {
284 yield* Effect.forEach(
285 new Set(workspaceRoots),
286 (workspaceRoot) =>
287 Effect.all(
288 [
289 Cache.invalidate(repositoryIdentityCache, workspaceRoot),
290 Cache.invalidate(faviconCache, workspaceRoot),
291 // The resolver keeps its own misses, which would outlive a clone filling the folder.
292 faviconResolver.invalidate(workspaceRoot),
293 ],
294 { concurrency: "unbounded", discard: true },
295 ),
296 { discard: true },
297 );
298 });
299
300 return ProjectEnrichmentService.of({
301 peek,
302 request,
303 getAvailable,
304 readRepositoryIdentity,
305 invalidate,
306 subscribeChanges: PubSub.subscribe(changes),
307 });
308});
309
310export const layer = Layer.effect(ProjectEnrichmentService, make());