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

PullRequestReadCache.ts

125 lines4.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 Encoding from "effect/Encoding";
8import * as Option from "effect/Option";
9import * as Context from "effect/Context";
10import * as Duration from "effect/Duration";
11import * as Effect from "effect/Effect";
12import * as Exit from "effect/Exit";
13import * as Layer from "effect/Layer";
14import * as Path from "effect/Path";
15import * as Schema from "effect/Schema";
16import * as Semaphore from "effect/Semaphore";
17import * as KeyValueStore from "effect/unstable/persistence/KeyValueStore";
18import * as Persistable from "effect/unstable/persistence/Persistable";
19import * as PersistedCache from "effect/unstable/persistence/PersistedCache";
20import * as Persistence from "effect/unstable/persistence/Persistence";
21import { ServerConfig } from "../config.ts";
22​
23const CONCURRENT_READS = 512;
24type ReadError = PullRequestOperationError | PullRequestUnavailableError;
25​
26class Read extends Persistable.Class<{
27 payload: { key: string; lookup: Effect.Effect<string, ReadError> };
28}>()("PullRequestRead", {
29 primaryKey: ({ key }) => key,
30 success: Schema.Struct({ payload: Schema.String, expiresAt: Schema.Finite }),
31 error: Schema.Union([PullRequestOperationError, PullRequestUnavailableError]),
32}) {
33 [Equal.symbol](that: unknown): boolean {
34 return that instanceof Read && that.key === this.key;
35 }
36 [Hash.symbol](): number {
37 return Hash.string(this.key);
38 }
40​
41export class PullRequestReadCache extends Context.Service<
42 PullRequestReadCache,
43 {
44 readonly get: (
45 key: string,
46 lookup: Effect.Effect<string, ReadError>,
47 ) => Effect.Effect<string, ReadError>;
48 readonly invalidate: Effect.Effect<void>;
49 }
50>()("t3/pullRequest/PullRequestReadCache") {}
51​
52export const make = Effect.gen(function* () {
53 const backing = yield* KeyValueStore.KeyValueStore;
54 const crypto = yield* Crypto.Crypto;
55 const clock = yield* Clock.Clock;
56 let enabled = true;
57 const lock = yield* Semaphore.make(CONCURRENT_READS);
58 const timeToLive: Persistable.TimeToLiveFn<Read> = (exit) =>
59 Exit.isSuccess(exit)
60 ? Duration.millis(Math.max(0, exit.value.expiresAt - clock.currentTimeMillisUnsafe()))
61 : Duration.zero;
62 const cache = yield* PersistedCache.make(
63 (request: Read) =>
64 request.lookup.pipe(
65 Effect.map((payload) => ({ payload, expiresAt: clock.currentTimeMillisUnsafe() + 60_000 })),
66 ),
67 {
68 storeId: "pr-v2",
69 timeToLive,
70 inMemoryTTL: timeToLive,
71 inMemoryCapacity: CONCURRENT_READS,
72 },
73 );
74 return PullRequestReadCache.of({
75 get: Effect.fn("PullRequestReadCache.get")(function* (key, lookup) {
76 if (!enabled) return yield* lookup;
77 const digest = yield* crypto
78 .digest("SHA-256", new TextEncoder().encode(key))
79 .pipe(Effect.option);
80 if (Option.isNone(digest)) return yield* lookup;
81 const read = yield* Effect.cached(lookup);
82 return yield* cache
83 .get(new Read({ key: Encoding.encodeHex(digest.value), lookup: read }))
84 .pipe(
85 Effect.map((result) => result.payload),
86 Effect.catchTags({
87 PersistenceError: () => read,
88 SchemaError: () => read,
89 }),
90 Effect.uninterruptible,
91 lock.withPermits(1),
92 );
93 }),
94 // Let existing reads finish before clearing, so they cannot repopulate stale entries.
95 invalidate: Cache.invalidateAll(cache.inMemory).pipe(
96 Effect.andThen(backing.clear),
97 Effect.catch(() => {
98 enabled = false;
99 return Effect.logWarning("PR cache disabled after clearing failed");
100 }),
101 lock.withPermits(CONCURRENT_READS),
102 ),
103 });
104});
105​
106export const layer = Layer.unwrap(
107 Effect.gen(function* () {
108 const config = yield* ServerConfig;
109 const path = yield* Path.Path;
110 return Layer.effect(PullRequestReadCache, make).pipe(
111 Layer.provide(Persistence.layerKvs),
112 Layer.provide(
113 KeyValueStore.layerFileSystem(
114 path.join(config.providerStatusCacheDir, "pull-requests"),
115 ).pipe(
116 Layer.catch(() =>
117 Layer.effectDiscard(
118 Effect.logWarning("PR cache directory unavailable; using memory cache"),
119 ).pipe(Layer.provideMerge(KeyValueStore.layerMemory)),
120 ),
121 ),
122 ),
123 );
124 }),
125);