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 Encoding from "effect/Encoding";
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 Layer from "effect/Layer";
13import * as Path from "effect/Path";
14import * as Schema from "effect/Schema";
15import * as Semaphore from "effect/Semaphore";
16import * as KeyValueStore from "effect/unstable/persistence/KeyValueStore";
17import * as Persistable from "effect/unstable/persistence/Persistable";
18import * as PersistedCache from "effect/unstable/persistence/PersistedCache";
19import * as Persistence from "effect/unstable/persistence/Persistence";
20import { ServerConfig } from "../config.ts";
21
22const CONCURRENT_READS = 512;
23type ReadError = PullRequestOperationError | PullRequestUnavailableError;
24const revisionCodec = Schema.fromJsonString(
25 Schema.Record(
26 Schema.String,
27 Schema.Struct({ revision: Schema.String, expiresAt: Schema.Finite }),
28 ),
29);
30class Read extends Persistable.Class<{
31 payload: { key: string; revision: string; lookup: Effect.Effect<string, ReadError> };
32}>()("PullRequestRead", {
33 primaryKey: ({ key }) => key,
34 success: Schema.Struct({
35 payload: Schema.String,
36 expiresAt: Schema.Finite,
37 revision: Schema.optionalKey(Schema.String),
38 }),
39 error: Schema.Union([PullRequestOperationError, PullRequestUnavailableError]),
40}) {
41 matchesRevision(revision: string | undefined): boolean {
42 const stored = revision?.split(":") ?? [];
43 return this.revision
44 .split(":")
45 .every((value, index) => value === "" || value === stored[index]);
46 }
47
48 [Equal.symbol](that: unknown): boolean {
49 return that instanceof Read && that.key === this.key && that.revision === this.revision;
50 }
51 [Hash.symbol](): number {
52 return Hash.string(`${this.key}:${this.revision}`);
53 }
54}
55
56export class PullRequestReadCache extends Context.Service<
57 PullRequestReadCache,
58 {
59 readonly get: (
60 key: string,
61 lookup: Effect.Effect<string, ReadError>,
62 scopes?: ReadonlyArray<string>,
63 ) => Effect.Effect<string, ReadError>;
64 readonly invalidate: (scope: string) => Effect.Effect<void>;
65 }
66>()("t3/pullRequest/PullRequestReadCache") {}
67
68export const make = Effect.gen(function* () {
69 const backing = yield* KeyValueStore.KeyValueStore;
70 const crypto = yield* Crypto.Crypto;
71 const clock = yield* Clock.Clock;
72 let enabled = true;
73 const lock = yield* Semaphore.make(CONCURRENT_READS);
74 const digest = (key: string) =>
75 crypto.digest("SHA-256", new TextEncoder().encode(key)).pipe(Effect.map(Encoding.encodeHex));
76 const revisions = yield* Cache.makeWith(
77 () =>
78 backing
79 .get("revisions")
80 .pipe(Effect.flatMap((raw) => Schema.decodeEffect(revisionCodec)(raw ?? "{}"))),
81 {
82 capacity: 1,
83 timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.infinity : Duration.zero),
84 },
85 );
86 const timeToLive: Persistable.TimeToLiveFn<Read> = (exit) =>
87 Exit.isSuccess(exit)
88 ? Duration.millis(Math.max(0, exit.value.expiresAt - clock.currentTimeMillisUnsafe()))
89 : Duration.zero;
90 const cache = yield* PersistedCache.make(
91 (request: Read) =>
92 request.lookup.pipe(
93 Effect.map((payload) => ({
94 payload,
95 expiresAt: clock.currentTimeMillisUnsafe() + 60_000,
96 revision: request.revision,
97 })),
98 ),
99 {
100 storeId: "pr-v2",
101 timeToLive,
102 inMemoryTTL: timeToLive,
103 inMemoryCapacity: CONCURRENT_READS,
104 },
105 ).pipe(Effect.provide(Persistence.layerKvs));
106 const refreshes = yield* Cache.makeWith(
107 Effect.fn("PullRequestReadCache.refresh")(function* (request: Read) {
108 const stored = yield* cache.get(request);
109 if (request.matchesRevision(stored.revision)) return stored;
110 yield* cache.invalidate(request);
111 return yield* cache.get(request);
112 }),
113 { capacity: CONCURRENT_READS, timeToLive: () => Duration.zero },
114 );
115 return PullRequestReadCache.of({
116 get: Effect.fn("PullRequestReadCache.get")(function* (key, lookup, scopes = []) {
117 if (!enabled) return yield* lookup;
118 const read = yield* Effect.cached(lookup);
119 return yield* Effect.gen(function* () {
120 const current = yield* Cache.get(revisions, undefined);
121 const now = clock.currentTimeMillisUnsafe();
122 const revision = scopes
123 .map((scope) => {
124 const value = current[scope];
125 return value !== undefined && value.expiresAt > now ? value.revision : "";
126 })
127 .join(":");
128 const request = new Read({ key: yield* digest(key), revision, lookup: read });
129 const stored = yield* cache.get(request);
130 return (
131 request.matchesRevision(stored.revision) ? stored : yield* Cache.get(refreshes, request)
132 ).payload;
133 }).pipe(
134 Effect.catchTags({
135 PlatformError: () => read,
136 KeyValueStoreError: () => read,
137 PersistenceError: () => read,
138 SchemaError: () => read,
139 }),
140 lock.withPermits(1),
141 );
142 }),
143 invalidate: (scope) =>
144 Effect.gen(function* () {
145 const now = clock.currentTimeMillisUnsafe();
146 const current = yield* Cache.get(revisions, undefined);
147 const next = Object.fromEntries(
148 Object.entries(current).filter(([, value]) => value.expiresAt > now),
149 );
150 next[scope] = { revision: yield* crypto.randomUUIDv4, expiresAt: now + 60_000 };
151 const encoded = yield* Schema.encodeEffect(revisionCodec)(next);
152 yield* backing.set("revisions", encoded);
153 yield* Cache.set(revisions, undefined, next);
154 }).pipe(
155 Effect.catch(() => {
156 enabled = false;
157 return Effect.logWarning("PR cache disabled after clearing failed");
158 }),
159 Effect.uninterruptible,
160 lock.withPermits(CONCURRENT_READS),
161 ),
162 });
163});
164
165export const layer = Layer.unwrap(
166 Effect.gen(function* () {
167 const config = yield* ServerConfig;
168 const path = yield* Path.Path;
169 return Layer.effect(PullRequestReadCache, make).pipe(
170 Layer.provide(
171 KeyValueStore.layerFileSystem(
172 path.join(config.providerStatusCacheDir, "pull-requests"),
173 ).pipe(
174 Layer.catch(() =>
175 Layer.effectDiscard(
176 Effect.logWarning("PR cache directory unavailable; using memory cache"),
177 ).pipe(Layer.provideMerge(KeyValueStore.layerMemory)),
178 ),
179 ),
180 ),
181 );
182 }),
183);