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