@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 122 lines 4.39 KB
Raw
1 import * as agw2 from "@distilled.cloud/aws/apigatewayv2";
2 import { diffTags, normalizeTags } from "alchemy/Tags";
3 import * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import { pipe } from "effect/Function";
6 import * as Schedule from "effect/Schedule";
7
8 /**
9 * API Gateway v2 ARN helpers. Unlike most services the resource ARNs used
10 * for tagging omit the account id (`arn:aws:apigateway:{region}::/apis/{id}`).
11 */
12 export const apiArn = (region: string, apiId: string) =>
13 `arn:aws:apigateway:${region}::/apis/${apiId}`;
14
15 export const stageArn = (region: string, apiId: string, stageName: string) =>
16 `arn:aws:apigateway:${region}::/apis/${apiId}/stages/${stageName}`;
17
18 export const domainNameArn = (region: string, domainName: string) =>
19 `arn:aws:apigateway:${region}::/domainnames/${domainName}`;
20
21 export const vpcLinkArn = (region: string, vpcLinkId: string) =>
22 `arn:aws:apigateway:${region}::/vpclinks/${vpcLinkId}`;
23
24 /**
25 * The `execute-api` ARN that IAM policies (Lambda resource policies,
26 * `execute-api:Invoke`/`ManageConnections` statements) use to scope access
27 * to an API. Wildcards match across path segments.
28 */
29 export const executeApiArn = (region: string, accountId: string, apiId: string, suffix = "/*") =>
30 `arn:aws:execute-api:${region}:${accountId}:${apiId}${suffix}`;
31
32 /**
33 * `Create/Update/Delete` operations across API Gateway v2 share an
34 * account-wide throttle; parallel test suites and deploys routinely see
35 * `TooManyRequestsException` outlast the blanket SDK retry budget. The
36 * schedule below (exponential base 1s capped at 20s, 10 attempts, ~60s
37 * total) rides out the throttle window without hiding real failures.
38 *
39 * The helper carries an EXPLICIT return annotation so the conditional type
40 * of `Effect.retry` never leaks into declaration emit (which would widen the
41 * provider layer to `unknown` for every consumer of `AWS.providers()`).
42 */
43 export const retryOnTooManyRequests = <A, E extends { _tag: string }, R>(
44 effect: Effect.Effect<A, E, R>,
45 ): Effect.Effect<A, E, R> =>
46 Effect.retry(effect, {
47 while: (error: E) =>
48 error._tag === "TooManyRequestsException" || error._tag === "ConflictException",
49 schedule: Schedule.max([
50 pipe(
51 Schedule.exponential(Duration.seconds(1), 2),
52 Schedule.modifyDelay(({ duration }) =>
53 Effect.succeed(
54 Duration.isGreaterThan(duration, Duration.seconds(20))
55 ? Duration.seconds(20)
56 : duration,
57 ),
58 ),
59 ),
60 Schedule.recurs(10),
61 ]),
62 }) as Effect.Effect<A, E, R>;
63
64 /**
65 * Normalize the wire tag map (values may be `undefined`) to a plain record.
66 */
67 export const tagRecord = (
68 tags: { [key: string]: string | undefined } | undefined,
69 ): Record<string, string> =>
70 Object.fromEntries(
71 Object.entries(tags ?? {}).filter((entry): entry is [string, string] => entry[1] !== undefined),
72 );
73
74 /**
75 * API Gateway v2 collection operations (`getApis`, `getRoutes`, `getStages`,
76 * …) return `{ Items, NextToken }` pages without a Smithy pagination trait,
77 * so distilled exposes no `.pages` stream for them. Collect every page
78 * manually, bounded at 100 pages so a misbehaving token can never hang the
79 * engine.
80 */
81 export const collectAllPages = Effect.fn(function* <A, E, R>(
82 fetchPage: (
83 nextToken: string | undefined,
84 ) => Effect.Effect<{ Items?: readonly A[] | A[]; NextToken?: string }, E, R>,
85 ) {
86 const items: A[] = [];
87 let nextToken: string | undefined = undefined;
88 for (let page = 0; page < 100; page++) {
89 const result: { Items?: readonly A[] | A[]; NextToken?: string } = yield* fetchPage(nextToken);
90 items.push(...(result.Items ?? []));
91 nextToken = result.NextToken;
92 if (!nextToken) break;
93 }
94 return items;
95 });
96
97 /**
98 * Diff observed tags against desired tags and apply only the delta via the
99 * v2 `tagResource`/`untagResource` operations.
100 */
101 export const syncTags = Effect.fn(function* ({
102 resourceArn,
103 oldTags,
104 newTags,
105 }: {
106 resourceArn: string;
107 oldTags: Record<string, string>;
108 newTags: Record<string, string>;
109 }) {
110 const { removed, upsert } = diffTags(oldTags, newTags);
111 if (removed.length > 0) {
112 yield* agw2
113 .untagResource({ ResourceArn: resourceArn, TagKeys: removed })
114 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
115 }
116 if (upsert.length > 0) {
117 yield* agw2.tagResource({
118 ResourceArn: resourceArn,
119 Tags: normalizeTags(upsert),
120 });
121 }
122 });