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

ProjectEnrichmentService.ts

302 lines10.6 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;
42 readonly successTtl?: Duration.Input;
43 readonly faviconTtl?: Duration.Input;
44 readonly failureTtl?: Duration.Input;
46​
47export class ProjectEnrichmentService extends Context.Service<
48 ProjectEnrichmentService,
49 {
50 readonly peek: (workspaceRoot: string) => Effect.Effect<ProjectEnrichment>;
51 readonly request: (workspaceRoot: string) => Effect.Effect<void>;
52 readonly getAvailable: (workspaceRoot: string) => Effect.Effect<ProjectEnrichment>;
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 const successTtl = options.successTtl ?? DEFAULT_SUCCESS_TTL;
94 const failureTtl = options.failureTtl ?? DEFAULT_FAILURE_TTL;
95 const faviconTtl = options.faviconTtl ?? DEFAULT_FAVICON_TTL;
96​
97 const repositoryIdentityCache = yield* Cache.makeWith(
98 (workspaceRoot: string) => Effect.exit(repositoryIdentityResolver.resolve(workspaceRoot)),
99 {
100 capacity: cacheCapacity,
101 timeToLive: Exit.match({
102 onFailure: () => failureTtl,
103 onSuccess: (result) => (Exit.isSuccess(result) ? successTtl : failureTtl),
104 }),
105 },
106 );
107 const faviconCache = yield* Cache.makeWith(
108 (workspaceRoot: string) => Effect.exit(faviconResolver.resolvePath(workspaceRoot)),
109 {
110 capacity: cacheCapacity,
111 timeToLive: Exit.match({
112 onFailure: () => failureTtl,
113 onSuccess: (result) => (Exit.isSuccess(result) ? faviconTtl : failureTtl),
114 }),
115 },
116 );
117 const makeWorkLane = Effect.gen(function* () {
118 const pendingRoots = yield* Ref.make<ReadonlySet<string>>(new Set());
119 const queue = yield* Effect.acquireRelease(Queue.dropping<string>(maxPending), (queue) =>
120 Queue.shutdown(queue),
121 );
122 return { pendingRoots, queue } satisfies EnrichmentWorkLane;
123 });
124 const repositoryIdentityLane = yield* makeWorkLane;
125 const faviconLane = yield* makeWorkLane;
126 const changes = yield* Effect.acquireRelease(
127 PubSub.sliding<ProjectEnrichmentChange>(256),
128 (pubsub) => PubSub.shutdown(pubsub),
129 );
130​
131 const removePending = (lane: EnrichmentWorkLane, workspaceRoot: string) =>
132 Ref.update(lane.pendingRoots, (current) => {
133 if (!current.has(workspaceRoot)) return current;
134 const next = new Set(current);
135 next.delete(workspaceRoot);
136 return next;
137 });
138​
139 const reservePending = (lane: EnrichmentWorkLane, workspaceRoot: string) =>
140 Ref.modify(lane.pendingRoots, (current) => {
141 if (current.has(workspaceRoot) || current.size >= maxPending) {
142 return [false, current] as const;
143 }
144 const next = new Set(current);
145 next.add(workspaceRoot);
146 return [true, next] as const;
147 });
148​
149 const logFailure = <A, E>(
150 workspaceRoot: string,
151 field: "repositoryIdentity" | "faviconPath",
152 result: Exit.Exit<A, E>,
153 ) =>
154 Exit.isFailure(result)
155 ? Effect.logWarning("Failed to enrich optional project metadata", {
156 workspaceRoot,
157 field,
158 cause: Cause.pretty(result.cause),
159 })
160 : Effect.void;
161​
162 const resolveRepositoryIdentity = Effect.fn("ProjectEnrichmentService.resolveRepositoryIdentity")(
163 function* (workspaceRoot: string) {
164 const repositoryIdentity = yield* Cache.get(repositoryIdentityCache, workspaceRoot);
165 yield* logFailure(workspaceRoot, "repositoryIdentity", repositoryIdentity);
166 const faviconPath = yield* Cache.getSuccess(faviconCache, workspaceRoot);
167 const repositoryIdentityResolved = Exit.isSuccess(repositoryIdentity);
168 yield* PubSub.publish(changes, {
169 workspaceRoot,
170 repositoryIdentityResolved,
171 enrichment: {
172 repositoryIdentity: availableValue(Option.some(repositoryIdentity)),
173 faviconPath: availableValue(faviconPath),
174 repositoryIdentityResolved,
175 },
176 });
177 },
178 );
179​
180 const resolveFavicon = Effect.fn("ProjectEnrichmentService.resolveFavicon")(function* (
181 workspaceRoot: string,
182 ) {
183 const faviconPath = yield* Cache.get(faviconCache, workspaceRoot);
184 const isMissingWorkspaceRoot = Option.exists(
185 Exit.findErrorOption(faviconPath),
186 ProjectFaviconResolver.isMissingWorkspaceRoot,
187 );
188 if (isMissingWorkspaceRoot) {
189 return;
190 }
191 yield* logFailure(workspaceRoot, "faviconPath", faviconPath);
192 });
193​
194 const startWorkers = (
195 lane: EnrichmentWorkLane,
196 resolve: (workspaceRoot: string) => Effect.Effect<void>,
197 ) => {
198 const worker = Queue.take(lane.queue).pipe(
199 Effect.flatMap((workspaceRoot) =>
200 resolve(workspaceRoot).pipe(Effect.ensuring(removePending(lane, workspaceRoot))),
201 ),
202 Effect.forever,
203 );
204 return Effect.forEach(Array.from({ length: concurrency }), () => Effect.forkScoped(worker), {
205 discard: true,
206 });
207 };
208 yield* Effect.all(
209 [
210 startWorkers(repositoryIdentityLane, resolveRepositoryIdentity),
211 startWorkers(faviconLane, resolveFavicon),
212 ],
213 { concurrency: "unbounded", discard: true },
214 );
215​
216 const requestLane = Effect.fn("ProjectEnrichmentService.requestLane")(function* (
217 lane: EnrichmentWorkLane,
218 workspaceRoot: string,
219 field: "repositoryIdentity" | "faviconPath",
220 ) {
221 if (!(yield* reservePending(lane, workspaceRoot))) return;
222 if (!(yield* Queue.offer(lane.queue, workspaceRoot))) {
223 yield* removePending(lane, workspaceRoot);
224 yield* Effect.logWarning("Project metadata enrichment queue is full", {
225 workspaceRoot,
226 field,
227 });
228 }
229 });
230​
231 const peek: ProjectEnrichmentService["Service"]["peek"] = Effect.fn(
232 "ProjectEnrichmentService.peek",
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 const request: ProjectEnrichmentService["Service"]["request"] = Effect.fn(
249 "ProjectEnrichmentService.request",
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 const getAvailable: ProjectEnrichmentService["Service"]["getAvailable"] = Effect.fn(
267 "ProjectEnrichmentService.getAvailable",
268 )(function* (workspaceRoot) {
269 const available = yield* peek(workspaceRoot);
270 yield* request(workspaceRoot);
271 return available;
272 });
273​
274 const invalidate: ProjectEnrichmentService["Service"]["invalidate"] = Effect.fn(
275 "ProjectEnrichmentService.invalidate",
276 )(function* (workspaceRoots) {
277 yield* Effect.forEach(
278 new Set(workspaceRoots),
279 (workspaceRoot) =>
280 Effect.all(
281 [
282 Cache.invalidate(repositoryIdentityCache, workspaceRoot),
283 Cache.invalidate(faviconCache, workspaceRoot),
284 // The resolver keeps its own misses, which would outlive a clone filling the folder.
285 faviconResolver.invalidate(workspaceRoot),
286 ],
287 { concurrency: "unbounded", discard: true },
288 ),
289 { discard: true },
290 );
291 });
292​
293 return ProjectEnrichmentService.of({
294 peek,
295 request,
296 getAvailable,
297 invalidate,
298 subscribeChanges: PubSub.subscribe(changes),
299 });
300});
301​
302export const layer = Layer.effect(ProjectEnrichmentService, make());