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("resumes caching after a failed scope read", () =>
127 Effect.gen(function* () {
128 const backing = yield* KeyValueStore.KeyValueStore;
129 let fail = true;
130 let reads = 0;
131 const cache = yield* PullRequestReadCache.make.pipe(
132 Effect.provideService(KeyValueStore.KeyValueStore, {
133 ...backing,
134 get: (key) =>
135 Effect.suspend(() => {
136 if (!fail) return backing.get(key);
137 fail = false;
138 return Effect.fail(
139 new KeyValueStore.KeyValueStoreError({ method: "get", message: "unavailable" }),
140 );
141 }),
142 }),
143 );
144 const read = cache.get(
145 "summary",
146 Effect.sync(() => String(++reads)),
147 ["pr"],
148 );
149 assert.strictEqual(yield* read, "1");
150 assert.strictEqual(yield* read, "2");
151 assert.strictEqual(yield* read, "2");
152 }).pipe(Effect.provide(KeyValueStore.layerMemory)),
153 );
154
155 it.effect("does not keep a caller's data alive after its reads and invalidations", () =>
156 Effect.gen(function* () {
157 const cache = yield* PullRequestReadCache.make;
158 const sweeps: Array<WeakRef<object>> = [];
159 // Like a sync sweep: an Effect.fn made per run that closes over that run's data.
160 const sweep = Effect.fn("sweep")(function* (index: number) {
161 const groups = new Map<string, number>(
162 Array.from({ length: 1_000 }, (_, id) => [`group-${id}`, id]),
163 );
164 sweeps.push(new WeakRef(groups));
165 const read = Effect.fn("read")(function* (pr: string) {
166 const size = groups.size;
167 yield* cache.invalidate(pr);
168 const answer = yield* cache.get(`${pr}-${index}`, Effect.succeed("answer"), [pr]);
169 return size + answer.length;
170 });
171 yield* Effect.forEach(["pr-1", "pr-2"], read, { discard: true });
172 });
173 for (let index = 0; index < 5; index++) yield* sweep(index);
174 // WeakRef targets stay alive until the current job ends, so yield before collecting.
175 yield* Effect.yieldNow;
176 collectGarbage();
177 assert.strictEqual(sweeps.filter((sweepData) => sweepData.deref() !== undefined).length, 0);
178 }).pipe(Effect.provide(KeyValueStore.layerMemory)),
179 );
180
181 it.effect("cancels abandoned reads without blocking invalidation", () =>
182 Effect.gen(function* () {
183 const cache = yield* PullRequestReadCache.make;
184 const started = yield* Deferred.make<void>();
185 const read = yield* cache
186 .get("summary", Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never)), [
187 "pr",
188 ])
189 .pipe(Effect.forkChild);
190 yield* Deferred.await(started);
191 yield* Fiber.interrupt(read);
192 yield* cache.invalidate("pr");
193 assert.strictEqual(yield* cache.get("summary", Effect.succeed("fresh"), ["pr"]), "fresh");
194 }).pipe(Effect.provide(KeyValueStore.layerMemory)),
195 );
196
197 it.effect(
198 "finishes the in-memory revision update when invalidation is canceled after writing",
199 () =>
200 Effect.gen(function* () {
201 const backing = yield* KeyValueStore.KeyValueStore;
202 const written = yield* Deferred.make<void>();
203 const release = yield* Deferred.make<void>();
204 const cache = yield* PullRequestReadCache.make.pipe(
205 Effect.provideService(KeyValueStore.KeyValueStore, {
206 ...backing,
207 set: (key, value) =>
208 backing
209 .set(key, value)
210 .pipe(
211 Effect.andThen(
212 key === "revisions"
213 ? Deferred.succeed(written, undefined).pipe(
214 Effect.andThen(Deferred.await(release)),
215 )
216 : Effect.void,
217 ),
218 ),
219 }),
220 );
221 yield* cache.get("summary", Effect.succeed("old"), ["pr"]);
222 const invalidation = yield* cache.invalidate("pr").pipe(Effect.forkChild);
223 yield* Deferred.await(written);
224 const interrupt = yield* Fiber.interrupt(invalidation).pipe(
225 Effect.forkChild({ startImmediately: true }),
226 );
227 yield* Deferred.succeed(release, undefined);
228 yield* Fiber.join(interrupt);
229 assert.strictEqual(yield* cache.get("summary", Effect.succeed("fresh"), ["pr"]), "fresh");
230 }).pipe(Effect.provide(KeyValueStore.layerMemory)),
231 );
232});