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

main
ts 668 lines 22.4 KB
Raw
1 import * as crypto from "node:crypto";
2 import * as fis from "@distilled.cloud/aws/fis";
3 import { Unowned } from "alchemy/AdoptPolicy";
4 import { isResolved } from "alchemy/Diff";
5 import type { Input } from "alchemy/Input";
6 import * as Provider from "alchemy/Provider";
7 import { Resource } from "alchemy/Resource";
8 import { createInternalTags, diffTags, hasAlchemyTags, tagRecord } from "alchemy/Tags";
9 import { toSeconds } from "alchemy/Util/Duration";
10 import type * as Duration from "effect/Duration";
11 import * as Effect from "effect/Effect";
12 import * as Schedule from "effect/Schedule";
13 import * as Stream from "effect/Stream";
14 import type { Providers } from "../Providers.ts";
15
16 /**
17 * A filter that narrows the resources selected by an experiment template
18 * target using resource attribute paths.
19 */
20 export interface ExperimentTemplateTargetFilter {
21 /**
22 * The attribute path used to filter, e.g. `State.Name` for EC2 instances.
23 */
24 path: string;
25 /**
26 * The attribute values that a resource must match to be included.
27 */
28 values: string[];
29 }
30
31 /**
32 * A target definition for an experiment template — the set of resources an
33 * action is applied to.
34 */
35 export interface ExperimentTemplateTarget {
36 /**
37 * The resource type of the target, e.g. `aws:ec2:instance`.
38 */
39 resourceType: string;
40 /**
41 * ARNs of specific resources to target. Mutually exclusive with
42 * `resourceTags`.
43 */
44 resourceArns?: string[];
45 /**
46 * Tags that resources must have to be targeted. Mutually exclusive with
47 * `resourceArns`.
48 */
49 resourceTags?: Record<string, string>;
50 /**
51 * Filters that further narrow the targeted resources by attribute path,
52 * e.g. only running instances.
53 */
54 filters?: ExperimentTemplateTargetFilter[];
55 /**
56 * How targets are selected from the matched resources, e.g. `ALL`,
57 * `COUNT(1)`, or `PERCENT(25)`.
58 */
59 selectionMode: string;
60 /**
61 * Resource-type-specific parameters for the target.
62 */
63 parameters?: Record<string, string>;
64 }
65
66 /**
67 * An action carried out on targets during an experiment, e.g.
68 * `aws:ec2:stop-instances`.
69 */
70 export interface ExperimentTemplateAction {
71 /**
72 * The FIS action ID, e.g. `aws:ec2:stop-instances` or
73 * `aws:fis:wait`.
74 */
75 actionId: string;
76 /**
77 * A description of the action.
78 */
79 description?: string;
80 /**
81 * Action-specific parameters, e.g.
82 * `{ startInstancesAfterDuration: "PT2M" }`.
83 */
84 parameters?: Record<string, string>;
85 /**
86 * The named targets (keys of the template's `targets` map) the action
87 * applies to, keyed by the action's target name, e.g.
88 * `{ Instances: "MyTarget" }`.
89 */
90 targets?: Record<string, string>;
91 /**
92 * Names of other actions that must complete before this action starts.
93 */
94 startAfter?: string[];
95 }
96
97 /**
98 * A stop condition for an experiment. When triggered while an experiment is
99 * running, the experiment is stopped.
100 */
101 export interface ExperimentTemplateStopCondition {
102 /**
103 * The source of the stop condition: `aws:cloudwatch:alarm` or `none`.
104 */
105 source: "aws:cloudwatch:alarm" | "none" | (string & {});
106 /**
107 * The ARN of the CloudWatch alarm. Required when `source` is
108 * `aws:cloudwatch:alarm`.
109 */
110 value?: string;
111 }
112
113 /**
114 * Experiment log delivery configuration.
115 */
116 export interface ExperimentTemplateLogConfiguration {
117 /**
118 * Deliver experiment logs to a CloudWatch Logs log group.
119 */
120 cloudWatchLogsConfiguration?: {
121 /**
122 * The ARN of the destination log group.
123 */
124 logGroupArn: string;
125 };
126 /**
127 * Deliver experiment logs to an S3 bucket.
128 */
129 s3Configuration?: {
130 /**
131 * The name of the destination bucket.
132 */
133 bucketName: string;
134 /**
135 * The bucket prefix for delivered log objects.
136 */
137 prefix?: string;
138 };
139 /**
140 * The schema version of delivered log records.
141 * @default 2
142 */
143 logSchemaVersion?: number;
144 }
145
146 /**
147 * Experiment options controlling account targeting and empty-target
148 * behavior.
149 */
150 export interface ExperimentTemplateExperimentOptions {
151 /**
152 * Whether the experiment targets resources in the current account only or
153 * across multiple accounts. Changing this replaces the template.
154 * @default "single-account"
155 */
156 accountTargeting?: "single-account" | "multi-account";
157 /**
158 * What happens when a target resolves to zero resources: `fail` the
159 * experiment or `skip` the action.
160 * @default "fail"
161 */
162 emptyTargetResolutionMode?: "fail" | "skip";
163 }
164
165 /**
166 * Experiment report configuration.
167 */
168 export interface ExperimentTemplateReportConfiguration {
169 /**
170 * Where the experiment report is delivered.
171 */
172 outputs?: {
173 /**
174 * Deliver the report to an S3 bucket.
175 */
176 s3Configuration?: {
177 /**
178 * The name of the destination bucket.
179 */
180 bucketName?: string;
181 /**
182 * The bucket prefix for the delivered report.
183 */
184 prefix?: string;
185 };
186 };
187 /**
188 * Data sources included in the report.
189 */
190 dataSources?: {
191 /**
192 * CloudWatch dashboards to capture in the report.
193 */
194 cloudWatchDashboards?: {
195 /**
196 * The ARN of the CloudWatch dashboard.
197 */
198 dashboardIdentifier?: string;
199 }[];
200 };
201 /**
202 * How long before the experiment to capture data, e.g. `"10 minutes"` or
203 * `Duration.minutes(10)`. Sent to FIS as an ISO-8601 duration (`PT10M`).
204 */
205 preExperimentDuration?: Duration.Input;
206 /**
207 * How long after the experiment to capture data, e.g. `"10 minutes"` or
208 * `Duration.minutes(10)`. Sent to FIS as an ISO-8601 duration (`PT10M`).
209 */
210 postExperimentDuration?: Duration.Input;
211 }
212
213 export interface ExperimentTemplateProps {
214 /**
215 * A description of the experiment template.
216 * @default the logical ID of the resource
217 */
218 description?: string;
219 /**
220 * The ARN of the IAM role that grants FIS permission to perform the
221 * template's actions on your behalf. The role must trust
222 * `fis.amazonaws.com`.
223 */
224 roleArn: string;
225 /**
226 * The actions carried out during an experiment, keyed by a name of your
227 * choosing.
228 */
229 actions: Record<string, ExperimentTemplateAction>;
230 /**
231 * The targets the actions apply to, keyed by a name of your choosing and
232 * referenced from each action's `targets` map.
233 */
234 targets?: Record<string, ExperimentTemplateTarget>;
235 /**
236 * Stop conditions that halt a running experiment when triggered.
237 * @default [{ source: "none" }]
238 */
239 stopConditions?: ExperimentTemplateStopCondition[];
240 /**
241 * Experiment log delivery configuration. Once configured, log delivery
242 * cannot be fully removed via the API — only changed.
243 */
244 logConfiguration?: ExperimentTemplateLogConfiguration;
245 /**
246 * Experiment options. `accountTargeting` is create-only — changing it
247 * replaces the template.
248 */
249 experimentOptions?: ExperimentTemplateExperimentOptions;
250 /**
251 * Experiment report configuration.
252 */
253 experimentReportConfiguration?: ExperimentTemplateReportConfiguration;
254 /**
255 * Tags to apply to the experiment template. Merged with internal Alchemy
256 * tags.
257 */
258 tags?: Record<string, string>;
259 }
260
261 export interface ExperimentTemplate extends Resource<
262 "AWS.FIS.ExperimentTemplate",
263 ExperimentTemplateProps,
264 {
265 /**
266 * The generated ID of the experiment template, e.g. `EXT1a2b3c4d`.
267 */
268 id: string;
269 /**
270 * The ARN of the experiment template.
271 */
272 arn: string;
273 /**
274 * The ARN of the IAM role the experiment runs as.
275 */
276 roleArn: string;
277 },
278 never,
279 Providers
280 > {}
281
282 /**
283 * An AWS Fault Injection Service (FIS) experiment template — a reusable
284 * definition of a chaos-engineering experiment: the targets to disrupt, the
285 * fault actions to run against them, and the stop conditions that abort a
286 * runaway experiment.
287 *
288 * Creating a template is free and does not disrupt any resources — faults
289 * are only injected when an experiment is explicitly started from the
290 * template.
291 * ### Creating Experiment Templates
292 * **Example:** Stop EC2 instances selected by tag
293 * ```typescript
294 * import * as AWS from "@alchemy.run/aws";
295 *
296 * const role = yield* AWS.IAM.Role("FisRole", {
297 * assumeRolePolicyDocument: {
298 * Version: "2012-10-17",
299 * Statement: [{
300 * Effect: "Allow",
301 * Principal: { Service: "fis.amazonaws.com" },
302 * Action: ["sts:AssumeRole"],
303 * }],
304 * },
305 * managedPolicyArns: [
306 * "arn:aws:iam::aws:policy/service-role/AWSFaultInjectionSimulatorEC2Access",
307 * ],
308 * });
309 *
310 * const template = yield* AWS.FIS.ExperimentTemplate("StopInstances", {
311 * description: "Stop one tagged instance for two minutes",
312 * roleArn: role.roleArn,
313 * targets: {
314 * Instances: {
315 * resourceType: "aws:ec2:instance",
316 * resourceTags: { ChaosReady: "true" },
317 * selectionMode: "COUNT(1)",
318 * },
319 * },
320 * actions: {
321 * StopInstances: {
322 * actionId: "aws:ec2:stop-instances",
323 * parameters: { startInstancesAfterDuration: "PT2M" },
324 * targets: { Instances: "Instances" },
325 * },
326 * },
327 * });
328 * ```
329 *
330 * **Example:** Stop condition backed by a CloudWatch alarm
331 * ```typescript
332 * const template = yield* AWS.FIS.ExperimentTemplate("GuardedExperiment", {
333 * roleArn: role.roleArn,
334 * targets: {
335 * Instances: {
336 * resourceType: "aws:ec2:instance",
337 * resourceTags: { ChaosReady: "true" },
338 * selectionMode: "ALL",
339 * },
340 * },
341 * actions: {
342 * StopInstances: {
343 * actionId: "aws:ec2:stop-instances",
344 * targets: { Instances: "Instances" },
345 * },
346 * },
347 * stopConditions: [
348 * {
349 * source: "aws:cloudwatch:alarm",
350 * value: alarmArn,
351 * },
352 * ],
353 * });
354 * ```
355 *
356 * **Example:** Wait action sequenced after a fault
357 * ```typescript
358 * const template = yield* AWS.FIS.ExperimentTemplate("SequencedExperiment", {
359 * roleArn: role.roleArn,
360 * actions: {
361 * Wait: {
362 * actionId: "aws:fis:wait",
363 * parameters: { duration: "PT1M" },
364 * },
365 * WaitAgain: {
366 * actionId: "aws:fis:wait",
367 * parameters: { duration: "PT1M" },
368 * startAfter: ["Wait"],
369 * },
370 * },
371 * });
372 * ```
373 *
374 * @resource
375 */
376 export const ExperimentTemplate = Resource<ExperimentTemplate>("AWS.FIS.ExperimentTemplate");
377
378 /**
379 * A freshly created IAM role referenced by `roleArn` can take a few seconds
380 * to become visible to FIS, which rejects the create/update with a
381 * `ValidationException` until the role propagates. Bounded retry through the
382 * propagation window. Explicitly typed so the conditional `Retry.Return`
383 * type never leaks into declaration emit.
384 */
385 const retryRolePropagation = <A, E extends { _tag: string }, R>(
386 self: Effect.Effect<A, E, R>,
387 ): Effect.Effect<A, E, R> =>
388 Effect.retry(self, {
389 while: (e) => e._tag === "ValidationException",
390 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(10)]),
391 });
392
393 /**
394 * Deterministic stringification for observed-vs-desired comparison: sorts
395 * object keys and drops `undefined` members, empty arrays, and empty objects
396 * so wire-level "absent" and "empty" compare equal.
397 */
398 const normalize = (value: unknown): unknown => {
399 if (Array.isArray(value)) {
400 const items = value.map(normalize).filter((v) => v !== undefined);
401 return items.length === 0 ? undefined : items;
402 }
403 if (typeof value === "object" && value !== null) {
404 const entries = Object.entries(value)
405 .map(([k, v]) => [k, normalize(v)] as const)
406 .filter(([, v]) => v !== undefined)
407 .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
408 return entries.length === 0 ? undefined : Object.fromEntries(entries);
409 }
410 return value;
411 };
412
413 const stableStringify = (value: unknown): string => JSON.stringify(normalize(value) ?? null);
414
415 export const ExperimentTemplateProvider = () =>
416 Provider.effect(
417 ExperimentTemplate,
418 Effect.gen(function* () {
419 const getTemplate = (templateId: string) =>
420 fis.getExperimentTemplate({ id: templateId }).pipe(
421 Effect.map((r) => r.experimentTemplate),
422 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
423 );
424
425 // FIS template IDs are server-generated, so when the cached output is
426 // lost (state persistence failure) we recover our template by the
427 // internal Alchemy tags carried on the list summaries. The match is
428 // scoped to the INSTANCE id (not just stack/stage/logical id): during a
429 // replacement the new instance must not "recover" the old physical
430 // template — it has to create a fresh one.
431 const findByTags = Effect.fn(function* (id: string, instanceId: string) {
432 const summaries = yield* fis.listExperimentTemplates.items({}).pipe(
433 Stream.runCollect,
434 Effect.map((chunk) => Array.from(chunk)),
435 );
436 for (const summary of summaries) {
437 if (
438 summary.id !== undefined &&
439 tagRecord(summary.tags)["alchemy::instance"] === instanceId &&
440 (yield* hasAlchemyTags(id, summary.tags))
441 ) {
442 return yield* getTemplate(summary.id);
443 }
444 }
445 return undefined;
446 });
447
448 const toAttrs = (template: fis.ExperimentTemplate) => ({
449 id: template.id!,
450 arn: template.arn!,
451 roleArn: template.roleArn!,
452 });
453
454 // Report-capture durations are `Duration.Input`s; the FIS wire format
455 // is an ISO-8601 duration string (e.g. `PT10M`). Normalize through the
456 // central Duration util (handles state-persisted Duration JSON), then
457 // emit hours when the duration is whole hours, else minutes, else
458 // seconds, matching the canonical forms FIS reports back.
459 const toIsoDuration = (input: Duration.Input | undefined): string | undefined => {
460 if (input === undefined) return undefined;
461 const seconds = toSeconds(input)!;
462 if (seconds > 0 && seconds % 3600 === 0) return `PT${seconds / 3600}H`;
463 if (seconds % 60 === 0) return `PT${seconds / 60}M`;
464 return `PT${seconds}S`;
465 };
466
467 // Project the report configuration into the wire shape (ISO-8601
468 // duration strings).
469 const projectReportConfiguration = (
470 config: ExperimentTemplateReportConfiguration | undefined,
471 ) =>
472 config
473 ? {
474 ...config,
475 preExperimentDuration: toIsoDuration(config.preExperimentDuration),
476 postExperimentDuration: toIsoDuration(config.postExperimentDuration),
477 }
478 : undefined;
479
480 // The desired mutable state, projected into the wire shape that
481 // `getExperimentTemplate` reports so observed-vs-desired comparison is
482 // structural.
483 const projectDesired = (id: string, props: ExperimentTemplateProps) => ({
484 description: props.description ?? id,
485 roleArn: props.roleArn,
486 stopConditions: props.stopConditions ?? [{ source: "none" }],
487 targets: props.targets ?? {},
488 actions: props.actions,
489 // Settable-but-not-removable aspects only participate in the
490 // comparison while the user declares them, so dropping the prop
491 // doesn't cause a perpetual (and futile) update call.
492 logConfiguration: props.logConfiguration
493 ? {
494 ...props.logConfiguration,
495 logSchemaVersion: props.logConfiguration.logSchemaVersion ?? 2,
496 }
497 : undefined,
498 emptyTargetResolutionMode: props.experimentOptions?.emptyTargetResolutionMode,
499 experimentReportConfiguration: projectReportConfiguration(
500 props.experimentReportConfiguration,
501 ),
502 });
503
504 const projectObserved = (
505 template: fis.ExperimentTemplate,
506 props: ExperimentTemplateProps,
507 ) => ({
508 description: template.description,
509 roleArn: template.roleArn,
510 stopConditions: template.stopConditions ?? [],
511 targets: template.targets ?? {},
512 actions: template.actions ?? {},
513 logConfiguration: props.logConfiguration ? template.logConfiguration : undefined,
514 emptyTargetResolutionMode: props.experimentOptions?.emptyTargetResolutionMode
515 ? template.experimentOptions?.emptyTargetResolutionMode
516 : undefined,
517 experimentReportConfiguration: props.experimentReportConfiguration
518 ? template.experimentReportConfiguration
519 : undefined,
520 });
521
522 return ExperimentTemplate.Provider.of({
523 stables: ["id", "arn"],
524
525 // Enumerate every experiment template in the ambient account/region,
526 // hydrating each summary into the full attribute shape. A template
527 // can vanish between enumeration and hydration; drop it.
528 list: () =>
529 Effect.gen(function* () {
530 const summaries = yield* fis.listExperimentTemplates.items({}).pipe(
531 Stream.runCollect,
532 Effect.map((chunk) => Array.from(chunk)),
533 );
534 const items = yield* Effect.forEach(
535 summaries,
536 (summary) =>
537 summary.id === undefined
538 ? Effect.undefined
539 : getTemplate(summary.id).pipe(Effect.map((t) => (t ? toAttrs(t) : undefined))),
540 { concurrency: 10 },
541 );
542 return items.filter(
543 (item): item is ExperimentTemplate["Attributes"] => item !== undefined,
544 );
545 }),
546
547 read: Effect.fn(function* ({ id, instanceId, output }) {
548 const template = output?.id
549 ? yield* getTemplate(output.id)
550 : yield* findByTags(id, instanceId);
551 if (template === undefined) return undefined;
552 const attrs = toAttrs(template);
553 return (yield* hasAlchemyTags(id, template.tags)) ? attrs : Unowned(attrs);
554 }),
555
556 diff: Effect.fn(function* ({ news, olds }) {
557 // accountTargeting is create-only — changing it replaces. Other
558 // props (commonly roleArn) are unresolved Outputs during plan, so
559 // narrow only the field replacement detection needs rather than
560 // requiring the whole props object to be resolved.
561 const newOptions = (
562 news as {
563 experimentOptions?: Input<ExperimentTemplateExperimentOptions>;
564 }
565 ).experimentOptions;
566 if (newOptions !== undefined && !isResolved(newOptions)) {
567 return undefined;
568 }
569 const oldTargeting = olds.experimentOptions?.accountTargeting ?? "single-account";
570 const newTargeting = newOptions?.accountTargeting ?? "single-account";
571 if (oldTargeting !== newTargeting) {
572 return { action: "replace" } as const;
573 }
574 // fall through: undefined → default update
575 }),
576
577 reconcile: Effect.fn(function* ({ id, instanceId, news, output, session }) {
578 const internalTags = yield* createInternalTags(id);
579 const desiredTags = {
580 ...news.tags,
581 ...internalTags,
582 "alchemy::instance": instanceId,
583 };
584 const desired = projectDesired(id, news);
585
586 // 1. Observe — cloud state is authoritative; output is only an id
587 // cache. Fall back to instance-scoped tag recovery when the id is
588 // unknown (state persistence failure).
589 let observed = output?.id ? yield* getTemplate(output.id) : undefined;
590 if (observed === undefined) {
591 observed = yield* findByTags(id, instanceId);
592 }
593
594 // 2. Ensure — create if missing. The clientToken is a per-request
595 // idempotency token, not a physical name.
596 if (observed === undefined) {
597 const clientToken = yield* Effect.sync(() => crypto.randomUUID());
598 observed = yield* retryRolePropagation(
599 fis.createExperimentTemplate({
600 clientToken,
601 description: desired.description,
602 stopConditions: desired.stopConditions,
603 targets: desired.targets,
604 actions: desired.actions,
605 roleArn: news.roleArn,
606 logConfiguration: desired.logConfiguration,
607 experimentOptions: news.experimentOptions,
608 experimentReportConfiguration: desired.experimentReportConfiguration,
609 tags: desiredTags,
610 }),
611 ).pipe(Effect.map((r) => r.experimentTemplate!));
612 } else if (
613 // 3a. Sync definition — compare the observed template against the
614 // desired projection and apply a single update on any delta
615 // (UpdateExperimentTemplate replaces the provided aspects
616 // wholesale). Skip the API entirely on no-op.
617 stableStringify(projectObserved(observed, news)) !== stableStringify(desired)
618 ) {
619 observed = yield* retryRolePropagation(
620 fis.updateExperimentTemplate({
621 id: observed.id!,
622 description: desired.description,
623 stopConditions: desired.stopConditions,
624 targets: desired.targets,
625 actions: desired.actions,
626 roleArn: news.roleArn,
627 logConfiguration: desired.logConfiguration,
628 experimentOptions: news.experimentOptions
629 ? {
630 emptyTargetResolutionMode: news.experimentOptions.emptyTargetResolutionMode,
631 }
632 : undefined,
633 experimentReportConfiguration: desired.experimentReportConfiguration,
634 }),
635 ).pipe(Effect.map((r) => r.experimentTemplate!));
636 }
637
638 // 3b. Sync tags — diff against the OBSERVED cloud tags (the create
639 // path already landed them, so this is a no-op there; adoption and
640 // out-of-band drift converge here).
641 const arn = observed.arn!;
642 const currentTags = tagRecord(observed.tags);
643 const { upsert, removed } = diffTags(currentTags, desiredTags);
644 if (upsert.length > 0) {
645 yield* fis.tagResource({
646 resourceArn: arn,
647 tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
648 });
649 }
650 if (removed.length > 0) {
651 yield* fis.untagResource({
652 resourceArn: arn,
653 tagKeys: removed,
654 });
655 }
656
657 yield* session.note(observed.id!);
658 return toAttrs(observed);
659 }),
660
661 delete: Effect.fn(function* ({ output }) {
662 yield* fis
663 .deleteExperimentTemplate({ id: output.id })
664 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
665 }),
666 });
667 }),
668 );