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