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

ProviderLatestVersions.ts

60 lines2.0 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 = (seed: Iterable<readonly [key: string, version: string | null]> = []) =>
29 Effect.gen(function* () {
30 const entries = yield* Ref.make(
31 new Map<string, Entry>(
32 Array.from(seed, ([key, version]) => [
33 key,
34 { version, expiresAt: Number.MAX_SAFE_INTEGER },
35 ]),
36 ),
37 );
38 return ProviderLatestVersions.of({
39 cached: (key, lookup, options) =>
40 Effect.gen(function* () {
41 const now = DateTime.toEpochMillis(yield* DateTime.now);
42 const existing = (yield* Ref.get(entries)).get(key);
43 if (!options?.fresh && existing && existing.expiresAt > now) return existing.version;
44 const version = yield* lookup;
45 const ttl = version === null ? MISSING_TTL : FOUND_TTL;
46 yield* Ref.update(entries, (current) =>
47 new Map(current).set(key, { version, expiresAt: now + Duration.toMillis(ttl) }),
48 );
49 return version;
50 }),
51 invalidate: (key) =>
52 Ref.update(entries, (current) => {
53 const next = new Map(current);
54 next.delete(key);
55 return next;
56 }),
57 });
58 });
59​
60export const layer = Layer.effect(ProviderLatestVersions, make());