@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 49 lines 1.61 KB
Raw
1 import * as Cache from "effect/Cache";
2 import * as Clock from "effect/Clock";
3 import * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import * as Exit from "effect/Exit";
6
7 /**
8 * Refresh expiring credentials this long before they actually expire so that
9 * in-flight requests never race the expiry deadline.
10 */
11 export const CREDENTIAL_REFRESH_WINDOW = Duration.minutes(5);
12
13 /** Compute how long credentials may remain cached. */
14 export const credentialTimeToLive = (
15 expiresAt: number | undefined,
16 resolvedAt: number,
17 ): Duration.Duration => {
18 if (expiresAt === undefined) return Duration.infinity;
19 return Duration.millis(
20 Math.max(0, expiresAt - resolvedAt - Duration.toMillis(CREDENTIAL_REFRESH_WINDOW)),
21 );
22 };
23
24 /**
25 * Build a single-entry Effect cache whose TTL is derived from each resolved
26 * credential's expiry. Concurrent cache misses share one resolution.
27 */
28 export const cacheUntilExpiry = <A, E>(
29 resolve: Effect.Effect<A, E>,
30 expiresAt: (credentials: A) => number | undefined,
31 ) =>
32 Effect.gen(function* () {
33 const cache = yield* Cache.makeWith(
34 () =>
35 Effect.gen(function* () {
36 const resolvedAt = yield* Clock.currentTimeMillis;
37 const credentials = yield* resolve;
38 return { credentials, resolvedAt };
39 }),
40 {
41 capacity: 1,
42 timeToLive: (exit) =>
43 Exit.isSuccess(exit)
44 ? credentialTimeToLive(expiresAt(exit.value.credentials), exit.value.resolvedAt)
45 : Duration.zero,
46 },
47 );
48 return Cache.get(cache, undefined).pipe(Effect.map(({ credentials }) => credentials));
49 });