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

main
ts 70 lines 2.99 KB
Raw
1 import * as ce from "@distilled.cloud/aws/cost-explorer";
2 import { diffTags } from "alchemy/Tags";
3 import * as Effect from "effect/Effect";
4 import * as Schedule from "effect/Schedule";
5 import { Region } from "../Region.ts";
6
7 // Cost Explorer is a global service served exclusively from the us-east-1
8 // endpoint. Every control-plane call must target that region regardless of
9 // the ambient stack region, so we pin it on every distilled operation. The
10 // distilled Region service value is `Effect<RegionName>`, not a raw string —
11 // providing a bare string makes the client `yield*` a string and crash
12 // (same pattern as CloudFront KVS / ECR Public / WAFv2 / GlobalAccelerator).
13 export const CE_REGION = "us-east-1" as const;
14
15 // Cost Explorer's control-plane rate limits are extremely low and shared
16 // account-wide, so concurrent deploys readily trip `LimitExceededException:
17 // Rate limit exceeded`. Retry it with capped exponential backoff, bounded
18 // (~47s total) so a genuine quota LimitExceeded still surfaces quickly.
19 const ceThrottleRetrySchedule = Schedule.max([
20 Schedule.min([Schedule.exponential("1 second"), Schedule.spaced("8 seconds")]),
21 Schedule.recurs(8),
22 ]);
23
24 export const pinCe = <A, E extends { _tag: string }, R>(
25 effect: Effect.Effect<A, E, R>,
26 ): Effect.Effect<A, E, R> =>
27 effect.pipe(
28 Effect.provideService(Region, Effect.succeed(CE_REGION)),
29 Effect.retry({
30 while: (e) => e._tag === "LimitExceededException",
31 schedule: ceThrottleRetrySchedule,
32 }),
33 );
34
35 /** Convert a plain tag record to Cost Explorer's `ResourceTag` list shape. */
36 export const toResourceTags = (tags: Record<string, string>): ce.ResourceTag[] =>
37 Object.entries(tags).map(([Key, Value]) => ({ Key, Value }));
38
39 /** Convert a Cost Explorer `ResourceTag` list to a plain tag record. */
40 export const toTagRecord = (tags: readonly ce.ResourceTag[] | undefined): Record<string, string> =>
41 Object.fromEntries((tags ?? []).map((t) => [t.Key, t.Value]));
42
43 /**
44 * Fetch the observed tags for a Cost Explorer resource ARN. Tolerates the
45 * resource disappearing mid-read (`ResourceNotFoundException` → `{}`).
46 */
47 export const fetchCeTags = Effect.fn(function* (resourceArn: string) {
48 const listed = yield* pinCe(ce.listTagsForResource({ ResourceArn: resourceArn })).pipe(
49 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed({ ResourceTags: [] })),
50 );
51 return toTagRecord(listed.ResourceTags);
52 });
53
54 /**
55 * Sync the tags on a Cost Explorer resource: diff the OBSERVED cloud tags
56 * against the desired set and apply only the delta.
57 */
58 export const syncCeTags = Effect.fn(function* (
59 resourceArn: string,
60 desiredTags: Record<string, string>,
61 ) {
62 const observedTags = yield* fetchCeTags(resourceArn);
63 const { upsert, removed } = diffTags(observedTags, desiredTags);
64 if (upsert.length > 0) {
65 yield* pinCe(ce.tagResource({ ResourceArn: resourceArn, ResourceTags: upsert }));
66 }
67 if (removed.length > 0) {
68 yield* pinCe(ce.untagResource({ ResourceArn: resourceArn, ResourceTagKeys: removed }));
69 }
70 });