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

PullRequestReadCache.ts

249 lines9.4 KB

1import * as Cache from "effect/Cache";
2import * as Clock from "effect/Clock";
3import * as Equal from "effect/Equal";
4import * as Hash from "effect/Hash";
5import { PullRequestOperationError, PullRequestUnavailableError } from "@t3tools/contracts";
6import * as Crypto from "effect/Crypto";
7import * as Hex from "effect/encoding/Hex";
8import * as Context from "effect/Context";
9import * as Duration from "effect/Duration";
10import * as Effect from "effect/Effect";
11import * as Exit from "effect/Exit";
12import * as FileSystem from "effect/FileSystem";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as Path from "effect/Path";
16import * as Schedule from "effect/Schedule";
17import * as Schema from "effect/Schema";
18import * as Semaphore from "effect/Semaphore";
19import * as KeyValueStore from "effect/persistence/KeyValueStore";
20import * as Persistable from "effect/persistence/Persistable";
21import * as PersistedCache from "effect/persistence/PersistedCache";
22import * as Persistence from "effect/persistence/Persistence";
23import * as ServerConfig from "../config.ts";
24import { detachStackFrame } from "../git/detachStackFrame.ts";
25import { forkParked } from "../serverActivation.ts";
26​
27const CONCURRENT_READS = 512;
28// Entry filenames have the store-id prefix; the scope revisions file does not.
29const STORE_ID = "pr-v2";
30const ENTRY_FILE_NAME = new RegExp(`^${STORE_ID}[0-9a-f]{64}$`);
31/**
32 * A file untouched for a day is long expired; the day only leaves slack for
33 * clock changes.
34 */
35const ENTRY_FILE_MAX_AGE = Duration.days(1);
36type ReadError = PullRequestOperationError | PullRequestUnavailableError;
37const revisionCodec = Schema.fromJsonString(
38 Schema.Record(
39 Schema.String,
40 Schema.Struct({ revision: Schema.String, expiresAt: Schema.Finite }),
41 ),
42);
43class Read extends Persistable.Class<{
44 payload: { key: string; revision: string; lookup: Effect.Effect<string, ReadError> };
45}>()("PullRequestRead", {
46 primaryKey: ({ key }) => key,
47 success: Schema.Struct({
48 payload: Schema.String,
49 expiresAt: Schema.Finite,
50 revision: Schema.optionalKey(Schema.String),
51 }),
52 error: Schema.Union([PullRequestOperationError, PullRequestUnavailableError]),
53}) {
54 matchesRevision(revision: string | undefined): boolean {
55 const stored = revision?.split(":") ?? [];
56 return this.revision
57 .split(":")
58 .every((value, index) => value === "" || value === stored[index]);
59 }
60​
61 [Equal.symbol](that: unknown): boolean {
62 return that instanceof Read && that.key === this.key && that.revision === this.revision;
63 }
64 [Hash.symbol](): number {
65 return Hash.string(`${this.key}:${this.revision}`);
66 }
68​
69export class PullRequestReadCache extends Context.Service<
70 PullRequestReadCache,
71 {
72 readonly get: (
73 key: string,
74 lookup: Effect.Effect<string, ReadError>,
75 scopes?: ReadonlyArray<string>,
76 ) => Effect.Effect<string, ReadError>;
77 readonly invalidate: (scope: string) => Effect.Effect<void>;
78 }
79>()("t3/pullRequest/PullRequestReadCache") {}
80​
81export const make = Effect.gen(function* () {
82 const backing = yield* KeyValueStore.KeyValueStore;
83 const crypto = yield* Crypto.Crypto;
84 const clock = yield* Clock.Clock;
85 let enabled = true;
86 const lock = yield* Semaphore.make(CONCURRENT_READS);
87 const digest = (key: string) =>
88 crypto.digest("SHA-256", new TextEncoder().encode(key)).pipe(Effect.map(Hex.encode));
89 const revisions = yield* Cache.makeWith(
90 () =>
91 backing.get("revisions").pipe(
92 Effect.flatMap((raw) => Schema.decodeEffect(revisionCodec)(raw ?? "{}")),
93 Effect.catchTags({
94 SchemaError: Effect.fn("PullRequestReadCache.recoverRevisions")(function* () {
95 // Without scope revisions, persisted PR entries cannot be trusted.
96 yield* backing.clear;
97 yield* Effect.logWarning("PR cache reset after invalid scope revisions");
98 return yield* Schema.decodeEffect(revisionCodec)("{}");
99 }),
100 }),
101 ),
102 {
103 capacity: 1,
104 timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.infinity : Duration.zero),
105 },
106 );
107 const timeToLive: Persistable.TimeToLiveFn<Read> = (exit) =>
108 Exit.isSuccess(exit)
109 ? Duration.millis(Math.max(0, exit.value.expiresAt - clock.currentTimeMillisUnsafe()))
110 : Duration.zero;
111 const cache = yield* PersistedCache.make(
112 (request: Read) =>
113 request.lookup.pipe(
114 Effect.map((payload) => ({
115 payload,
116 expiresAt: clock.currentTimeMillisUnsafe() + 60_000,
117 revision: request.revision,
118 })),
119 ),
120 {
121 storeId: STORE_ID,
122 timeToLive,
123 inMemoryTTL: timeToLive,
124 inMemoryCapacity: CONCURRENT_READS,
125 },
126 ).pipe(Effect.provide(Persistence.layerKvs));
127 const refreshes = yield* Cache.makeWith(
128 Effect.fn("PullRequestReadCache.refresh")(function* (request: Read) {
129 const stored = yield* cache.get(request);
130 if (request.matchesRevision(stored.revision)) return stored;
131 yield* cache.invalidate(request);
132 return yield* cache.get(request);
133 }),
134 { capacity: CONCURRENT_READS, timeToLive: () => Duration.zero },
135 );
136 // A cache entry keeps the fiber that filled it, whose lazy stack frames would keep the caller's
137 // data (e.g. a whole sync sweep) alive until eviction.
138 return PullRequestReadCache.of({
139 get: Effect.fn("PullRequestReadCache.get")(function* (key, lookup, scopes = []) {
140 if (!enabled) return yield* lookup;
141 const read = yield* Effect.cached(lookup);
142 return yield* Effect.gen(function* () {
143 const current = yield* Cache.get(revisions, undefined);
144 const now = clock.currentTimeMillisUnsafe();
145 const revision = scopes
146 .map((scope) => {
147 const value = current[scope];
148 return value !== undefined && value.expiresAt > now ? value.revision : "";
149 })
150 .join(":");
151 const request = new Read({ key: yield* digest(key), revision, lookup: read });
152 const stored = yield* cache.get(request);
153 return (
154 request.matchesRevision(stored.revision) ? stored : yield* Cache.get(refreshes, request)
155 ).payload;
156 }).pipe(
157 Effect.catchTags({
158 PlatformError: () => read,
159 KeyValueStoreError: () => read,
160 PersistenceError: () => read,
161 SchemaError: () => read,
162 }),
163 lock.withPermits(1),
164 );
165 }, detachStackFrame),
166 invalidate: Effect.fn("PullRequestReadCache.invalidate")(
167 function* (scope) {
168 const now = clock.currentTimeMillisUnsafe();
169 const current = yield* Cache.get(revisions, undefined);
170 const next = Object.fromEntries(
171 Object.entries(current).filter(([, value]) => value.expiresAt > now),
172 );
173 next[scope] = { revision: yield* crypto.randomUUIDv4(), expiresAt: now + 60_000 };
174 const encoded = yield* Schema.encodeEffect(revisionCodec)(next);
175 yield* backing.set("revisions", encoded);
176 yield* Cache.set(revisions, undefined, next);
177 },
178 Effect.catch(() => {
179 enabled = false;
180 return Effect.logWarning("PR cache disabled after clearing failed");
181 }),
182 Effect.uninterruptible,
183 lock.withPermits(CONCURRENT_READS),
184 detachStackFrame,
185 ),
186 });
187});
188​
189/**
190 * The persisted cache drops an expired entry only when it is read again, so
191 * files for PRs nobody reopens would otherwise stay forever.
192 */
193const pruneExpiredEntryFiles = Effect.fn("PullRequestReadCache.pruneExpiredEntryFiles")(function* (
194 directory: string,
195) {
196 const fileSystem = yield* FileSystem.FileSystem;
197 const path = yield* Path.Path;
198 const cutoff = (yield* Clock.currentTimeMillis) - Duration.toMillis(ENTRY_FILE_MAX_AGE);
199 const entries = (yield* fileSystem.readDirectory(directory)).filter((name) =>
200 ENTRY_FILE_NAME.test(name),
201 );
202 const [, failures] = yield* Effect.partition(entries, (name) => {
203 const entryPath = path.join(directory, name);
204 return fileSystem.stat(entryPath).pipe(
205 Effect.flatMap((info) =>
206 Option.exists(info.mtime, (mtime) => mtime.getTime() < cutoff)
207 ? fileSystem.remove(entryPath)
208 : Effect.void,
209 ),
210 Effect.catchReason("PlatformError", "NotFound", () => Effect.void),
211 );
212 });
213 if (failures.length > 0) {
214 yield* Effect.logWarning("Failed to prune some PR cache files", {
215 failed: failures.length,
216 cause: failures[0],
217 });
218 }
219});
220​
221export const layer = Layer.unwrap(
222 Effect.gen(function* () {
223 const config = yield* ServerConfig.ServerConfig;
224 const path = yield* Path.Path;
225 const directory = path.join(config.providerStatusCacheDir, "pull-requests");
226 return Layer.effect(PullRequestReadCache, make).pipe(
227 Layer.provide(
228 // Memoize cleanup acquisition with the store; Layer.tap runs per consumer.
229 Layer.effectDiscard(
230 forkParked(
231 pruneExpiredEntryFiles(directory).pipe(
232 Effect.catch((cause) =>
233 Effect.logWarning("Failed to prune PR cache files", { cause }),
234 ),
235 Effect.repeat(Schedule.spaced(Duration.hours(1))),
236 ),
237 ),
238 ).pipe(
239 Layer.provideMerge(KeyValueStore.layerFileSystem(directory)),
240 Layer.catch(() =>
241 Layer.effectDiscard(
242 Effect.logWarning("PR cache directory unavailable; using memory cache"),
243 ).pipe(Layer.provideMerge(KeyValueStore.layerMemory)),
244 ),
245 ),
246 ),
247 );
248 }),
249);