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

PullRequestReadCache.test.ts

421 lines17.8 KB

1import { assert, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { PullRequestOperationError } from "@t3tools/contracts";
4import * as DateTime from "effect/DateTime";
5import * as Deferred from "effect/Deferred";
6import * as Duration from "effect/Duration";
7import * as Effect from "effect/Effect";
8import * as Fiber from "effect/Fiber";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Path from "effect/Path";
12import * as Queue from "effect/Queue";
13import * as TestClock from "effect/testing/TestClock";
14import * as KeyValueStore from "effect/persistence/KeyValueStore";
15import * as ServerConfig from "../config.ts";
16import { ServerActivation } from "../serverActivation.ts";
17import * as PullRequestReadCache from "./PullRequestReadCache.ts";
18​
19const cacheLayer = (directory: string) =>
20 PullRequestReadCache.make.pipe(Effect.provide(KeyValueStore.layerFileSystem(directory)));
21​
22const ageFiles = (directory: string, names: ReadonlyArray<string>, age: Duration.Duration) =>
23 Effect.gen(function* () {
24 const fs = yield* FileSystem.FileSystem;
25 const path = yield* Path.Path;
26 const mtime = DateTime.toDateUtc(DateTime.subtractDuration(yield* DateTime.now, age));
27 for (const name of names) yield* fs.utimes(path.join(directory, name), mtime, mtime);
28 });
29​
30it.layer(NodeServices.layer)("PR filesystem cache", (it) => {
31 it.effect("prunes entry files written before the max age and keeps fresh ones", () =>
32 Effect.gen(function* () {
33 const fs = yield* FileSystem.FileSystem;
34 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pr-cache-" });
35 yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-01T00:00:00Z")));
36 const cache = yield* cacheLayer(directory);
37 yield* cache.get("old", Effect.succeed("old"), ["pr"]);
38 yield* cache.invalidate("pr");
39 const [stale, revisions] = (yield* fs.readDirectory(directory)).toSorted();
40 assert.strictEqual(revisions, "revisions");
41 yield* cache.get("fresh", Effect.succeed("fresh"));
42 const fresh = (yield* fs.readDirectory(directory)).find(
43 (name) => name !== stale && name !== revisions,
44 );
45 const unrelated = "unrelated.json";
46 yield* fs.writeFileString(`${directory}/${unrelated}`, "{}");
47 const prefixed = "pr-v2-backup.json";
48 yield* fs.writeFileString(`${directory}/${prefixed}`, "{}");
49 const justExpired = Duration.sum(
50 PullRequestReadCache.ENTRY_FILE_MAX_AGE,
51 Duration.seconds(1),
52 );
53 yield* ageFiles(directory, [stale!, revisions!, unrelated, prefixed], justExpired);
54 yield* ageFiles(directory, [fresh!], PullRequestReadCache.ENTRY_FILE_MAX_AGE);
55​
56 yield* PullRequestReadCache.pruneExpiredEntryFiles(directory);
57​
58 assert.deepStrictEqual(
59 (yield* fs.readDirectory(directory)).toSorted(),
60 [fresh!, revisions!, unrelated, prefixed].toSorted(),
61 );
62 }),
63 );
64​
65 it.effect("shares one scoped prune loop across cache layer consumers", () =>
66 Effect.gen(function* () {
67 const fs = yield* FileSystem.FileSystem;
68 const activation = yield* Deferred.make<void>();
69 let scans = 0;
70 const observedFs = FileSystem.FileSystem.of({
71 ...fs,
72 // An empty directory keeps every sweep synchronous under the test clock.
73 readDirectory: () =>
74 Effect.sync(() => {
75 scans++;
76 return [];
77 }),
78 });
79 const caches: Array<PullRequestReadCache.PullRequestReadCache["Service"]> = [];
80 const sharedLayer = PullRequestReadCache.layer.pipe(
81 Layer.provide(Layer.succeed(FileSystem.FileSystem, observedFs)),
82 );
83 const consumers = Array.from({ length: 6 }, () =>
84 Layer.effectDiscard(
85 Effect.gen(function* () {
86 caches.push(yield* PullRequestReadCache.PullRequestReadCache);
87 }),
88 ).pipe(Layer.provide(sharedLayer)),
89 );
90 const scanCounts: Array<number> = [];
91​
92 yield* Effect.scoped(
93 Effect.gen(function* () {
94 yield* Layer.build(Layer.mergeAll(consumers[0]!, ...consumers.slice(1)));
95 assert.strictEqual(caches.length, 6);
96 assert.strictEqual(new Set(caches).size, 1);
97 scanCounts.push(scans);
98 yield* Deferred.succeed(activation, undefined);
99 yield* TestClock.adjust(Duration.zero);
100 scanCounts.push(scans);
101 yield* TestClock.adjust("59 minutes");
102 scanCounts.push(scans);
103 yield* TestClock.adjust("1 minute");
104 scanCounts.push(scans);
105 yield* TestClock.adjust("1 hour");
106 scanCounts.push(scans);
107 }).pipe(Effect.provideService(ServerActivation, Deferred.await(activation))),
108 );
109 yield* TestClock.adjust("2 hours");
110 assert.deepStrictEqual([...scanCounts, scans], [0, 1, 1, 2, 3, 3]);
111 }).pipe(
112 Effect.scoped,
113 Effect.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-pr-cache-shared-" })),
114 ),
115 );
116​
117 it.effect("uses memory without starting cleanup when the cache directory is unavailable", () =>
118 Effect.gen(function* () {
119 const fs = yield* FileSystem.FileSystem;
120 const { providerStatusCacheDir } = yield* ServerConfig.ServerConfig;
121 yield* fs.remove(providerStatusCacheDir, { recursive: true });
122 yield* fs.writeFileString(providerStatusCacheDir, "blocks the cache directory");
123 let scans = 0;
124 const observedFs = FileSystem.FileSystem.of({
125 ...fs,
126 readDirectory: () =>
127 Effect.sync(() => {
128 scans++;
129 return [];
130 }),
131 });
132 yield* Effect.gen(function* () {
133 const cache = yield* PullRequestReadCache.PullRequestReadCache;
134 let reads = 0;
135 const lookup = Effect.sync(() => String(++reads));
136 assert.strictEqual(yield* cache.get("summary", lookup, ["pr"]), "1");
137 assert.strictEqual(yield* cache.get("summary", lookup, ["pr"]), "1");
138 yield* cache.invalidate("pr");
139 assert.strictEqual(yield* cache.get("summary", lookup, ["pr"]), "2");
140 yield* TestClock.adjust("1 hour");
141 assert.strictEqual(scans, 0);
142 }).pipe(
143 Effect.provide(
144 PullRequestReadCache.layer.pipe(
145 Layer.provide(Layer.succeed(FileSystem.FileSystem, observedFs)),
146 ),
147 ),
148 );
149 }).pipe(
150 Effect.scoped,
151 Effect.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-pr-cache-fallback-" })),
152 ),
153 );
154​
155 it.effect("sweeps the cache directory every hour once the layer is built", () =>
156 Effect.gen(function* () {
157 const fs = yield* FileSystem.FileSystem;
158 const { providerStatusCacheDir } = yield* ServerConfig.ServerConfig;
159 const directory = `${providerStatusCacheDir}/pull-requests`;
160 yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-01T00:00:00Z")));
161 yield* (yield* cacheLayer(directory)).get("summary", Effect.succeed("cached"));
162 const [entry] = yield* fs.readDirectory(directory);
163 yield* ageFiles(
164 directory,
165 [entry!],
166 Duration.subtract(PullRequestReadCache.ENTRY_FILE_MAX_AGE, Duration.minutes(90)),
167 );
168 const operations = yield* Queue.unbounded<string>();
169 const observedFs = FileSystem.FileSystem.of({
170 ...fs,
171 stat: (path) => fs.stat(path).pipe(Effect.tap(() => Queue.offer(operations, "stat"))),
172 remove: (path, options) =>
173 fs.remove(path, options).pipe(Effect.tap(() => Queue.offer(operations, "remove"))),
174 });
175 yield* Layer.build(
176 PullRequestReadCache.layer.pipe(
177 Layer.provide(Layer.succeed(FileSystem.FileSystem, observedFs)),
178 ),
179 );
180 assert.strictEqual(yield* Queue.take(operations), "stat");
181 yield* TestClock.adjust("1 hour");
182 assert.strictEqual(yield* Queue.take(operations), "stat");
183 assert.deepStrictEqual(yield* fs.readDirectory(directory), [entry]);
184 yield* TestClock.adjust("1 hour");
185 assert.deepStrictEqual(yield* Queue.takeN(operations, 2), ["stat", "remove"]);
186 assert.deepStrictEqual(yield* fs.readDirectory(directory), []);
187 }).pipe(
188 Effect.scoped,
189 Effect.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-pr-cache-layer-" })),
190 ),
191 );
192​
193 it.effect("reuses files after restart and respects the original expiry", () =>
194 Effect.gen(function* () {
195 const fs = yield* FileSystem.FileSystem;
196 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pr-cache-" });
197 let reads = 0;
198 const lookup = Effect.sync(() => String(++reads));
199 const first = yield* cacheLayer(directory);
200 const key = "long/repository/key".repeat(100);
201 assert.strictEqual(yield* first.get(key, lookup), "1");
202 yield* TestClock.adjust("59 seconds");
203 const restarted = yield* cacheLayer(directory);
204 assert.strictEqual(yield* restarted.get(key, lookup), "1");
205 yield* TestClock.adjust("1 second");
206 assert.strictEqual(yield* restarted.get(key, lookup), "2");
207 assert.strictEqual(reads, 2);
208 assert.strictEqual((yield* fs.readDirectory(directory)).length, 1);
209 }),
210 );
211​
212 it.effect("clears in-flight reads before a new service can reuse them", () =>
213 Effect.gen(function* () {
214 const fs = yield* FileSystem.FileSystem;
215 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pr-cache-" });
216 const started = yield* Deferred.make<void>();
217 const release = yield* Deferred.make<void>();
218 const cache = yield* cacheLayer(directory);
219 const read = yield* cache
220 .get(
221 "summary",
222 Deferred.succeed(started, undefined).pipe(
223 Effect.andThen(Deferred.await(release)),
224 Effect.as("old"),
225 ),
226 ["pr"],
227 )
228 .pipe(Effect.forkChild);
229 yield* Deferred.await(started);
230 const invalidate = yield* cache
231 .invalidate("pr")
232 .pipe(Effect.forkChild({ startImmediately: true }));
233 yield* Deferred.succeed(release, undefined);
234 yield* Fiber.join(read);
235 yield* Fiber.join(invalidate);
236 const restarted = yield* cacheLayer(directory);
237 assert.strictEqual(yield* restarted.get("summary", Effect.succeed("new"), ["pr"]), "new");
238 }),
239 );
240​
241 it.effect("invalidates only the changed scope across restarts and coalesces its next reads", () =>
242 Effect.gen(function* () {
243 const fs = yield* FileSystem.FileSystem;
244 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pr-cache-" });
245 let reads = 0;
246 const lookup = Effect.sync(() => String(++reads));
247 const cache = yield* cacheLayer(directory);
248 yield* cache.get("first", lookup, ["project", "pr-1"]);
249 yield* cache.get("second", lookup, ["project", "pr-2"]);
250 yield* cache.get("third", lookup, ["other-project", "pr-3"]);
251 yield* cache.invalidate("pr-1");
252 const restarted = yield* cacheLayer(directory);
253 const answers = yield* Effect.all(
254 Array.from({ length: 10 }, () => restarted.get("first", lookup, ["project", "pr-1"])),
255 { concurrency: 10 },
256 );
257 assert.deepStrictEqual(answers, Array(10).fill("4"));
258 assert.strictEqual(yield* restarted.get("second", lookup, ["project", "pr-2"]), "2");
259 yield* restarted.invalidate("project");
260 const again = yield* cacheLayer(directory);
261 assert.strictEqual(yield* again.get("second", lookup, ["project", "pr-2"]), "5");
262 assert.strictEqual(yield* again.get("third", lookup, ["other-project", "pr-3"]), "3");
263 assert.strictEqual(reads, 5);
264 const files = (yield* fs.readDirectory(directory)).length;
265 for (let index = 0; index < 3; index++) {
266 yield* again.invalidate("pr-1");
267 yield* again.get("first", lookup, ["project", "pr-1"]);
268 }
269 assert.strictEqual((yield* fs.readDirectory(directory)).length, files);
270 }),
271 );
272​
273 it.effect("shares a pending refresh without blocking an unrelated cached PR", () =>
274 Effect.gen(function* () {
275 const cache = yield* PullRequestReadCache.make;
276 yield* cache.get("first", Effect.succeed("old"), ["pr-1"]);
277 yield* cache.get("second", Effect.succeed("warm"), ["pr-2"]);
278 yield* cache.invalidate("pr-1");
279 const started = yield* Deferred.make<void>();
280 const release = yield* Deferred.make<void>();
281 let reads = 0;
282 const refresh = cache.get(
283 "first",
284 Effect.gen(function* () {
285 reads++;
286 yield* Deferred.succeed(started, undefined);
287 yield* Deferred.await(release);
288 return "fresh";
289 }),
290 ["pr-1"],
291 );
292 const pending = yield* Effect.all(
293 Array.from({ length: 10 }, () => refresh),
294 {
295 concurrency: 10,
296 },
297 ).pipe(Effect.forkChild);
298 yield* Deferred.await(started);
299 assert.strictEqual(yield* cache.get("second", Effect.die("cache miss"), ["pr-2"]), "warm");
300 yield* Deferred.succeed(release, undefined);
301 assert.deepStrictEqual(yield* Fiber.join(pending), Array(10).fill("fresh"));
302 assert.strictEqual(reads, 1);
303 }).pipe(Effect.provide(KeyValueStore.layerMemory)),
304 );
305​
306 it.effect("compacts expired scope records without discarding fresh PR data", () =>
307 Effect.gen(function* () {
308 const fs = yield* FileSystem.FileSystem;
309 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pr-cache-" });
310 const cache = yield* cacheLayer(directory);
311 yield* cache.get("summary", Effect.succeed("old"), ["pr"]);
312 yield* cache.invalidate("pr");
313 for (let index = 0; index < 100; index++) yield* cache.invalidate(`pr-${index}`);
314 assert.strictEqual((yield* fs.readDirectory(directory)).length, 2);
315 const before = (yield* fs.stat(`${directory}/revisions`)).size;
316 yield* TestClock.adjust("59 seconds");
317 assert.strictEqual(yield* cache.get("summary", Effect.succeed("fresh"), ["pr"]), "fresh");
318 yield* TestClock.adjust("1 second");
319 yield* cache.invalidate("other-pr");
320 assert.isTrue((yield* fs.stat(`${directory}/revisions`)).size < before);
321 const restarted = yield* cacheLayer(directory);
322 assert.strictEqual(
323 yield* restarted.get("summary", Effect.die("cache miss"), ["pr"]),
324 "fresh",
325 );
326 }),
327 );
328​
329 it.effect("does not persist failed GitHub reads", () =>
330 Effect.gen(function* () {
331 const fs = yield* FileSystem.FileSystem;
332 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pr-cache-" });
333 const cache = yield* cacheLayer(directory);
334 const error = new PullRequestOperationError({ operation: "summary", detail: "unavailable" });
335 yield* cache.get("summary", Effect.fail(error)).pipe(Effect.flip);
336 const restarted = yield* cacheLayer(directory);
337 assert.strictEqual(yield* restarted.get("summary", Effect.succeed("recovered")), "recovered");
338 }),
339 );
340​
341 it.effect("resumes caching after a failed scope read", () =>
342 Effect.gen(function* () {
343 const backing = yield* KeyValueStore.KeyValueStore;
344 let fail = true;
345 let reads = 0;
346 const cache = yield* PullRequestReadCache.make.pipe(
347 Effect.provideService(KeyValueStore.KeyValueStore, {
348 ...backing,
349 get: (key) =>
350 Effect.suspend(() => {
351 if (!fail) return backing.get(key);
352 fail = false;
353 return Effect.fail(
354 new KeyValueStore.KeyValueStoreError({ method: "get", message: "unavailable" }),
355 );
356 }),
357 }),
358 );
359 const read = cache.get(
360 "summary",
361 Effect.sync(() => String(++reads)),
362 ["pr"],
363 );
364 assert.strictEqual(yield* read, "1");
365 assert.strictEqual(yield* read, "2");
366 assert.strictEqual(yield* read, "2");
367 }).pipe(Effect.provide(KeyValueStore.layerMemory)),
368 );
369​
370 it.effect("cancels abandoned reads without blocking invalidation", () =>
371 Effect.gen(function* () {
372 const cache = yield* PullRequestReadCache.make;
373 const started = yield* Deferred.make<void>();
374 const read = yield* cache
375 .get("summary", Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never)), [
376 "pr",
377 ])
378 .pipe(Effect.forkChild);
379 yield* Deferred.await(started);
380 yield* Fiber.interrupt(read);
381 yield* cache.invalidate("pr");
382 assert.strictEqual(yield* cache.get("summary", Effect.succeed("fresh"), ["pr"]), "fresh");
383 }).pipe(Effect.provide(KeyValueStore.layerMemory)),
384 );
385​
386 it.effect(
387 "finishes the in-memory revision update when invalidation is canceled after writing",
388 () =>
389 Effect.gen(function* () {
390 const backing = yield* KeyValueStore.KeyValueStore;
391 const written = yield* Deferred.make<void>();
392 const release = yield* Deferred.make<void>();
393 const cache = yield* PullRequestReadCache.make.pipe(
394 Effect.provideService(KeyValueStore.KeyValueStore, {
395 ...backing,
396 set: (key, value) =>
397 backing
398 .set(key, value)
399 .pipe(
400 Effect.andThen(
401 key === "revisions"
402 ? Deferred.succeed(written, undefined).pipe(
403 Effect.andThen(Deferred.await(release)),
404 )
405 : Effect.void,
406 ),
407 ),
408 }),
409 );
410 yield* cache.get("summary", Effect.succeed("old"), ["pr"]);
411 const invalidation = yield* cache.invalidate("pr").pipe(Effect.forkChild);
412 yield* Deferred.await(written);
413 const interrupt = yield* Fiber.interrupt(invalidation).pipe(
414 Effect.forkChild({ startImmediately: true }),
415 );
416 yield* Deferred.succeed(release, undefined);
417 yield* Fiber.join(interrupt);
418 assert.strictEqual(yield* cache.get("summary", Effect.succeed("fresh"), ["pr"]), "fresh");
419 }).pipe(Effect.provide(KeyValueStore.layerMemory)),
420 );
421});