Open History to see the last commit
1import * as NodeV8 from "node:v8";
2import * as NodeVM from "node:vm";
3import { assert, it } from "@effect/vitest";
4import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import * as Layer from "effect/Layer";
7import { PullRequestOperationError } from "@t3tools/contracts";
8import * as Deferred from "effect/Deferred";
9import * as Duration from "effect/Duration";
10import * as Effect from "effect/Effect";
11import * as Fiber from "effect/Fiber";
12import * as FileSystem from "effect/FileSystem";
13import * as Option from "effect/Option";
14import * as Path from "effect/Path";
15import * as KeyValueStore from "effect/persistence/KeyValueStore";
16import * as TestClock from "effect/testing/TestClock";
17import * as PullRequestReadCache from "./PullRequestReadCache.ts";
18
19NodeV8.setFlagsFromString("--expose-gc");
20const collectGarbage = NodeVM.runInNewContext("gc") as () => void;
21
22const cacheLayer = (directory: string) =>
23 PullRequestReadCache.make.pipe(Effect.provide(KeyValueStore.layerFileSystem(directory)));
24
25it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("PR filesystem cache", (it) => {
26 it.effect("clears in-flight reads before a new service can reuse them", () =>
27 Effect.gen(function* () {
28 const fs = yield* FileSystem.FileSystem;
29 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pr-cache-" });
30 const started = yield* Deferred.make<void>();
31 const release = yield* Deferred.make<void>();
32 const cache = yield* cacheLayer(directory);
33 const read = yield* cache
34 .get(
35 "summary",
36 Deferred.succeed(started, undefined).pipe(
37 Effect.andThen(Deferred.await(release)),
38 Effect.as("old"),
39 ),
40 ["pr"],
41 )
42 .pipe(Effect.forkChild);
43 yield* Deferred.await(started);
44 const invalidate = yield* cache
45 .invalidate("pr")
46 .pipe(Effect.forkChild({ startImmediately: true }));
47 yield* Deferred.succeed(release, undefined);
48 yield* Fiber.join(read);
49 yield* Fiber.join(invalidate);
50 const restarted = yield* cacheLayer(directory);
51 assert.strictEqual(yield* restarted.get("summary", Effect.succeed("new"), ["pr"]), "new");
52 }),
53 );
54
55 it.effect("prunes expired entry files the store wrote", () =>
56 Effect.gen(function* () {
57 const fs = yield* FileSystem.FileSystem;
58 const path = yield* Path.Path;
59 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pr-cache-" });
60 const cache = yield* cacheLayer(directory);
61 yield* cache.get("summary", Effect.succeed("value"));
62 const [entry] = yield* fs.readDirectory(directory);
63 assert.isDefined(entry);
64 const info = yield* fs.stat(path.join(directory, entry));
65 yield* TestClock.setTime(
66 Option.getOrThrow(info.mtime).getTime() + Duration.toMillis(Duration.days(2)),
67 );
68 yield* PullRequestReadCache.pruneExpiredEntryFiles(directory);
69 assert.deepStrictEqual(yield* fs.readDirectory(directory), []);
70 }),
71 );
72
73 it.effect("invalidates only the changed scope across restarts and coalesces its next reads", () =>
74 Effect.gen(function* () {
75 const fs = yield* FileSystem.FileSystem;
76 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pr-cache-" });
77 let reads = 0;
78 const lookup = Effect.sync(() => String(++reads));
79 const cache = yield* cacheLayer(directory);
80 yield* cache.get("first", lookup, ["project", "pr-1"]);
81 yield* cache.get("second", lookup, ["project", "pr-2"]);
82 yield* cache.get("third", lookup, ["other-project", "pr-3"]);
83 yield* cache.invalidate("pr-1");
84 const restarted = yield* cacheLayer(directory);
85 const answers = yield* Effect.all(
86 Array.from({ length: 10 }, () => restarted.get("first", lookup, ["project", "pr-1"])),
87 { concurrency: 10 },
88 );
89 assert.deepStrictEqual(answers, Array(10).fill("4"));
90 assert.strictEqual(yield* restarted.get("second", lookup, ["project", "pr-2"]), "2");
91 yield* restarted.invalidate("project");
92 const again = yield* cacheLayer(directory);
93 assert.strictEqual(yield* again.get("second", lookup, ["project", "pr-2"]), "5");
94 assert.strictEqual(yield* again.get("third", lookup, ["other-project", "pr-3"]), "3");
95 assert.strictEqual(reads, 5);
96 const files = (yield* fs.readDirectory(directory)).length;
97 for (let index = 0; index < 3; index++) {
98 yield* again.invalidate("pr-1");
99 yield* again.get("first", lookup, ["project", "pr-1"]);
100 }
101 assert.strictEqual((yield* fs.readDirectory(directory)).length, files);
102 }),
103 );
104
105 it.effect("shares a pending refresh without blocking an unrelated cached PR", () =>
106 Effect.gen(function* () {
107 const cache = yield* PullRequestReadCache.make;
108 yield* cache.get("first", Effect.succeed("old"), ["pr-1"]);
109 yield* cache.get("second", Effect.succeed("warm"), ["pr-2"]);
110 yield* cache.invalidate("pr-1");
111 const started = yield* Deferred.make<void>();
112 const release = yield* Deferred.make<void>();
113 let reads = 0;
114 const refresh = cache.get(
115 "first",
116 Effect.gen(function* () {
117 reads++;
118 yield* Deferred.succeed(started, undefined);
119 yield* Deferred.await(release);
120 return "fresh";
121 }),
122 ["pr-1"],
123 );
124 const pending = yield* Effect.all(
125 Array.from({ length: 10 }, () => refresh),
126 {
127 concurrency: 10,
128 },
129 ).pipe(Effect.forkChild);
130 yield* Deferred.await(started);
131 assert.strictEqual(yield* cache.get("second", Effect.die("cache miss"), ["pr-2"]), "warm");
132 yield* Deferred.succeed(release, undefined);
133 assert.deepStrictEqual(yield* Fiber.join(pending), Array(10).fill("fresh"));
134 assert.strictEqual(reads, 1);
135 }).pipe(Effect.provide(KeyValueStore.layerMemory)),
136 );
137
138 it.effect("does not persist failed GitHub reads", () =>
139 Effect.gen(function* () {
140 const fs = yield* FileSystem.FileSystem;
141 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pr-cache-" });
142 const cache = yield* cacheLayer(directory);
143 const error = new PullRequestOperationError({ operation: "summary", detail: "unavailable" });
144 yield* cache.get("summary", Effect.fail(error)).pipe(Effect.flip);
145 const restarted = yield* cacheLayer(directory);
146 assert.strictEqual(yield* restarted.get("summary", Effect.succeed("recovered")), "recovered");
147 }),
148 );
149
150 it.effect.each(["", "{", '{"pr":{"revision":42}}'])(
151 "recovers from malformed scope revisions without reusing stale entries: %j",
152 (corrupt) =>
153 Effect.gen(function* () {
154 const fs = yield* FileSystem.FileSystem;
155 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pr-cache-" });
156 const original = yield* cacheLayer(directory);
157 yield* original.get("summary", Effect.succeed("stale"), ["pr"]);
158 yield* fs.writeFileString(directory + "/revisions", corrupt);
159 const recovered = yield* cacheLayer(directory);
160 let reads = 0;
161 const lookup = Effect.sync(() => String(++reads));
162 assert.strictEqual(yield* recovered.get("summary", lookup, ["pr"]), "1");
163 assert.strictEqual(yield* recovered.get("summary", lookup, ["pr"]), "1");
164 yield* recovered.invalidate("pr");
165 assert.strictEqual(yield* recovered.get("summary", lookup, ["pr"]), "2");
166 const restarted = yield* cacheLayer(directory);
167 assert.strictEqual(yield* restarted.get("summary", lookup, ["pr"]), "2");
168 assert.strictEqual(reads, 2);
169 }),
170 );
171 it.effect("resumes caching after a failed scope read", () =>
172 Effect.gen(function* () {
173 const backing = yield* KeyValueStore.KeyValueStore;
174 let fail = true;
175 let reads = 0;
176 const cache = yield* PullRequestReadCache.make.pipe(
177 Effect.provideService(KeyValueStore.KeyValueStore, {
178 ...backing,
179 get: (key) =>
180 Effect.suspend(() => {
181 if (!fail) return backing.get(key);
182 fail = false;
183 return Effect.fail(
184 new KeyValueStore.KeyValueStoreError({ method: "get", message: "unavailable" }),
185 );
186 }),
187 }),
188 );
189 const read = cache.get(
190 "summary",
191 Effect.sync(() => String(++reads)),
192 ["pr"],
193 );
194 assert.strictEqual(yield* read, "1");
195 assert.strictEqual(yield* read, "2");
196 assert.strictEqual(yield* read, "2");
197 }).pipe(Effect.provide(KeyValueStore.layerMemory)),
198 );
199
200 it.effect("does not keep a caller's data alive after its reads and invalidations", () =>
201 Effect.gen(function* () {
202 const cache = yield* PullRequestReadCache.make;
203 const sweeps: Array<WeakRef<object>> = [];
204 // Like a sync sweep: an Effect.fn made per run that closes over that run's data.
205 const sweep = Effect.fn("sweep")(function* (index: number) {
206 const groups = new Map<string, number>(
207 Array.from({ length: 1_000 }, (_, id) => [`group-${id}`, id]),
208 );
209 sweeps.push(new WeakRef(groups));
210 const read = Effect.fn("read")(function* (pr: string) {
211 const size = groups.size;
212 yield* cache.invalidate(pr);
213 const answer = yield* cache.get(`${pr}-${index}`, Effect.succeed("answer"), [pr]);
214 return size + answer.length;
215 });
216 yield* Effect.forEach(["pr-1", "pr-2"], read, { discard: true });
217 });
218 for (let index = 0; index < 5; index++) yield* sweep(index);
219 // WeakRef targets stay alive until the current job ends, so yield before collecting.
220 yield* Effect.yieldNow;
221 collectGarbage();
222 assert.strictEqual(sweeps.filter((sweepData) => sweepData.deref() !== undefined).length, 0);
223 }).pipe(Effect.provide(KeyValueStore.layerMemory)),
224 );
225
226 it.effect("cancels abandoned reads without blocking invalidation", () =>
227 Effect.gen(function* () {
228 const cache = yield* PullRequestReadCache.make;
229 const started = yield* Deferred.make<void>();
230 const read = yield* cache
231 .get("summary", Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never)), [
232 "pr",
233 ])
234 .pipe(Effect.forkChild);
235 yield* Deferred.await(started);
236 yield* Fiber.interrupt(read);
237 yield* cache.invalidate("pr");
238 assert.strictEqual(yield* cache.get("summary", Effect.succeed("fresh"), ["pr"]), "fresh");
239 }).pipe(Effect.provide(KeyValueStore.layerMemory)),
240 );
241
242 it.effect(
243 "finishes the in-memory revision update when invalidation is canceled after writing",
244 () =>
245 Effect.gen(function* () {
246 const backing = yield* KeyValueStore.KeyValueStore;
247 const written = yield* Deferred.make<void>();
248 const release = yield* Deferred.make<void>();
249 const cache = yield* PullRequestReadCache.make.pipe(
250 Effect.provideService(KeyValueStore.KeyValueStore, {
251 ...backing,
252 set: (key, value) =>
253 backing
254 .set(key, value)
255 .pipe(
256 Effect.andThen(
257 key === "revisions"
258 ? Deferred.succeed(written, undefined).pipe(
259 Effect.andThen(Deferred.await(release)),
260 )
261 : Effect.void,
262 ),
263 ),
264 }),
265 );
266 yield* cache.get("summary", Effect.succeed("old"), ["pr"]);
267 const invalidation = yield* cache.invalidate("pr").pipe(Effect.forkChild);
268 yield* Deferred.await(written);
269 const interrupt = yield* Fiber.interrupt(invalidation).pipe(
270 Effect.forkChild({ startImmediately: true }),
271 );
272 yield* Deferred.succeed(release, undefined);
273 yield* Fiber.join(interrupt);
274 assert.strictEqual(yield* cache.get("summary", Effect.succeed("fresh"), ["pr"]), "fresh");
275 }).pipe(Effect.provide(KeyValueStore.layerMemory)),
276 );
277});