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

ProjectEnrichmentService.ts

306 lines10.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 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 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 readRepositoryIdentity: ProjectEnrichmentService["Service"]["readRepositoryIdentity"] =
272 Effect.fn("ProjectEnrichmentService.readRepositoryIdentity")(function* (workspaceRoot) {
273 const resolved = yield* Cache.get(repositoryIdentityCache, workspaceRoot);
274 return Exit.isSuccess(resolved) ? resolved.value : null;
275 });
276​
277 const invalidate: ProjectEnrichmentService["Service"]["invalidate"] = Effect.fn(
278 "ProjectEnrichmentService.invalidate",
279 )(function* (workspaceRoots) {
280 yield* Effect.forEach(
281 new Set(workspaceRoots),
282 (workspaceRoot) =>
283 Effect.all(
284 [
285 Cache.invalidate(repositoryIdentityCache, workspaceRoot),
286 Cache.invalidate(faviconCache, workspaceRoot),
287 // The resolver keeps its own misses, which would outlive a clone filling the folder.
288 faviconResolver.invalidate(workspaceRoot),
289 ],
290 { concurrency: "unbounded", discard: true },
291 ),
292 { discard: true },
293 );
294 });
295​
296 return ProjectEnrichmentService.of({
297 peek,
298 request,
299 getAvailable,
300 readRepositoryIdentity,
301 invalidate,
302 subscribeChanges: PubSub.subscribe(changes),
303 });
304});
305​
306export const layer = Layer.effect(ProjectEnrichmentService, make());