@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, 06:00 UTC

main
ts 64 lines 2.55 KB
Raw
1 import * as kvs from "@distilled.cloud/aws/cloudfront-keyvaluestore";
2 import { Region as AwsRegion } from "@distilled.cloud/aws/Region";
3 import * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import * as Redacted from "effect/Redacted";
6 import * as Schedule from "effect/Schedule";
7
8 // CloudFront KeyValueStore APIs are only available from us-east-1, even when
9 // the distribution using the store lives elsewhere.
10 export const KVS_REGION = "us-east-1" as const;
11
12 export const extractValue = (v: string | Redacted.Redacted<string>): string =>
13 typeof v === "string" ? v : Redacted.value(v);
14
15 export const withKvsRegion = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
16 // The distilled Region service value is `Effect<RegionName>`, not a raw
17 // string — providing a bare string makes the client `yield*` a string and
18 // crash. Wrap in Effect.succeed (same as ACM/ECRPublic/WAFv2/GlobalAccelerator).
19 effect.pipe(Effect.provideService(AwsRegion, Effect.succeed(KVS_REGION)));
20
21 export const withKvsRegionFn =
22 <Args extends any[], A, E, R>(fn: (...args: Args) => Effect.Effect<A, E, R>) =>
23 (...args: Args) =>
24 withKvsRegion(fn(...args));
25
26 const isKvsNotReady = (error: unknown) => {
27 const tag = (error as { _tag?: string })._tag;
28 return tag === "ResourceNotFoundException" || tag === "ConflictException";
29 };
30
31 /**
32 * Bounded KVS retry: exponential backoff with the per-attempt delay capped
33 * at 2s and at most 24 recurrences (~45s worst case). NEVER use a bare
34 * `Schedule.max([Schedule.exponential(...), Schedule.recurs(n)])` for KVS
35 * retries — `recurs` bounds the COUNT, not the TIME, and an uncapped
36 * exponential makes the tail attempts wait minutes-to-hours (24 attempts
37 * at 100ms doubling total ~19 days), which reads as a silent hang.
38 */
39 export const cappedKvsRetrySchedule = Schedule.max([
40 Schedule.exponential("100 millis"),
41 Schedule.recurs(24),
42 ]).pipe(
43 Schedule.modifyDelay(({ duration }) =>
44 Effect.succeed(
45 Duration.isGreaterThan(duration, Duration.seconds(2)) ? Duration.seconds(2) : duration,
46 ),
47 ),
48 );
49
50 export const retryForKvsReadiness = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
51 effect.pipe(
52 Effect.retry({
53 while: isKvsNotReady,
54 schedule: cappedKvsRetrySchedule,
55 }),
56 );
57
58 export const getKvsEtag = Effect.fn(function* (store: string) {
59 const response = yield* kvs.describeKeyValueStore({ KvsARN: store });
60 return response.ETag;
61 });
62
63 export const isKvsPreconditionFailed = (err: kvs.ValidationException) =>
64 typeof err.message === "string" && err.message.includes("Pre-Condition failed");