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);
22const DEFAULT_FAILURE_TTL = Duration.seconds(5);
23
24export interface ProjectEnrichment {
25 readonly repositoryIdentity: RepositoryIdentity | null;
26 readonly faviconPath: string | null;
27}
28
29export interface ProjectEnrichmentChange {
30 readonly workspaceRoot: string;
31 readonly enrichment: ProjectEnrichment;
32 readonly repositoryIdentityResolved: boolean;
33}
34
35export interface ProjectEnrichmentServiceOptions {
36 readonly cacheCapacity?: number;
37 /** Maximum active and queued roots for each enrichment field. */
38 readonly maxPending?: number;
39 /** Worker concurrency for each enrichment field. */
40 readonly concurrency?: number;
41 readonly successTtl?: Duration.Input;
42 readonly failureTtl?: Duration.Input;
43}
44
45export class ProjectEnrichmentService extends Context.Service<
46 ProjectEnrichmentService,
47 {
48 /** Read resolved metadata without starting or awaiting filesystem work. */
49 readonly peek: (workspaceRoot: string) => Effect.Effect<ProjectEnrichment>;
50 /** Schedule missing metadata for bounded background resolution. */
51 readonly request: (workspaceRoot: string) => Effect.Effect<void>;
52 /** Read immediately available metadata and schedule anything missing. */
53 readonly getAvailable: (workspaceRoot: string) => Effect.Effect<ProjectEnrichment>;
54 /** Invalidate workspace-derived metadata. */
55 readonly invalidate: (workspaceRoots: Iterable<string>) => Effect.Effect<void>;
56 /** Subscribe to ephemeral completion notifications. */
57 readonly subscribeChanges: Effect.Effect<
58 PubSub.Subscription<ProjectEnrichmentChange>,
59 never,
60 Scope.Scope
61 >;
62 }
63>()("t3/project/ProjectEnrichmentService") {}
64
65function availableValue<A, E>(cached: Option.Option<Exit.Exit<A, E>>): A | null {
66 return Option.match(cached, {
67 onNone: () => null,
68 onSome: (exit) =>
69 Exit.match(exit, {
70 onFailure: () => null,
71 onSuccess: (value) => value,
72 }),
73 });
74}
75
76interface EnrichmentWorkLane {
77 readonly pendingRoots: Ref.Ref<ReadonlySet<string>>;
78 readonly queue: Queue.Queue<string>;
79}
80
81export const make = Effect.fn("ProjectEnrichmentService.make")(function* (
82 options: ProjectEnrichmentServiceOptions = {},
83) {
84 const repositoryIdentityResolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
85 const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
86 const cacheCapacity = Math.max(1, options.cacheCapacity ?? DEFAULT_CACHE_CAPACITY);
87 const maxPending = Math.max(1, options.maxPending ?? DEFAULT_MAX_PENDING);
88 const concurrency = Math.max(1, options.concurrency ?? DEFAULT_CONCURRENCY);
89 const successTtl = options.successTtl ?? DEFAULT_SUCCESS_TTL;
90 const failureTtl = options.failureTtl ?? DEFAULT_FAILURE_TTL;
91
92 const repositoryIdentityCache = yield* Cache.makeWith(
93 (workspaceRoot: string) => Effect.exit(repositoryIdentityResolver.resolve(workspaceRoot)),
94 {
95 capacity: cacheCapacity,
96 timeToLive: Exit.match({
97 onFailure: () => failureTtl,
98 onSuccess: (result) => (Exit.isSuccess(result) ? successTtl : failureTtl),
99 }),
100 },
101 );
102 const faviconCache = yield* Cache.makeWith(
103 (workspaceRoot: string) => Effect.exit(faviconResolver.resolvePath(workspaceRoot)),
104 {
105 capacity: cacheCapacity,
106 timeToLive: Exit.match({
107 onFailure: () => failureTtl,
108 onSuccess: (result) => (Exit.isSuccess(result) ? successTtl : failureTtl),
109 }),
110 },
111 );
112 const makeWorkLane = Effect.gen(function* () {
113 const pendingRoots = yield* Ref.make<ReadonlySet<string>>(new Set());
114 const queue = yield* Effect.acquireRelease(Queue.dropping<string>(maxPending), (queue) =>
115 Queue.shutdown(queue),
116 );
117 return { pendingRoots, queue } satisfies EnrichmentWorkLane;
118 });
119 const repositoryIdentityLane = yield* makeWorkLane;
120 const faviconLane = yield* makeWorkLane;
121 const changes = yield* Effect.acquireRelease(
122 PubSub.sliding<ProjectEnrichmentChange>(256),
123 (pubsub) => PubSub.shutdown(pubsub),
124 );
125
126 const removePending = (lane: EnrichmentWorkLane, workspaceRoot: string) =>
127 Ref.update(lane.pendingRoots, (current) => {
128 if (!current.has(workspaceRoot)) return current;
129 const next = new Set(current);
130 next.delete(workspaceRoot);
131 return next;
132 });
133
134 const reservePending = (lane: EnrichmentWorkLane, workspaceRoot: string) =>
135 Ref.modify(lane.pendingRoots, (current) => {
136 if (current.has(workspaceRoot) || current.size >= maxPending) {
137 return [false, current] as const;
138 }
139 const next = new Set(current);
140 next.add(workspaceRoot);
141 return [true, next] as const;
142 });
143
144 const logFailure = <A, E>(
145 workspaceRoot: string,
146 field: "repositoryIdentity" | "faviconPath",
147 result: Exit.Exit<A, E>,
148 ) =>
149 Exit.isFailure(result)
150 ? Effect.logWarning("Failed to enrich optional project metadata", {
151 workspaceRoot,
152 field,
153 cause: Cause.pretty(result.cause),
154 })
155 : Effect.void;
156
157 const resolveRepositoryIdentity = Effect.fn("ProjectEnrichmentService.resolveRepositoryIdentity")(
158 function* (workspaceRoot: string) {
159 const repositoryIdentity = yield* Cache.get(repositoryIdentityCache, workspaceRoot);
160 yield* logFailure(workspaceRoot, "repositoryIdentity", repositoryIdentity);
161 const faviconPath = yield* Cache.getSuccess(faviconCache, workspaceRoot);
162 yield* PubSub.publish(changes, {
163 workspaceRoot,
164 repositoryIdentityResolved: Exit.isSuccess(repositoryIdentity),
165 enrichment: {
166 repositoryIdentity: availableValue(Option.some(repositoryIdentity)),
167 faviconPath: availableValue(faviconPath),
168 },
169 });
170 },
171 );
172
173 const resolveFavicon = Effect.fn("ProjectEnrichmentService.resolveFavicon")(function* (
174 workspaceRoot: string,
175 ) {
176 const faviconPath = yield* Cache.get(faviconCache, workspaceRoot);
177 yield* logFailure(workspaceRoot, "faviconPath", faviconPath);
178 });
179
180 const startWorkers = (
181 lane: EnrichmentWorkLane,
182 resolve: (workspaceRoot: string) => Effect.Effect<void>,
183 ) => {
184 const worker = Queue.take(lane.queue).pipe(
185 Effect.flatMap((workspaceRoot) =>
186 resolve(workspaceRoot).pipe(Effect.ensuring(removePending(lane, workspaceRoot))),
187 ),
188 Effect.forever,
189 );
190 return Effect.forEach(Array.from({ length: concurrency }), () => Effect.forkScoped(worker), {
191 discard: true,
192 });
193 };
194 yield* Effect.all(
195 [
196 startWorkers(repositoryIdentityLane, resolveRepositoryIdentity),
197 startWorkers(faviconLane, resolveFavicon),
198 ],
199 { concurrency: "unbounded", discard: true },
200 );
201
202 const requestLane = Effect.fn("ProjectEnrichmentService.requestLane")(function* (
203 lane: EnrichmentWorkLane,
204 workspaceRoot: string,
205 field: "repositoryIdentity" | "faviconPath",
206 ) {
207 if (!(yield* reservePending(lane, workspaceRoot))) return;
208 if (!(yield* Queue.offer(lane.queue, workspaceRoot))) {
209 yield* removePending(lane, workspaceRoot);
210 yield* Effect.logWarning("Project metadata enrichment queue is full", {
211 workspaceRoot,
212 field,
213 });
214 }
215 });
216
217 const peek: ProjectEnrichmentService["Service"]["peek"] = Effect.fn(
218 "ProjectEnrichmentService.peek",
219 )(function* (workspaceRoot) {
220 const [repositoryIdentity, faviconPath] = yield* Effect.all(
221 [
222 Cache.getSuccess(repositoryIdentityCache, workspaceRoot),
223 Cache.getSuccess(faviconCache, workspaceRoot),
224 ] as const,
225 { concurrency: "unbounded" },
226 );
227 return {
228 repositoryIdentity: availableValue(repositoryIdentity),
229 faviconPath: availableValue(faviconPath),
230 };
231 });
232
233 const request: ProjectEnrichmentService["Service"]["request"] = Effect.fn(
234 "ProjectEnrichmentService.request",
235 )(function* (workspaceRoot) {
236 const [hasRepositoryIdentity, hasFaviconPath] = yield* Effect.all(
237 [Cache.has(repositoryIdentityCache, workspaceRoot), Cache.has(faviconCache, workspaceRoot)],
238 { concurrency: "unbounded" },
239 );
240 yield* Effect.all(
241 [
242 hasRepositoryIdentity
243 ? Effect.void
244 : requestLane(repositoryIdentityLane, workspaceRoot, "repositoryIdentity"),
245 hasFaviconPath ? Effect.void : requestLane(faviconLane, workspaceRoot, "faviconPath"),
246 ],
247 { concurrency: "unbounded", discard: true },
248 );
249 });
250
251 const getAvailable: ProjectEnrichmentService["Service"]["getAvailable"] = Effect.fn(
252 "ProjectEnrichmentService.getAvailable",
253 )(function* (workspaceRoot) {
254 const available = yield* peek(workspaceRoot);
255 yield* request(workspaceRoot);
256 return available;
257 });
258
259 const invalidate: ProjectEnrichmentService["Service"]["invalidate"] = Effect.fn(
260 "ProjectEnrichmentService.invalidate",
261 )(function* (workspaceRoots) {
262 yield* Effect.forEach(
263 new Set(workspaceRoots),
264 (workspaceRoot) =>
265 Effect.all(
266 [
267 Cache.invalidate(repositoryIdentityCache, workspaceRoot),
268 Cache.invalidate(faviconCache, workspaceRoot),
269 ],
270 { concurrency: "unbounded", discard: true },
271 ),
272 { discard: true },
273 );
274 });
275
276 return ProjectEnrichmentService.of({
277 peek,
278 request,
279 getAvailable,
280 invalidate,
281 subscribeChanges: PubSub.subscribe(changes),
282 });
283});
284
285export const layer = Layer.effect(ProjectEnrichmentService, make());