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

main
ts 196 lines 6.51 KB
Raw
1 import * as lexm from "@distilled.cloud/aws/lex-models-v2";
2 import { diffTags } from "alchemy/Tags";
3 import * as Data from "effect/Data";
4 import * as Effect from "effect/Effect";
5 import * as Schedule from "effect/Schedule";
6
7 /** A Lex V2 resource ended in a terminal `Failed` state (or never settled). */
8 export class LexOperationFailed extends Data.TaggedError("LexOperationFailed")<{
9 readonly resourceId: string;
10 readonly status: string;
11 readonly reasons: readonly string[];
12 }> {}
13
14 /**
15 * Coerce a generated physical name into Lex's name pattern
16 * `^([0-9a-zA-Z][_-]?){1,100}$` — every `-`/`_` must be preceded by an
17 * alphanumeric (no leading or consecutive separators).
18 */
19 export const toLexName = (name: string): string =>
20 name
21 .replace(/[^0-9a-zA-Z_-]/g, "-")
22 .replace(/[-_]{2,}/g, "-")
23 .replace(/^[-_]+/, "")
24 .slice(0, 100);
25
26 /** Convert a Lex wire tag map (values may be undefined) into a plain record. */
27 export const toTagRecord = (
28 tags: { [key: string]: string | undefined } | undefined,
29 ): Record<string, string> =>
30 Object.fromEntries(
31 Object.entries(tags ?? {}).filter((entry): entry is [string, string] => entry[1] !== undefined),
32 );
33
34 /**
35 * Retry `ConflictException`s on a bounded schedule. Lex serializes most
36 * mutations per bot — a concurrent build/version/update surfaces as a
37 * transient conflict.
38 *
39 * The explicit `Effect.Effect<A, E, R>` return annotation is load-bearing:
40 * inlining retry/repeat combinators in provider lifecycle code lets their
41 * conditional return types survive into declaration emit and widen the
42 * provider layer to `unknown` (see `../EC2/VolumeAttachment.ts`).
43 */
44 export const retryWhileConflict = <A, E extends { readonly _tag: string }, R>(
45 self: Effect.Effect<A, E, R>,
46 ): Effect.Effect<A, E, R> =>
47 Effect.retry(self, {
48 while: (e) => e._tag === "ConflictException",
49 schedule: Schedule.max([Schedule.fixed(2000), Schedule.recurs(10)]),
50 });
51
52 /**
53 * Repeat a describe poll until `done` holds (bounded). Explicitly typed for
54 * the declaration-emit reason above.
55 */
56 const untilConverged = <A, E, R>(
57 self: Effect.Effect<A, E, R>,
58 done: (a: A) => boolean,
59 options?: { intervalSeconds?: number; times?: number },
60 ): Effect.Effect<A, E, R> =>
61 Effect.repeat(self, {
62 schedule: Schedule.spaced(`${options?.intervalSeconds ?? 2} seconds`),
63 until: done,
64 times: options?.times ?? 40,
65 });
66
67 const transientBotStatuses = new Set(["Creating", "Versioning", "Updating", "Importing"]);
68
69 /**
70 * Poll `describeBot` until the bot leaves its transient statuses
71 * (`Creating`/`Versioning`/`Updating`/`Importing`). Fails typed on `Failed`.
72 * Bot mutations settle in seconds — budget ~80s.
73 */
74 export const waitForBotSettled = Effect.fn("AWS.LexV2.waitForBotSettled")(function* (
75 botId: string,
76 ) {
77 const bot = yield* untilConverged(
78 lexm.describeBot({ botId }),
79 (b) => !transientBotStatuses.has(b.botStatus ?? ""),
80 );
81 if (bot.botStatus === "Failed" || transientBotStatuses.has(bot.botStatus ?? "")) {
82 return yield* new LexOperationFailed({
83 resourceId: botId,
84 status: bot.botStatus ?? "unknown",
85 reasons: bot.failureReasons ?? [],
86 });
87 }
88 return bot;
89 });
90
91 const transientLocaleStatuses = new Set(["Creating", "Processing", "Importing", "Deleting"]);
92
93 /**
94 * Poll `describeBotLocale` until the DRAFT locale leaves its create-time
95 * transient statuses (settles at `NotBuilt`/`Built`/`ReadyExpressTesting`).
96 * Fails typed on `Failed`.
97 */
98 export const waitForLocaleSettled = Effect.fn("AWS.LexV2.waitForLocaleSettled")(function* (
99 botId: string,
100 localeId: string,
101 ) {
102 const locale = yield* untilConverged(
103 lexm.describeBotLocale({ botId, botVersion: "DRAFT", localeId }),
104 (l) => !transientLocaleStatuses.has(l.botLocaleStatus ?? ""),
105 );
106 if (
107 locale.botLocaleStatus === "Failed" ||
108 transientLocaleStatuses.has(locale.botLocaleStatus ?? "")
109 ) {
110 return yield* new LexOperationFailed({
111 resourceId: `${botId}/${localeId}`,
112 status: locale.botLocaleStatus ?? "unknown",
113 reasons: locale.failureReasons ?? [],
114 });
115 }
116 return locale;
117 });
118
119 /**
120 * Poll `describeBotLocale` until a triggered build lands on `Built`.
121 * `Building` and `ReadyExpressTesting` are intermediate build states. A tiny
122 * bot normally builds in under a minute; keep the poll bounded to ~90 seconds
123 * so a stalled AWS build fails promptly.
124 */
125 export const waitForLocaleBuilt = Effect.fn("AWS.LexV2.waitForLocaleBuilt")(function* (
126 botId: string,
127 localeId: string,
128 ) {
129 const locale = yield* untilConverged(
130 lexm.describeBotLocale({ botId, botVersion: "DRAFT", localeId }),
131 (l) => l.botLocaleStatus === "Built" || l.botLocaleStatus === "Failed",
132 { intervalSeconds: 5, times: 18 },
133 );
134 if (locale.botLocaleStatus !== "Built") {
135 return yield* new LexOperationFailed({
136 resourceId: `${botId}/${localeId}`,
137 status: locale.botLocaleStatus ?? "unknown",
138 reasons: locale.failureReasons ?? [],
139 });
140 }
141 return locale;
142 });
143
144 /**
145 * Poll `describeBotAlias` until the alias leaves `Creating`. Fails typed on
146 * `Failed`.
147 */
148 export const waitForAliasSettled = Effect.fn("AWS.LexV2.waitForAliasSettled")(function* (
149 botId: string,
150 botAliasId: string,
151 ) {
152 const alias = yield* untilConverged(
153 lexm.describeBotAlias({ botId, botAliasId }),
154 (a) => a.botAliasStatus !== "Creating",
155 );
156 if (alias.botAliasStatus === "Failed" || alias.botAliasStatus === "Creating") {
157 return yield* new LexOperationFailed({
158 resourceId: `${botId}/${botAliasId}`,
159 status: alias.botAliasStatus ?? "unknown",
160 reasons: [],
161 });
162 }
163 return alias;
164 });
165
166 /**
167 * Read the observed tags of a Lex resource by ARN. Best-effort — a race with
168 * deletion reports no tags.
169 */
170 export const readLexTags = Effect.fn("AWS.LexV2.readLexTags")(function* (arn: string) {
171 const response = yield* lexm
172 .listTagsForResource({ resourceARN: arn })
173 .pipe(Effect.orElseSucceed(() => undefined));
174 return toTagRecord(response?.tags);
175 });
176
177 /**
178 * Sync tags on a Lex resource: diff OBSERVED cloud tags against the desired
179 * set and apply only the delta.
180 */
181 export const syncLexTags = Effect.fn("AWS.LexV2.syncLexTags")(function* (
182 arn: string,
183 observed: Record<string, string>,
184 desired: Record<string, string>,
185 ) {
186 const { removed, upsert } = diffTags(observed, desired);
187 if (upsert.length > 0) {
188 yield* lexm.tagResource({
189 resourceARN: arn,
190 tags: Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])),
191 });
192 }
193 if (removed.length > 0) {
194 yield* lexm.untagResource({ resourceARN: arn, tagKeys: removed });
195 }
196 });