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

ProjectEnrichmentService.ts

312 lines11.1 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 readRepositoryIdentity: (
54 workspaceRoot: string,
55 ) => Effect.Effect<RepositoryIdentity | null>;
56 readonly invalidate: (workspaceRoots: Iterable<string>) => Effect.Effect<void>;
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 });
75​
76function isSuccessfullyResolved<A, E>(cached: Option.Option<Exit.Exit<A, E>>): boolean {
77 return Option.match(cached, {
78 onNone: () => false,
79 onSome: (exit) => Exit.isSuccess(exit),
80 });
82​
83interface EnrichmentWorkLane {
84 readonly pendingRoots: Ref.Ref<ReadonlySet<string>>;
85 readonly queue: Queue.Queue<string>;
87​
88export const make = Effect.fn("ProjectEnrichmentService.make")(function* (
89 options: ProjectEnrichmentServiceOptions = {},
90) {
91 const repositoryIdentityResolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
92 const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
93 const cacheCapacity = Math.max(1, options.cacheCapacity ?? DEFAULT_CACHE_CAPACITY);
94 const maxPending = Math.max(1, options.maxPending ?? DEFAULT_MAX_PENDING);
95 const concurrency = Math.max(1, options.concurrency ?? DEFAULT_CONCURRENCY);
96 const successTtl = options.successTtl ?? DEFAULT_SUCCESS_TTL;
97 const failureTtl = options.failureTtl ?? DEFAULT_FAILURE_TTL;
98 const faviconTtl = options.faviconTtl ?? DEFAULT_FAVICON_TTL;
99​
100 const repositoryIdentityCache = yield* Cache.makeWith(
101 (workspaceRoot: string) => Effect.exit(repositoryIdentityResolver.resolve(workspaceRoot)),
102 {
103 capacity: cacheCapacity,
104 timeToLive: Exit.match({
105 onFailure: () => failureTtl,
106 onSuccess: (result) => (Exit.isSuccess(result) ? successTtl : failureTtl),
107 }),
108 },
109 );
110 const faviconCache = yield* Cache.makeWith(
111 (workspaceRoot: string) => Effect.exit(faviconResolver.resolvePath(workspaceRoot)),
112 {
113 capacity: cacheCapacity,
114 timeToLive: Exit.match({
115 onFailure: () => failureTtl,
116 onSuccess: (result) => (Exit.isSuccess(result) ? faviconTtl : failureTtl),
117 }),
118 },
119 );
120 const makeWorkLane = Effect.gen(function* () {
121 const pendingRoots = yield* Ref.make<ReadonlySet<string>>(new Set());
122 const queue = yield* Effect.acquireRelease(Queue.dropping<string>(maxPending), (queue) =>
123 Queue.shutdown(queue),
124 );
125 return { pendingRoots, queue } satisfies EnrichmentWorkLane;
126 });
127 const repositoryIdentityLane = yield* makeWorkLane;
128 const faviconLane = yield* makeWorkLane;
129 const changes = yield* Effect.acquireRelease(
130 PubSub.sliding<ProjectEnrichmentChange>(256),
131 (pubsub) => PubSub.shutdown(pubsub),
132 );
133​
134 const removePending = (lane: EnrichmentWorkLane, workspaceRoot: string) =>
135 Ref.update(lane.pendingRoots, (current) => {
136 if (!current.has(workspaceRoot)) return current;
137 const next = new Set(current);
138 next.delete(workspaceRoot);
139 return next;
140 });
141​
142 const reservePending = (lane: EnrichmentWorkLane, workspaceRoot: string) =>
143 Ref.modify(lane.pendingRoots, (current) => {
144 if (current.has(workspaceRoot) || current.size >= maxPending) {
145 return [false, current] as const;
146 }
147 const next = new Set(current);
148 next.add(workspaceRoot);
149 return [true, next] as const;
150 });
151​
152 const logFailure = <A, E>(
153 workspaceRoot: string,
154 field: "repositoryIdentity" | "faviconPath",
155 result: Exit.Exit<A, E>,
156 ) =>
157 Exit.isFailure(result)
158 ? Effect.logWarning("Failed to enrich optional project metadata", {
159 workspaceRoot,
160 field,
161 cause: Cause.pretty(result.cause),
162 })
163 : Effect.void;
164​
165 const resolveRepositoryIdentity = Effect.fn("ProjectEnrichmentService.resolveRepositoryIdentity")(
166 function* (workspaceRoot: string) {
167 const repositoryIdentity = yield* Cache.get(repositoryIdentityCache, workspaceRoot);
168 yield* logFailure(workspaceRoot, "repositoryIdentity", repositoryIdentity);
169 const faviconPath = yield* Cache.getSuccess(faviconCache, workspaceRoot);
170 const repositoryIdentityResolved = Exit.isSuccess(repositoryIdentity);
171 yield* PubSub.publish(changes, {
172 workspaceRoot,
173 repositoryIdentityResolved,
174 enrichment: {
175 repositoryIdentity: availableValue(Option.some(repositoryIdentity)),
176 faviconPath: availableValue(faviconPath),
177 repositoryIdentityResolved,
178 },
179 });
180 },
181 );
182​
183 const resolveFavicon = Effect.fn("ProjectEnrichmentService.resolveFavicon")(function* (
184 workspaceRoot: string,
185 ) {
186 const faviconPath = yield* Cache.get(faviconCache, workspaceRoot);
187 const isMissingWorkspaceRoot = Option.exists(
188 Exit.findErrorOption(faviconPath),
189 ProjectFaviconResolver.isMissingWorkspaceRoot,
190 );
191 if (isMissingWorkspaceRoot) {
192 return;
193 }
194 yield* logFailure(workspaceRoot, "faviconPath", faviconPath);
195 });
196​
197 const startWorkers = (
198 lane: EnrichmentWorkLane,
199 resolve: (workspaceRoot: string) => Effect.Effect<void>,
200 ) => {
201 const worker = Queue.take(lane.queue).pipe(
202 Effect.flatMap((workspaceRoot) =>
203 resolve(workspaceRoot).pipe(Effect.ensuring(removePending(lane, workspaceRoot))),
204 ),
205 Effect.forever,
206 );
207 return Effect.forEach(Array.from({ length: concurrency }), () => Effect.forkScoped(worker), {
208 discard: true,
209 });
210 };
211 yield* Effect.all(
212 [
213 startWorkers(repositoryIdentityLane, resolveRepositoryIdentity),
214 startWorkers(faviconLane, resolveFavicon),
215 ],
216 { concurrency: "unbounded", discard: true },
217 );
218​
219 const requestLane = Effect.fn("ProjectEnrichmentService.requestLane")(function* (
220 lane: EnrichmentWorkLane,
221 workspaceRoot: string,
222 field: "repositoryIdentity" | "faviconPath",
223 ) {
224 if (!(yield* reservePending(lane, workspaceRoot))) return;
225 if (!(yield* Queue.offer(lane.queue, workspaceRoot))) {
226 yield* removePending(lane, workspaceRoot);
227 yield* Effect.logWarning("Project metadata enrichment queue is full", {
228 workspaceRoot,
229 field,
230 });
231 }
232 });
233​
234 const peek: ProjectEnrichmentService["Service"]["peek"] = Effect.fn(
235 "ProjectEnrichmentService.peek",
236 )(function* (workspaceRoot) {
237 const [repositoryIdentity, faviconPath] = yield* Effect.all(
238 [
239 Cache.getSuccess(repositoryIdentityCache, workspaceRoot),
240 Cache.getSuccess(faviconCache, workspaceRoot),
241 ] as const,
242 { concurrency: "unbounded" },
243 );
244 return {
245 repositoryIdentity: availableValue(repositoryIdentity),
246 faviconPath: availableValue(faviconPath),
247 repositoryIdentityResolved: isSuccessfullyResolved(repositoryIdentity),
248 };
249 });
250​
251 const request: ProjectEnrichmentService["Service"]["request"] = Effect.fn(
252 "ProjectEnrichmentService.request",
253 )(function* (workspaceRoot) {
254 const [hasRepositoryIdentity, hasFaviconPath] = yield* Effect.all(
255 [Cache.has(repositoryIdentityCache, workspaceRoot), Cache.has(faviconCache, workspaceRoot)],
256 { concurrency: "unbounded" },
257 );
258 yield* Effect.all(
259 [
260 hasRepositoryIdentity
261 ? Effect.void
262 : requestLane(repositoryIdentityLane, workspaceRoot, "repositoryIdentity"),
263 hasFaviconPath ? Effect.void : requestLane(faviconLane, workspaceRoot, "faviconPath"),
264 ],
265 { concurrency: "unbounded", discard: true },
266 );
267 });
268​
269 const getAvailable: ProjectEnrichmentService["Service"]["getAvailable"] = Effect.fn(
270 "ProjectEnrichmentService.getAvailable",
271 )(function* (workspaceRoot) {
272 const available = yield* peek(workspaceRoot);
273 yield* request(workspaceRoot);
274 return available;
275 });
276​
277 const readRepositoryIdentity: ProjectEnrichmentService["Service"]["readRepositoryIdentity"] =
278 Effect.fn("ProjectEnrichmentService.readRepositoryIdentity")(function* (workspaceRoot) {
279 const resolved = yield* Cache.get(repositoryIdentityCache, workspaceRoot);
280 return Exit.isSuccess(resolved) ? resolved.value : null;
281 });
282​
283 const invalidate: ProjectEnrichmentService["Service"]["invalidate"] = Effect.fn(
284 "ProjectEnrichmentService.invalidate",
285 )(function* (workspaceRoots) {
286 yield* Effect.forEach(
287 new Set(workspaceRoots),
288 (workspaceRoot) =>
289 Effect.all(
290 [
291 Cache.invalidate(repositoryIdentityCache, workspaceRoot),
292 Cache.invalidate(faviconCache, workspaceRoot),
293 // The resolver keeps its own misses, which would outlive a clone filling the folder.
294 faviconResolver.invalidate(workspaceRoot),
295 ],
296 { concurrency: "unbounded", discard: true },
297 ),
298 { discard: true },
299 );
300 });
301​
302 return ProjectEnrichmentService.of({
303 peek,
304 request,
305 getAvailable,
306 readRepositoryIdentity,
307 invalidate,
308 subscribeChanges: PubSub.subscribe(changes),
309 });
310});
311​
312export const layer = Layer.effect(ProjectEnrichmentService, make());