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

main
ts 443 lines 15.8 KB
Raw
1 import * as cloudformation from "@distilled.cloud/aws/cloudformation";
2 import { toWireMinutes } from "alchemy/Util/Duration";
3 import * as Data from "effect/Data";
4 import type * as Duration from "effect/Duration";
5 import * as Effect from "effect/Effect";
6 import * as Schedule from "effect/Schedule";
7
8 /**
9 * Bounded wait for a stack to leave an in-progress status. Explicitly-typed
10 * pipeable helper — an inline `Effect.retry` in a provider lifecycle op leaks
11 * `Retry.Return`'s conditional into declaration emit and widens the provider
12 * layer to `unknown` R for every `AWS.providers()` consumer.
13 */
14 const retryUntilStackSettled = <A, E extends { readonly _tag: string }, R>(
15 self: Effect.Effect<A, E, R>,
16 ): Effect.Effect<A, E, R> =>
17 Effect.retry(self, {
18 while: (e) => e._tag === "StackNotSettled",
19 schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(120)]),
20 });
21 import { Unowned } from "alchemy/AdoptPolicy";
22 import { isResolved } from "alchemy/Diff";
23 import { createPhysicalName } from "alchemy/PhysicalName";
24 import * as Provider from "alchemy/Provider";
25 import { Resource } from "alchemy/Resource";
26 import { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
27 import * as Stream from "effect/Stream";
28 import type { Providers } from "../Providers.ts";
29
30 /**
31 * Behaviour when stack creation fails.
32 * - `ROLLBACK` (default) — roll the stack back and delete created resources.
33 * - `DO_NOTHING` — leave created resources in place for inspection.
34 * - `DELETE` — delete the stack and all created resources.
35 */
36 export type OnFailure = "DO_NOTHING" | "ROLLBACK" | "DELETE";
37
38 export interface StackProps {
39 /**
40 * Name of the CloudFormation stack. Must be 1-128 characters, start with a
41 * letter, and contain only letters, digits, and hyphens. If omitted, a
42 * deterministic physical name is generated. Changing the name replaces the
43 * stack.
44 */
45 stackName?: string;
46 /**
47 * The CloudFormation template as an inline JSON or YAML string. Mutually
48 * exclusive with `templateURL`. Maximum 51,200 bytes — use `templateURL`
49 * for larger templates.
50 */
51 templateBody?: string;
52 /**
53 * Location of a template stored in Amazon S3 (an `https://` URL to an S3
54 * object). Mutually exclusive with `templateBody`.
55 */
56 templateURL?: string;
57 /**
58 * Input parameter values for the template, keyed by parameter name.
59 */
60 parameters?: Record<string, string>;
61 /**
62 * IAM capabilities the stack is allowed to acknowledge. Required when the
63 * template creates IAM resources (`CAPABILITY_IAM` /
64 * `CAPABILITY_NAMED_IAM`) or uses macros (`CAPABILITY_AUTO_EXPAND`).
65 */
66 capabilities?: Array<"CAPABILITY_IAM" | "CAPABILITY_NAMED_IAM" | "CAPABILITY_AUTO_EXPAND">;
67 /**
68 * ARN of an IAM role that CloudFormation assumes to create/update/delete
69 * the stack's resources. Defaults to the credentials of the deploying
70 * principal.
71 */
72 roleArn?: string;
73 /**
74 * SNS topic ARNs that receive stack event notifications.
75 */
76 notificationARNs?: string[];
77 /**
78 * Whether to disable rollback of the stack if creation fails.
79 * @default false
80 */
81 disableRollback?: boolean;
82 /**
83 * Behaviour when stack creation fails. Applied only on create.
84 * @default "ROLLBACK"
85 */
86 onFailure?: OnFailure;
87 /**
88 * Amount of time that can pass before the stack status becomes
89 * `CREATE_FAILED` (e.g. `"30 minutes"` or `Duration.minutes(30)`; a bare
90 * number is milliseconds). Converted to whole minutes on the wire.
91 */
92 timeout?: Duration.Input;
93 /**
94 * User-defined tags propagated to every resource in the stack.
95 */
96 tags?: Record<string, string>;
97 }
98
99 export interface Stack extends Resource<
100 "AWS.CloudFormation.Stack",
101 StackProps,
102 {
103 /**
104 * Name of the stack.
105 */
106 stackName: string;
107 /**
108 * The unique stack ID (ARN).
109 */
110 stackId: string;
111 /**
112 * Current status of the stack (e.g. `CREATE_COMPLETE`, `UPDATE_COMPLETE`).
113 */
114 stackStatus: string;
115 /** Template outputs keyed by output name. */
116 outputs: Record<string, string>;
117 },
118 never,
119 Providers
120 > {}
121
122 /**
123 * An AWS CloudFormation stack — deploy an existing CloudFormation template
124 * from Alchemy as an interop/escape hatch.
125 *
126 * Create and update are asynchronous: the provider submits the template and
127 * then polls (bounded) until the stack reaches a terminal state, surfacing a
128 * `CREATE_FAILED` / `ROLLBACK_COMPLETE` / `UPDATE_ROLLBACK_COMPLETE` status as
129 * a typed error rather than hanging. An update whose template and parameters
130 * are unchanged is a no-op (`No updates are to be performed`). Deletion waits
131 * for `DELETE_COMPLETE`.
132 * ### Deploying a Template
133 * **Example:** Inline Template (SNS Topic)
134 * ```typescript
135 * const stack = yield* CloudFormation.Stack("Notifications", {
136 * templateBody: JSON.stringify({
137 * Resources: {
138 * Topic: { Type: "AWS::SNS::Topic", Properties: { DisplayName: "alerts" } },
139 * },
140 * Outputs: { TopicArn: { Value: { Ref: "Topic" } } },
141 * }),
142 * });
143 * // stack.outputs.TopicArn -> "arn:aws:sns:us-west-2:...:Notifications-Topic-..."
144 * ```
145 *
146 * **Example:** Template with Parameters
147 * ```typescript
148 * const stack = yield* CloudFormation.Stack("Config", {
149 * templateBody: JSON.stringify({
150 * Parameters: { Value: { Type: "String" } },
151 * Resources: {
152 * Param: {
153 * Type: "AWS::SSM::Parameter",
154 * Properties: { Type: "String", Value: { Ref: "Value" } },
155 * },
156 * },
157 * }),
158 * parameters: { Value: "hello" },
159 * });
160 * ```
161 *
162 * ### IAM Templates
163 * **Example:** Acknowledging Capabilities
164 * ```typescript
165 * const stack = yield* CloudFormation.Stack("Roles", {
166 * templateBody: iamTemplateJson,
167 * capabilities: ["CAPABILITY_NAMED_IAM"],
168 * });
169 * ```
170 *
171 * @resource
172 */
173 export const Stack = Resource<Stack>("AWS.CloudFormation.Stack");
174
175 class StackNotSettled extends Data.TaggedError("StackNotSettled")<{
176 readonly stackId: string;
177 readonly status: string;
178 }> {}
179
180 class StackOperationFailed extends Data.TaggedError("StackOperationFailed")<{
181 readonly stackName: string;
182 readonly status: string;
183 readonly reason: string | undefined;
184 }> {}
185
186 /** A stack in one of these statuses is mid-operation. */
187 const isInProgress = (status: string | undefined): boolean =>
188 status?.endsWith("_IN_PROGRESS") ?? false;
189
190 /**
191 * A ROLLBACK_COMPLETE / ROLLBACK_FAILED create leaves the stack in a
192 * non-updatable "created but failed" state — it can only be deleted.
193 */
194 const isFailedCreateRemnant = (status: string | undefined): boolean =>
195 status === "ROLLBACK_COMPLETE" || status === "ROLLBACK_FAILED";
196
197 const isFailure = (status: string | undefined): boolean =>
198 (status?.endsWith("_FAILED") ?? false) ||
199 status === "ROLLBACK_COMPLETE" ||
200 status === "UPDATE_ROLLBACK_COMPLETE";
201
202 const toParameters = (
203 parameters: Record<string, string> | undefined,
204 ): cloudformation.Parameter[] | undefined =>
205 parameters === undefined
206 ? undefined
207 : Object.entries(parameters).map(([ParameterKey, ParameterValue]) => ({
208 ParameterKey,
209 ParameterValue,
210 }));
211
212 const toWireTags = (tags: Record<string, string>): cloudformation.Tag[] =>
213 Object.entries(tags).map(([Key, Value]) => ({ Key, Value }));
214
215 const toTagRecord = (tags: cloudformation.Tag[] | undefined): Record<string, string> =>
216 Object.fromEntries(
217 (tags ?? [])
218 .filter(
219 (tag): tag is { Key: string; Value: string } =>
220 typeof tag.Key === "string" && typeof tag.Value === "string",
221 )
222 .map((tag) => [tag.Key, tag.Value]),
223 );
224
225 const toOutputs = (outputs: cloudformation.Output[] | undefined): Record<string, string> =>
226 Object.fromEntries(
227 (outputs ?? []).flatMap((o) =>
228 o.OutputKey !== undefined && o.OutputValue !== undefined
229 ? [[o.OutputKey, o.OutputValue]]
230 : [],
231 ),
232 );
233
234 export const StackProvider = () =>
235 Provider.effect(
236 Stack,
237 Effect.gen(function* () {
238 const toName = (id: string, props: Partial<StackProps>) =>
239 props.stackName
240 ? Effect.succeed(props.stackName)
241 : createPhysicalName({ id, maxLength: 128 });
242
243 /**
244 * Describe a stack by name or id. A missing stack (typed
245 * `StackNotFound`) or a fully-deleted stack reads as absent.
246 */
247 const describe = Effect.fn(function* (nameOrId: string) {
248 const response = yield* cloudformation.describeStacks({ StackName: nameOrId }).pipe(
249 Effect.map((r) => r.Stacks ?? []),
250 Effect.catchTag("StackNotFound", () => Effect.succeed([])),
251 );
252 const stack = response[0];
253 return stack === undefined || stack.StackStatus === "DELETE_COMPLETE" ? undefined : stack;
254 });
255
256 // Create/update run asynchronously; CloudFormation reports *_IN_PROGRESS
257 // while converging. A small stack settles in ~1-2 minutes; budget
258 // ~10 min (120 * 5s).
259 const waitForSettled = Effect.fn(function* (stackId: string, stackName: string) {
260 const stack = yield* describe(stackId).pipe(
261 Effect.flatMap((s) =>
262 s !== undefined && isInProgress(s.StackStatus)
263 ? Effect.fail(
264 new StackNotSettled({
265 stackId,
266 status: s.StackStatus ?? "UNKNOWN",
267 }),
268 )
269 : Effect.succeed(s),
270 ),
271 retryUntilStackSettled,
272 );
273 if (stack !== undefined && isFailure(stack.StackStatus)) {
274 return yield* new StackOperationFailed({
275 stackName,
276 status: stack.StackStatus ?? "UNKNOWN",
277 reason: stack.StackStatusReason,
278 });
279 }
280 return stack;
281 });
282
283 // Deletion is asynchronous too — wait until the stack reports
284 // DELETE_COMPLETE (or vanishes) so dependencies can be torn down after.
285 const waitUntilGone = Effect.fn(function* (stackId: string, stackName: string) {
286 yield* retryUntilStackSettled(
287 describe(stackId).pipe(
288 Effect.flatMap((s): Effect.Effect<void, StackNotSettled | StackOperationFailed> => {
289 if (s === undefined) return Effect.void;
290 if (s.StackStatus === "DELETE_FAILED") {
291 return Effect.fail(
292 new StackOperationFailed({
293 stackName,
294 status: "DELETE_FAILED",
295 reason: s.StackStatusReason,
296 }),
297 );
298 }
299 return Effect.fail(
300 new StackNotSettled({
301 stackId,
302 status: s.StackStatus ?? "UNKNOWN",
303 }),
304 );
305 }),
306 ),
307 );
308 });
309
310 const toAttrs = (stack: cloudformation.Stack) => ({
311 stackName: stack.StackName!,
312 stackId: stack.StackId!,
313 stackStatus: stack.StackStatus!,
314 outputs: toOutputs(stack.Outputs),
315 });
316
317 return {
318 stables: ["stackName", "stackId"],
319
320 diff: Effect.fn(function* ({ id, olds, news }) {
321 if (!isResolved(news)) return undefined;
322 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) {
323 return { action: "replace" } as const;
324 }
325 }),
326
327 read: Effect.fn(function* ({ id, olds, output }) {
328 const stack = yield* describe(output?.stackId ?? (yield* toName(id, olds ?? {})));
329 if (stack === undefined) return undefined;
330 const attrs = toAttrs(stack);
331 const tags = toTagRecord(stack.Tags);
332 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
333 }),
334
335 reconcile: Effect.fn(function* ({ id, news, output, session }) {
336 const name = output?.stackName ?? (yield* toName(id, news));
337 const internalTags = yield* createInternalTags(id);
338 const desiredTags = { ...internalTags, ...news.tags };
339
340 // 1. Observe — cloud state is authoritative; output is only an id
341 // cache.
342 let observed = yield* describe(output?.stackId ?? name);
343
344 // A stack left in ROLLBACK_COMPLETE/ROLLBACK_FAILED by a failed
345 // create can only be deleted; clear it before recreating.
346 if (observed !== undefined && isFailedCreateRemnant(observed.StackStatus)) {
347 yield* cloudformation.deleteStack({ StackName: observed.StackId! });
348 yield* waitUntilGone(observed.StackId!, name);
349 observed = undefined;
350 }
351
352 // 2. Ensure — create if missing, then wait for CREATE_COMPLETE.
353 if (observed === undefined) {
354 const created = yield* cloudformation.createStack({
355 StackName: name,
356 TemplateBody: news.templateBody,
357 TemplateURL: news.templateURL,
358 Parameters: toParameters(news.parameters),
359 Capabilities: news.capabilities,
360 RoleARN: news.roleArn,
361 NotificationARNs: news.notificationARNs,
362 DisableRollback: news.disableRollback,
363 OnFailure: news.onFailure,
364 TimeoutInMinutes: toWireMinutes(news.timeout),
365 Tags: toWireTags(desiredTags),
366 });
367 const settled = yield* waitForSettled(created.StackId!, name);
368 if (settled === undefined) {
369 return yield* new StackOperationFailed({
370 stackName: name,
371 status: "DELETE_COMPLETE",
372 reason: "Stack disappeared immediately after creation",
373 });
374 }
375 yield* session.note(name);
376 return toAttrs(settled);
377 }
378
379 // 3. Sync — submit the desired template/params/tags. An unchanged
380 // template is a no-op (typed NoUpdateToPerform); skip the wait.
381 const didUpdate = yield* cloudformation
382 .updateStack({
383 StackName: observed.StackId!,
384 TemplateBody: news.templateBody,
385 TemplateURL: news.templateURL,
386 Parameters: toParameters(news.parameters),
387 Capabilities: news.capabilities,
388 RoleARN: news.roleArn,
389 NotificationARNs: news.notificationARNs,
390 DisableRollback: news.disableRollback,
391 Tags: toWireTags(desiredTags),
392 })
393 .pipe(
394 Effect.as(true),
395 Effect.catchTag("NoUpdateToPerform", () => Effect.succeed(false)),
396 );
397
398 const final = didUpdate ? yield* waitForSettled(observed.StackId!, name) : observed;
399 if (final === undefined) {
400 return yield* new StackOperationFailed({
401 stackName: name,
402 status: "DELETE_COMPLETE",
403 reason: "Stack disappeared while updating",
404 });
405 }
406
407 // 4. Return fresh attributes.
408 yield* session.note(name);
409 return toAttrs(final);
410 }),
411
412 delete: Effect.fn(function* ({ output }) {
413 yield* cloudformation.deleteStack({ StackName: output.stackId });
414 yield* waitUntilGone(output.stackId, output.stackName);
415 }),
416
417 list: () =>
418 cloudformation.describeStacks.pages({}).pipe(
419 Stream.runCollect,
420 Effect.map((chunk) =>
421 Array.from(chunk)
422 .flatMap((page) => page.Stacks ?? [])
423 .flatMap((s) =>
424 s.StackName !== undefined &&
425 s.StackId !== undefined &&
426 s.StackStatus !== undefined &&
427 s.StackStatus !== "DELETE_COMPLETE"
428 ? [
429 {
430 stackName: s.StackName,
431 stackId: s.StackId,
432 stackStatus: s.StackStatus,
433 outputs: toOutputs(s.Outputs),
434 },
435 ]
436 : [],
437 ),
438 ),
439 Effect.catchTag("StackNotFound", () => Effect.succeed([])),
440 ),
441 };
442 }),
443 );