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

ProjectEnrichmentService.ts

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