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// Entry filenames have the store-id prefix; the scope revisions file does not.
28const STORE_ID = "pr-v2";
29const ENTRY_FILE_NAME = new RegExp(`^${STORE_ID}[0-9a-f]{64}$`);
30/**
31 * A file untouched for a day is long expired; the day only leaves slack for
32 * clock changes.
33 */
34const ENTRY_FILE_MAX_AGE = Duration.days(1);
35type ReadError = PullRequestOperationError | PullRequestUnavailableError;
36const revisionCodec = Schema.fromJsonString(
37 Schema.Record(
38 Schema.String,
39 Schema.Struct({ revision: Schema.String, expiresAt: Schema.Finite }),
40 ),
41);
42class Read extends Persistable.Class<{
43 payload: { key: string; revision: string; lookup: Effect.Effect<string, ReadError> };
44}>()("PullRequestRead", {
45 primaryKey: ({ key }) => key,
46 success: Schema.Struct({
47 payload: Schema.String,
48 expiresAt: Schema.Finite,
49 revision: Schema.optionalKey(Schema.String),
50 }),
51 error: Schema.Union([PullRequestOperationError, PullRequestUnavailableError]),
52}) {
53 matchesRevision(revision: string | undefined): boolean {
54 const stored = revision?.split(":") ?? [];
55 return this.revision
56 .split(":")
57 .every((value, index) => value === "" || value === stored[index]);
58 }
59
60 [Equal.symbol](that: unknown): boolean {
61 return that instanceof Read && that.key === this.key && that.revision === this.revision;
62 }
63 [Hash.symbol](): number {
64 return Hash.string(`${this.key}:${this.revision}`);
65 }
66}
67
68export class PullRequestReadCache extends Context.Service<
69 PullRequestReadCache,
70 {
71 readonly get: (
72 key: string,
73 lookup: Effect.Effect<string, ReadError>,
74 scopes?: ReadonlyArray<string>,
75 ) => Effect.Effect<string, ReadError>;
76 readonly invalidate: (scope: string) => Effect.Effect<void>;
77 }
78>()("t3/pullRequest/PullRequestReadCache") {}
79
80export const make = Effect.gen(function* () {
81 const backing = yield* KeyValueStore.KeyValueStore;
82 const crypto = yield* Crypto.Crypto;
83 const clock = yield* Clock.Clock;
84 let enabled = true;
85 const lock = yield* Semaphore.make(CONCURRENT_READS);
86 const digest = (key: string) =>
87 crypto.digest("SHA-256", new TextEncoder().encode(key)).pipe(Effect.map(Hex.encode));
88 const revisions = yield* Cache.makeWith(
89 () =>
90 backing
91 .get("revisions")
92 .pipe(Effect.flatMap((raw) => Schema.decodeEffect(revisionCodec)(raw ?? "{}"))),
93 {
94 capacity: 1,
95 timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.infinity : Duration.zero),
96 },
97 );
98 const timeToLive: Persistable.TimeToLiveFn<Read> = (exit) =>
99 Exit.isSuccess(exit)
100 ? Duration.millis(Math.max(0, exit.value.expiresAt - clock.currentTimeMillisUnsafe()))
101 : Duration.zero;
102 const cache = yield* PersistedCache.make(
103 (request: Read) =>
104 request.lookup.pipe(
105 Effect.map((payload) => ({
106 payload,
107 expiresAt: clock.currentTimeMillisUnsafe() + 60_000,
108 revision: request.revision,
109 })),
110 ),
111 {
112 storeId: STORE_ID,
113 timeToLive,
114 inMemoryTTL: timeToLive,
115 inMemoryCapacity: CONCURRENT_READS,
116 },
117 ).pipe(Effect.provide(Persistence.layerKvs));
118 const refreshes = yield* Cache.makeWith(
119 Effect.fn("PullRequestReadCache.refresh")(function* (request: Read) {
120 const stored = yield* cache.get(request);
121 if (request.matchesRevision(stored.revision)) return stored;
122 yield* cache.invalidate(request);
123 return yield* cache.get(request);
124 }),
125 { capacity: CONCURRENT_READS, timeToLive: () => Duration.zero },
126 );
127 return PullRequestReadCache.of({
128 get: Effect.fn("PullRequestReadCache.get")(function* (key, lookup, scopes = []) {
129 if (!enabled) return yield* lookup;
130 const read = yield* Effect.cached(lookup);
131 return yield* Effect.gen(function* () {
132 const current = yield* Cache.get(revisions, undefined);
133 const now = clock.currentTimeMillisUnsafe();
134 const revision = scopes
135 .map((scope) => {
136 const value = current[scope];
137 return value !== undefined && value.expiresAt > now ? value.revision : "";
138 })
139 .join(":");
140 const request = new Read({ key: yield* digest(key), revision, lookup: read });
141 const stored = yield* cache.get(request);
142 return (
143 request.matchesRevision(stored.revision) ? stored : yield* Cache.get(refreshes, request)
144 ).payload;
145 }).pipe(
146 Effect.catchTags({
147 PlatformError: () => read,
148 KeyValueStoreError: () => read,
149 PersistenceError: () => read,
150 SchemaError: () => read,
151 }),
152 lock.withPermits(1),
153 );
154 }),
155 invalidate: Effect.fn("PullRequestReadCache.invalidate")(
156 function* (scope) {
157 const now = clock.currentTimeMillisUnsafe();
158 const current = yield* Cache.get(revisions, undefined);
159 const next = Object.fromEntries(
160 Object.entries(current).filter(([, value]) => value.expiresAt > now),
161 );
162 next[scope] = { revision: yield* crypto.randomUUIDv4(), expiresAt: now + 60_000 };
163 const encoded = yield* Schema.encodeEffect(revisionCodec)(next);
164 yield* backing.set("revisions", encoded);
165 yield* Cache.set(revisions, undefined, next);
166 },
167 Effect.catch(() => {
168 enabled = false;
169 return Effect.logWarning("PR cache disabled after clearing failed");
170 }),
171 Effect.uninterruptible,
172 lock.withPermits(CONCURRENT_READS),
173 ),
174 });
175});
176
177/**
178 * The persisted cache drops an expired entry only when it is read again, so
179 * files for PRs nobody reopens would otherwise stay forever.
180 */
181const pruneExpiredEntryFiles = Effect.fn("PullRequestReadCache.pruneExpiredEntryFiles")(function* (
182 directory: string,
183) {
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
209export const layer = Layer.unwrap(
210 Effect.gen(function* () {
211 const config = yield* ServerConfig.ServerConfig;
212 const path = yield* Path.Path;
213 const directory = path.join(config.providerStatusCacheDir, "pull-requests");
214 return Layer.effect(PullRequestReadCache, make).pipe(
215 Layer.provide(
216 // Memoize cleanup acquisition with the store; Layer.tap runs per consumer.
217 Layer.effectDiscard(
218 forkParked(
219 pruneExpiredEntryFiles(directory).pipe(
220 Effect.catch((cause) =>
221 Effect.logWarning("Failed to prune PR cache files", { cause }),
222 ),
223 Effect.repeat(Schedule.spaced(Duration.hours(1))),
224 ),
225 ),
226 ).pipe(
227 Layer.provideMerge(KeyValueStore.layerFileSystem(directory)),
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);