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

main
ts 96 lines 3.5 KB
Raw
1 import * as appsync from "@distilled.cloud/aws/appsync";
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 * AppSync serializes control-plane mutations per API; concurrent resolver /
10 * data-source / schema operations surface as `ConcurrentModificationException`.
11 * Ride out the contention window with a bounded retry (~40s).
12 *
13 * The helper carries an EXPLICIT return annotation so the conditional type
14 * of `Effect.retry` never leaks into declaration emit (which would widen the
15 * provider layer to `unknown` for every consumer of `AWS.providers()`).
16 */
17 export const retryConcurrentModification = <A, E extends { _tag: string }, R>(
18 effect: Effect.Effect<A, E, R>,
19 ): Effect.Effect<A, E, R> =>
20 Effect.retry(effect, {
21 while: (error: E) => error._tag === "ConcurrentModificationException",
22 schedule: Schedule.max([
23 pipe(
24 Schedule.exponential(Duration.seconds(1), 2),
25 Schedule.modifyDelay(({ duration }) =>
26 Effect.succeed(
27 Duration.isGreaterThan(duration, Duration.seconds(8)) ? Duration.seconds(8) : duration,
28 ),
29 ),
30 ),
31 Schedule.recurs(8),
32 ]),
33 }) as Effect.Effect<A, E, R>;
34
35 /**
36 * IAM changes (fresh service roles, updated trust policies) propagate to
37 * AppSync eventually; a `createDataSource` right after `createRole` can
38 * transiently fail with a `BadRequestException` complaining that AppSync
39 * is not authorized to assume the role. Bounded retry (~20s), scoped to
40 * role-assumption messages so genuine validation errors fail fast.
41 */
42 export const retryWhileRolePropagates = <A, E extends { _tag: string; message?: string }, R>(
43 effect: Effect.Effect<A, E, R>,
44 ): Effect.Effect<A, E, R> =>
45 Effect.retry(effect, {
46 while: (error: E) =>
47 error._tag === "BadRequestException" && /assume|role|authorized/i.test(error.message ?? ""),
48 schedule: Schedule.max([Schedule.fixed(Duration.seconds(2)), Schedule.recurs(10)]),
49 }) as Effect.Effect<A, E, R>;
50
51 /**
52 * AppSync data-source and pipeline-function names must match
53 * `[_A-Za-z][_0-9A-Za-z]*` (no dashes). Deterministic physical names are
54 * generated with dashes, so sanitize into the allowed alphabet.
55 */
56 export const sanitizeAppSyncName = (name: string): string => {
57 const sanitized = name.replaceAll(/[^_0-9A-Za-z]/g, "_");
58 return /^[_A-Za-z]/.test(sanitized) ? sanitized : `_${sanitized}`;
59 };
60
61 /**
62 * Normalize the wire tag map (values may be `undefined`) to a plain record.
63 */
64 export const tagRecord = (
65 tags: { [key: string]: string | undefined } | undefined,
66 ): Record<string, string> =>
67 Object.fromEntries(
68 Object.entries(tags ?? {}).filter((entry): entry is [string, string] => entry[1] !== undefined),
69 );
70
71 /**
72 * Diff observed tags against desired tags and apply only the delta via the
73 * AppSync `tagResource`/`untagResource` operations.
74 */
75 export const syncAppSyncTags = Effect.fn(function* ({
76 resourceArn,
77 oldTags,
78 newTags,
79 }: {
80 resourceArn: string;
81 oldTags: Record<string, string>;
82 newTags: Record<string, string>;
83 }) {
84 const { removed, upsert } = diffTags(oldTags, newTags);
85 if (removed.length > 0) {
86 yield* appsync
87 .untagResource({ resourceArn, tagKeys: removed })
88 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
89 }
90 if (upsert.length > 0) {
91 yield* appsync.tagResource({
92 resourceArn,
93 tags: normalizeTags(upsert),
94 });
95 }
96 });