@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 178 lines 6.68 KB
Raw
1 import * as ag from "@distilled.cloud/aws/api-gateway";
2 import * as Retry from "@distilled.cloud/aws/Retry";
3 import { diffTags, normalizeTags } from "alchemy/Tags";
4 import * as Data from "effect/Data";
5 import * as Effect from "effect/Effect";
6 import * as Schedule from "effect/Schedule";
7 import * as Semaphore from "effect/Semaphore";
8
9 /**
10 * API Gateway serializes mutations to a single RestApi at the control-plane
11 * level: while the API is transitioning between states it responds with a
12 * `BadRequestException` whose message matches one of:
13 *
14 * - `You cannot deploy a RestApi while the apiStatus is UPDATING or FAILED.`
15 * - `There is already an update in progress.`
16 *
17 * These are fundamentally transient — the retry window is short (seconds)
18 * and the only correct response is to wait and try again. Because the
19 * exception is a 4xx, the generic `Retry.transient` policy applied to the
20 * AWS SDK will not retry it, so we apply a targeted retry here for
21 * operations that race with concurrent mutations on the same RestApi
22 * (typically `createDeployment`, `updateStage`, `deleteStage`).
23 */
24 const isApiStatusUpdatingError = (error: unknown): boolean => {
25 if (!error || typeof error !== "object") return false;
26 if ((error as { _tag?: string })._tag !== "BadRequestException") return false;
27 const message = (error as { message?: string }).message ?? "";
28 return (
29 message.includes("apiStatus is UPDATING") || message.includes("already an update in progress")
30 );
31 };
32
33 /**
34 * Schedule for API Gateway's transient API-status conflicts. Throttling is
35 * deliberately not retried here: the shared AWS client policy already has a
36 * bounded, capped retry window long enough to cross API Gateway's ~30-second
37 * mutation quota. Retrying throttling again at this layer would nest the two
38 * policies and turn one operation into a many-minute wait.
39 */
40 const apiGatewayMutationSchedule = Schedule.max([
41 Schedule.spaced("5 seconds"),
42 Schedule.recurs(10),
43 ]);
44
45 /**
46 * Wraps an API Gateway mutation so that recoverable 4xx responses are
47 * retried with backoff:
48 *
49 * - `BadRequestException` with `apiStatus is UPDATING` or
50 * `already an update in progress` (transient, clears in seconds)
51 *
52 * Drop-in usage:
53 *
54 * ```ts
55 * yield* retryOnApiStatusUpdating(
56 * ag.createDeployment({ ... }),
57 * );
58 * ```
59 */
60 export const retryOnApiStatusUpdating = <A, E, R>(
61 effect: Effect.Effect<A, E, R>,
62 ): Effect.Effect<A, E, R> =>
63 Effect.retry(effect, {
64 schedule: apiGatewayMutationSchedule,
65 while: isApiStatusUpdatingError,
66 }) as Effect.Effect<A, E, R>;
67
68 const isRestApiDeleteRetryable = (error: unknown): boolean => {
69 if (!error || typeof error !== "object") return false;
70 const tagged = error as { _tag?: string; message?: string };
71 return (
72 tagged._tag === "TooManyRequestsException" ||
73 tagged._tag === "ConflictException" ||
74 (tagged._tag === "BadRequestException" &&
75 (tagged.message?.includes("apiStatus is UPDATING") === true ||
76 tagged.message?.includes("already an update in progress") === true))
77 );
78 };
79
80 // DeleteRestApi has its own unusually low regional quota (roughly one request
81 // every 30 seconds). Override the blanket AWS retry layer for this operation:
82 // otherwise its 5-second-capped budget expires after about a minute, and then
83 // wrapping that exhausted call in another retry schedule creates an opaque,
84 // nested multi-minute wait. This is one explicit 90-second wall instead.
85 const restApiDeleteSchedule = Schedule.max([Schedule.spaced("5 seconds"), Schedule.recurs(18)]);
86
87 class RestApiStillExists extends Data.TaggedError("RestApiStillExists")<{
88 readonly restApiId: string;
89 }> {}
90
91 const restApiGoneSchedule = Schedule.max([Schedule.spaced("1 second"), Schedule.recurs(8)]);
92
93 // DeleteRestApi's ~1-per-30s quota is ACCOUNT-wide, so concurrent destroys
94 // (parallel test files, parallel stacks in one process) all contend for the
95 // same token — each one's individual retry wall can expire while the others
96 // keep winning the race. Serialize deletes process-wide so each waiter only
97 // contends with the quota window itself, never with its siblings.
98 const restApiDeleteMutex = Semaphore.makeUnsafe(1);
99
100 /**
101 * Idempotently delete a REST API and observe it disappear.
102 *
103 * Every provider/test cleanup path uses this helper so nuke, normal destroy,
104 * and interrupted-run reapers all share the same bounded throttle handling.
105 */
106 export const deleteRestApiAndWait = Effect.fn(function* (restApiId: string) {
107 yield* ag.deleteRestApi({ restApiId }).pipe(
108 Retry.policy({
109 while: isRestApiDeleteRetryable,
110 schedule: restApiDeleteSchedule,
111 }),
112 Effect.catchTag("NotFoundException", () => Effect.void),
113 Semaphore.withPermits(restApiDeleteMutex, 1),
114 );
115
116 // Avoid nesting the account-wide AWS retry policy inside the observable
117 // poll. Each getRestApi is single-shot; this one bounded schedule owns both
118 // throttled reads and the short eventual-consistency window.
119 const observe = Retry.none(ag.getRestApi({ restApiId }));
120 yield* observe.pipe(
121 Effect.flatMap(() => Effect.fail(new RestApiStillExists({ restApiId }))),
122 Effect.retry({
123 while: (error) =>
124 error._tag === "TooManyRequestsException" || error._tag === "RestApiStillExists",
125 schedule: restApiGoneSchedule,
126 }),
127 Effect.catchTag("NotFoundException", () => Effect.void),
128 );
129 });
130
131 export const restApiArn = (region: string, restApiId: string) =>
132 `arn:aws:apigateway:${region}::/restapis/${restApiId}`;
133
134 export const stageArn = (region: string, restApiId: string, stageName: string) =>
135 `arn:aws:apigateway:${region}::/restapis/${restApiId}/stages/${stageName}`;
136
137 export const apiKeyArn = (region: string, apiKeyId: string) =>
138 `arn:aws:apigateway:${region}::/apikeys/${apiKeyId}`;
139
140 export const usagePlanArn = (region: string, usagePlanId: string) =>
141 `arn:aws:apigateway:${region}::/usageplans/${usagePlanId}`;
142
143 export const domainNameArn = (region: string, domainName: string) =>
144 `arn:aws:apigateway:${region}::/domainnames/${domainName}`;
145
146 export const vpcLinkArn = (region: string, vpcLinkId: string) =>
147 `arn:aws:apigateway:${region}::/vpclinks/${vpcLinkId}`;
148
149 export const syncTags = Effect.fn(function* ({
150 resourceArn,
151 oldTags,
152 newTags,
153 }: {
154 resourceArn: string;
155 oldTags: Record<string, string>;
156 newTags: Record<string, string>;
157 }) {
158 const { removed, upsert } = diffTags(oldTags, newTags);
159 if (removed.length > 0) {
160 yield* ag
161 .untagResource({
162 resourceArn,
163 tagKeys: removed,
164 })
165 .pipe(
166 Effect.catchTags({
167 NotFoundException: () => Effect.void,
168 BadRequestException: () => Effect.void,
169 }),
170 );
171 }
172 if (upsert.length > 0) {
173 yield* ag.tagResource({
174 resourceArn,
175 tags: normalizeTags(upsert),
176 });
177 }
178 });