Open History to see the last commit
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 { forkParked } from "../serverActivation.ts";
25
26const CONCURRENT_READS = 512;
27// Persistence prefixes every entry key with the store id, so each entry file
28// name starts with it. 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 */
35export const 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 }
67}
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
92 .get("revisions")
93 .pipe(Effect.flatMap((raw) => Schema.decodeEffect(revisionCodec)(raw ?? "{}"))),
94 {
95 capacity: 1,
96 timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.infinity : Duration.zero),
97 },
98 );
99 const timeToLive: Persistable.TimeToLiveFn<Read> = (exit) =>
100 Exit.isSuccess(exit)
101 ? Duration.millis(Math.max(0, exit.value.expiresAt - clock.currentTimeMillisUnsafe()))
102 : Duration.zero;
103 const cache = yield* PersistedCache.make(
104 (request: Read) =>
105 request.lookup.pipe(
106 Effect.map((payload) => ({
107 payload,
108 expiresAt: clock.currentTimeMillisUnsafe() + 60_000,
109 revision: request.revision,
110 })),
111 ),
112 {
113 storeId: STORE_ID,
114 timeToLive,
115 inMemoryTTL: timeToLive,
116 inMemoryCapacity: CONCURRENT_READS,
117 },
118 ).pipe(Effect.provide(Persistence.layerKvs));
119 const refreshes = yield* Cache.makeWith(
120 Effect.fn("PullRequestReadCache.refresh")(function* (request: Read) {
121 const stored = yield* cache.get(request);
122 if (request.matchesRevision(stored.revision)) return stored;
123 yield* cache.invalidate(request);
124 return yield* cache.get(request);
125 }),
126 { capacity: CONCURRENT_READS, timeToLive: () => Duration.zero },
127 );
128 return PullRequestReadCache.of({
129 get: Effect.fn("PullRequestReadCache.get")(function* (key, lookup, scopes = []) {
130 if (!enabled) return yield* lookup;
131 const read = yield* Effect.cached(lookup);
132 return yield* Effect.gen(function* () {
133 const current = yield* Cache.get(revisions, undefined);
134 const now = clock.currentTimeMillisUnsafe();
135 const revision = scopes
136 .map((scope) => {
137 const value = current[scope];
138 return value !== undefined && value.expiresAt > now ? value.revision : "";
139 })
140 .join(":");
141 const request = new Read({ key: yield* digest(key), revision, lookup: read });
142 const stored = yield* cache.get(request);
143 return (
144 request.matchesRevision(stored.revision) ? stored : yield* Cache.get(refreshes, request)
145 ).payload;
146 }).pipe(
147 Effect.catchTags({
148 PlatformError: () => read,
149 KeyValueStoreError: () => read,
150 PersistenceError: () => read,
151 SchemaError: () => read,
152 }),
153 lock.withPermits(1),
154 );
155 }),
156 invalidate: (scope) =>
157 Effect.gen(function* () {
158 const now = clock.currentTimeMillisUnsafe();
159 const current = yield* Cache.get(revisions, undefined);
160 const next = Object.fromEntries(
161 Object.entries(current).filter(([, value]) => value.expiresAt > now),
162 );
163 next[scope] = { revision: yield* crypto.randomUUIDv4(), expiresAt: now + 60_000 };
164 const encoded = yield* Schema.encodeEffect(revisionCodec)(next);
165 yield* backing.set("revisions", encoded);
166 yield* Cache.set(revisions, undefined, next);
167 }).pipe(
168 Effect.catch(() => {
169 enabled = false;
170 return Effect.logWarning("PR cache disabled after clearing failed");
171 }),
172 Effect.uninterruptible,
173 lock.withPermits(CONCURRENT_READS),
174 ),
175 });
176});
177
178/**
179 * The persisted cache drops an expired entry only when it is read again, so
180 * files for PRs nobody reopens would otherwise stay forever.
181 */
182export const pruneExpiredEntryFiles = Effect.fn("PullRequestReadCache.pruneExpiredEntryFiles")(
183 function* (directory: string) {
184 const fileSystem = yield* FileSystem.FileSystem;
185 const path = yield* Path.Path;
186 const cutoff = (yield* Clock.currentTimeMillis) - Duration.toMillis(ENTRY_FILE_MAX_AGE);
187 const entries = (yield* fileSystem.readDirectory(directory)).filter((name) =>
188 ENTRY_FILE_NAME.test(name),
189 );
190 const [, failures] = yield* Effect.partition(entries, (name) => {
191 const entryPath = path.join(directory, name);
192 return fileSystem.stat(entryPath).pipe(
193 Effect.flatMap((info) =>
194 Option.exists(info.mtime, (mtime) => mtime.getTime() < cutoff)
195 ? fileSystem.remove(entryPath)
196 : Effect.void,
197 ),
198 Effect.catchReason("PlatformError", "NotFound", () => Effect.void),
199 );
200 });
201 if (failures.length > 0) {
202 yield* Effect.logWarning("Failed to prune some PR cache files", {
203 failed: failures.length,
204 cause: failures[0],
205 });
206 }
207 },
208);
209
210export const layer = Layer.unwrap(
211 Effect.gen(function* () {
212 const config = yield* ServerConfig.ServerConfig;
213 const path = yield* Path.Path;
214 const directory = path.join(config.providerStatusCacheDir, "pull-requests");
215 return Layer.effect(PullRequestReadCache, make).pipe(
216 Layer.provide(
217 KeyValueStore.layerFileSystem(directory).pipe(
218 Layer.tap(() =>
219 forkParked(
220 pruneExpiredEntryFiles(directory).pipe(
221 Effect.catch((cause) =>
222 Effect.logWarning("Failed to prune PR cache files", { cause }),
223 ),
224 Effect.repeat(Schedule.spaced(Duration.hours(1))),
225 ),
226 ),
227 ),
228 Layer.catch(() =>
229 Layer.effectDiscard(
230 Effect.logWarning("PR cache directory unavailable; using memory cache"),
231 ).pipe(Layer.provideMerge(KeyValueStore.layerMemory)),
232 ),
233 ),
234 ),
235 );
236 }),
237);