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

ProviderLatestVersions.ts

62 lines2.2 KB

1import * as Context from "effect/Context";
2import * as DateTime from "effect/DateTime";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Ref from "effect/Ref";
7​
8const FOUND_TTL = Duration.hours(1);
9const MISSING_TTL = Duration.minutes(1);
10​
11interface Entry {
12 readonly expiresAt: number;
13 readonly version: string | null;
15​
16export class ProviderLatestVersions extends Context.Service<
17 ProviderLatestVersions,
18 {
19 readonly cached: <E, R>(
20 key: string,
21 lookup: Effect.Effect<string | null, E, R>,
22 options?: { readonly fresh?: boolean },
23 ) => Effect.Effect<string | null, E, R>;
24 readonly invalidate: (key: string) => Effect.Effect<void>;
25 }
26>()("@t3tools/provider-core/server/ProviderLatestVersions") {}
27​
28export const make = Effect.fn("ProviderLatestVersions.make")(function* (
29 seed: Iterable<readonly [key: string, version: string | null]> = [],
30) {
31 const entries = yield* Ref.make(
32 new Map<string, Entry>(
33 Array.from(seed, ([key, version]) => [key, { version, expiresAt: Number.MAX_SAFE_INTEGER }]),
34 ),
35 );
36 return ProviderLatestVersions.of({
37 cached: Effect.fn("ProviderLatestVersions.cached")(function* (key, lookup, options) {
38 const now = DateTime.toEpochMillis(yield* DateTime.now);
39 const existing = (yield* Ref.get(entries)).get(key);
40 if (!options?.fresh && existing && existing.expiresAt > now) return existing.version;
41 // Replacing or invalidating this entry retires any lookup still in flight.
42 const pending = { version: null, expiresAt: 0 };
43 yield* Ref.update(entries, (current) => new Map(current).set(key, pending));
44 const version = yield* lookup;
45 const ttl = version === null ? MISSING_TTL : FOUND_TTL;
46 yield* Ref.update(entries, (current) =>
47 current.get(key) === pending
48 ? new Map(current).set(key, { version, expiresAt: now + Duration.toMillis(ttl) })
49 : current,
50 );
51 return version;
52 }),
53 invalidate: (key) =>
54 Ref.update(entries, (current) => {
55 const next = new Map(current);
56 next.delete(key);
57 return next;
58 }),
59 });
60});
61​
62export const layer = Layer.effect(ProviderLatestVersions, make());