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

main
ts 892 lines 27.3 KB
Raw
1 import * as iam from "@distilled.cloud/aws/iam";
2 import * as s3 from "@distilled.cloud/aws/s3";
3 import * as Bundle from "alchemy/Bundle/Bundle";
4 import { findCwdForBundle, resolveMainPath } from "alchemy/Bundle/TempRoot";
5 import type { Input } from "alchemy/Input";
6 import { createPhysicalName } from "alchemy/PhysicalName";
7 import type { PlatformProps } from "alchemy/Platform";
8 import type { ScopedPlanStatusSession } from "alchemy/Report";
9 import type { ResourceBinding } from "alchemy/Resource";
10 import { createHostRuntimeContext, type HostRuntimeContext } from "alchemy/Runtime/Process";
11 import { createInternalTags, createTagsList, hasTags } from "alchemy/Tags";
12 import { sha256 } from "alchemy/Util/sha256";
13 import { zipCode } from "alchemy/Util/zip";
14 import * as Data from "effect/Data";
15 import * as Effect from "effect/Effect";
16 import * as FileSystem from "effect/FileSystem";
17 import type * as rolldown from "rolldown";
18 import { Assets } from "../Assets.ts";
19 import { roleHostBundle } from "../AWSBindings.ts";
20 import { AWSEnvironment } from "../Environment.ts";
21 import type { PolicyStatement } from "../IAM/Policy.ts";
22
23 export class EC2HostedInvalidProps extends Data.TaggedError("EC2HostedInvalidProps")<{
24 readonly message: string;
25 readonly cause?: unknown;
26 }> {}
27
28 export class EC2HostedConflict extends Data.TaggedError("EC2HostedConflict")<{
29 readonly message: string;
30 readonly cause?: unknown;
31 }> {}
32
33 /**
34 * Binding contract accepted by EC2-hosted runtimes: environment variables and
35 * IAM policy statements attached by capability bindings.
36 */
37 export interface Ec2HostedBinding {
38 /** Environment variables injected into the hosted runtime. */
39 env?: Record<string, any>;
40 /** IAM policy statements attached to the instance profile role. */
41 policyStatements?: PolicyStatement[];
42 }
43
44 /**
45 * Instance Metadata Service (IMDS) options for launched instances. Unset
46 * fields keep the AMI / account defaults.
47 */
48 export interface InstanceMetadataOptions {
49 /**
50 * `required` enforces IMDSv2 (session tokens); `optional` also allows
51 * IMDSv1.
52 */
53 httpTokens?: "required" | "optional";
54 /**
55 * Maximum hops for the IMDS PUT response, 1-64. `1` keeps containers on
56 * the host from reaching the instance role's credentials.
57 */
58 httpPutResponseHopLimit?: number;
59 /**
60 * Whether the metadata endpoint is reachable at all.
61 */
62 httpEndpoint?: "enabled" | "disabled";
63 /**
64 * Whether the IPv6 metadata endpoint is enabled.
65 */
66 httpProtocolIpv6?: "enabled" | "disabled";
67 /**
68 * Whether instance tags are readable from the metadata service.
69 */
70 instanceMetadataTags?: "enabled" | "disabled";
71 }
72
73 /**
74 * Shared props for EC2-backed hosted runtimes (an Instance that bundles and
75 * runs an application entrypoint).
76 */
77 export interface Ec2HostedProps extends PlatformProps {
78 /** AMI ID to launch the instance from. */
79 imageId: string;
80 /** EC2 instance type, e.g. `t3.micro`. */
81 instanceType: string;
82 /** Name of an EC2 key pair for SSH access. */
83 keyName?: Input<string>;
84 /** Existing instance profile to attach instead of a managed one. */
85 instanceProfileName?: string;
86 /** Additional user-data script prepended to the runtime bootstrap. */
87 userData?: string;
88 /** Subnet to launch the instance into. */
89 subnetId?: any;
90 /** Security groups attached to the instance. */
91 securityGroupIds?: readonly any[];
92 /** Whether to associate a public IP address. */
93 associatePublicIpAddress?: boolean;
94 /** Static private IP address within the subnet. */
95 privateIpAddress?: string;
96 /** Availability Zone to launch into. */
97 availabilityZone?: string;
98 /** Tags applied to the instance. */
99 tags?: Record<string, string>;
100 /** Instance Metadata Service options applied at launch. */
101 metadataOptions?: InstanceMetadataOptions;
102 /** Path to the application entrypoint to bundle and run on the instance. */
103 main?: string;
104 /** Named export of the handler within `main`. */
105 handler?: string;
106 /** Port the hosted HTTP server listens on. */
107 port?: number;
108 /** Environment variables injected into the hosted runtime. */
109 env?: Record<string, any>;
110 /**
111 * Overrides for the rolldown bundling of `main`. Unused code is
112 * tree-shaken. `effect`, alchemy, and `@distilled.cloud` are marked
113 * pure so unused parts prune more aggressively. List extra packages
114 * with `pure.packages`, or disable with `pure: false`.
115 */
116 build?: Bundle.BundleConfig;
117 /** Managed policy ARNs attached to the instance role. */
118 roleManagedPolicyArns?: string[];
119 }
120
121 export interface Ec2HostedRuntimeState {
122 userData?: string;
123 roleName?: string;
124 roleArn?: string;
125 policyName?: string;
126 instanceProfileName?: string;
127 instanceProfileArn?: string;
128 managedIam?: boolean;
129 runtimeUnitName?: string;
130 assetPrefix?: string;
131 code?: {
132 hash: string;
133 };
134 }
135
136 export interface Ec2HostedCleanupState {
137 roleName?: string;
138 policyName?: string;
139 instanceProfileName?: string;
140 managedIam?: boolean;
141 assetPrefix?: string;
142 }
143
144 /**
145 * Deploy-time / plan-time host context for EC2-backed platforms that bundle a
146 * long-lived program (`exports.program`) and collect background work via `run`
147 * / HTTP handlers via `serve`. Alias of the shared {@link HostRuntimeContext}.
148 */
149 export type Ec2HostRuntimeContext = HostRuntimeContext;
150
151 export const createEc2HostRuntimeContext = createHostRuntimeContext;
152
153 export const createEc2HostedSupport = ({
154 stackName,
155 stage,
156 virtualEntryPlugin,
157 resourceType,
158 }: {
159 stackName: string;
160 stage: string;
161 fs: FileSystem.FileSystem;
162 virtualEntryPlugin: (content: (importPath: string) => string) => rolldown.Plugin;
163 resourceType: string;
164 }) => {
165 const alchemyEnv = {
166 ALCHEMY_STACK_NAME: stackName,
167 ALCHEMY_STAGE: stage,
168 ALCHEMY_PHASE: "runtime",
169 };
170
171 const createRoleName = (id: string) =>
172 createPhysicalName({
173 id: `${id}-role`,
174 maxLength: 64,
175 });
176
177 const createPolicyName = (id: string) =>
178 createPhysicalName({
179 id: `${id}-policy`,
180 maxLength: 128,
181 });
182
183 const createManagedProfileName = (id: string) =>
184 createPhysicalName({
185 id: `${id}-profile`,
186 maxLength: 128,
187 });
188
189 const createRuntimeUnitName = (id: string) =>
190 createPhysicalName({
191 id: `${id}-instance`,
192 maxLength: 64,
193 lowercase: true,
194 }).pipe(Effect.map((name) => name.replaceAll(/[^a-z0-9-]/g, "-")));
195
196 const normalizeSecurityGroups = (groups?: readonly string[]) =>
197 [...(groups ?? [])].sort((a, b) => a.localeCompare(b));
198
199 const bundleProgram = Effect.fn(function* (id: string, props: Ec2HostedProps) {
200 if (!props.main) {
201 return yield* new EC2HostedInvalidProps({
202 message: `${resourceType} '${id}' requires 'main' when bundling a hosted process`,
203 });
204 }
205
206 const handler = props.handler ?? "default";
207 const realMain = yield* resolveMainPath(props.main);
208 const cwd = yield* findCwdForBundle(realMain);
209
210 const buildBundle = Effect.fn(function* (
211 entry: string,
212 plugins?: rolldown.RolldownPluginOption,
213 ) {
214 return yield* Bundle.build(
215 roleHostBundle({
216 ...props.build?.input,
217 input: entry,
218 cwd,
219 platform: "node",
220 // The hosted process runs under `bun` (installed by the user-data);
221 // keep `bun`/`bun:*` external and resolve the `bun` export condition
222 // so `@effect/platform-bun` picks its Bun implementations.
223 external: [
224 "bun",
225 "bun:*",
226 ...((props.build?.input?.external as string[] | undefined) ?? []),
227 ],
228 resolve: {
229 conditionNames: [...Bundle.BUN_CONDITION_NAMES],
230 ...props.build?.input?.resolve,
231 },
232 plugins: [props.build?.input?.plugins, plugins],
233 }),
234 {
235 ...props.build?.output,
236 format: "esm",
237 sourcemap: props.build?.output?.sourcemap ?? false,
238 minify: props.build?.output?.minify ?? false,
239 entryFileNames: "index.mjs",
240 },
241 props.build,
242 );
243 });
244
245 const bundleOutput = props.isExternal
246 ? yield* buildBundle(realMain)
247 : yield* buildBundle(
248 realMain,
249 virtualEntryPlugin(
250 (importPath) => `
251 import { bootstrap } from "@alchemy.run/aws/Bootstrap/Ec2";
252 import { ${handler} as entrypoint } from ${JSON.stringify(importPath)};
253
254 await bootstrap(entrypoint);
255 `,
256 ),
257 );
258
259 // Zip every emitted file: the entry becomes `index.mjs` (what the systemd
260 // unit runs) and shared chunks keep their `*.js` names so the entry's
261 // relative imports resolve. Dropping a chunk crashes the process at start.
262 const toBytes = (content: string | Uint8Array<ArrayBufferLike>) =>
263 typeof content === "string" ? new TextEncoder().encode(content) : content;
264 const [entryFile, ...chunkFiles] = bundleOutput.files;
265 const archive = yield* zipCode(
266 toBytes(entryFile.content),
267 chunkFiles.map((file) => ({
268 path: file.path,
269 content: toBytes(file.content),
270 })),
271 );
272 return { archive, hash: bundleOutput.hash };
273 });
274
275 const quoteEnvValue = (value: any) => {
276 const text = typeof value === "string" ? value : JSON.stringify(value ?? null);
277 return `'${text.replaceAll(/'/g, `'""'`).replaceAll(/\n/g, "\\n")}'`;
278 };
279
280 const renderEnvFile = (env: Record<string, any>) =>
281 Object.entries(env)
282 .sort(([a], [b]) => a.localeCompare(b))
283 .map(([key, value]) => `${key}=${quoteEnvValue(value)}`)
284 .join("\n");
285
286 const renderHostedUserData = Effect.fn(function* ({
287 unitName,
288 bundleKey,
289 envKey,
290 region,
291 }: {
292 unitName: string;
293 bundleKey: string;
294 envKey: string;
295 region: string;
296 }) {
297 const appDir = `/opt/${unitName}`;
298 const bucket = yield* Assets.BucketName;
299 // User-data runs once via cloud-init's `scripts-user` (once-per-instance),
300 // and is skipped on any subsequent boot — so it must NOT carry the work
301 // that can fail transiently (bun install over the network, S3 sync). It
302 // only writes the setup script + unit and enables the service. The systemd
303 // service (Restart=always) runs the setup on every start, so a flaky bun
304 // install / S3 read self-heals and the service survives reboots.
305 return `#!/bin/bash
306 set -uo pipefail
307
308 mkdir -p "${appDir}"
309
310 cat >/usr/local/bin/${unitName}-setup.sh <<'SETUP_EOF'
311 #!/bin/bash
312 set -uo pipefail
313 export HOME=/root
314
315 # unzip (needed below) — install if missing.
316 command -v unzip >/dev/null 2>&1 || {
317 (command -v dnf >/dev/null 2>&1 && dnf install -y unzip) \
318 || (command -v yum >/dev/null 2>&1 && yum install -y unzip) \
319 || (command -v apt-get >/dev/null 2>&1 && apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y unzip) || true
320 }
321
322 # AWS CLI — preinstalled on Amazon Linux 2023; install v2 otherwise.
323 command -v aws >/dev/null 2>&1 || {
324 curl -fsSL "https://awscli.amazonaws.com/awscli-exe-linux-$(uname -m).zip" -o /tmp/awscliv2.zip \
325 && (cd /tmp && unzip -q -o awscliv2.zip && ./aws/install) || true
326 }
327
328 # bun — retry the network install a few times.
329 if [ ! -x /root/.bun/bin/bun ]; then
330 for attempt in 1 2 3 4 5; do
331 curl -fsSL https://bun.sh/install | bash && break
332 sleep 5
333 done
334 fi
335
336 # Sync the bundle + env from S3 (must succeed for the service to start).
337 set -e
338 mkdir -p "${appDir}"
339 aws s3 cp "s3://${bucket}/${bundleKey}" "${appDir}/bundle.zip" --region "${region}"
340 aws s3 cp "s3://${bucket}/${envKey}" "${appDir}/env" --region "${region}"
341 rm -f "${appDir}/index.mjs"
342 unzip -o "${appDir}/bundle.zip" -d "${appDir}"
343 SETUP_EOF
344 chmod +x /usr/local/bin/${unitName}-setup.sh
345
346 cat >/etc/systemd/system/${unitName}.service <<'UNIT_EOF'
347 [Unit]
348 Description=Alchemy EC2 instance runtime ${unitName}
349 After=network-online.target
350 Wants=network-online.target
351
352 [Service]
353 Type=simple
354 WorkingDirectory=${appDir}
355 ExecStartPre=/usr/local/bin/${unitName}-setup.sh
356 EnvironmentFile=-${appDir}/env
357 # --no-install: the uploaded bundle is self-contained; bun must never fall
358 # into its auto-install path (which hangs startup on network package
359 # resolution) — fail fast if the bundle is incomplete instead.
360 ExecStart=/root/.bun/bin/bun --no-install ${appDir}/index.mjs
361 Restart=always
362 RestartSec=5
363
364 [Install]
365 WantedBy=multi-user.target
366 UNIT_EOF
367
368 systemctl daemon-reload
369 systemctl enable --now ${unitName}.service
370 `;
371 });
372
373 const mergeUserData = (hosted: string, userData?: string) => {
374 if (!userData) {
375 return hosted;
376 }
377 return `${hosted}\n\n# User supplied bootstrap\n${userData.replace(/^#!\/bin\/bash\s*/, "")}`;
378 };
379
380 const listAttachedPolicyArns = (roleName: string) =>
381 iam
382 .listAttachedRolePolicies({
383 RoleName: roleName,
384 })
385 .pipe(
386 Effect.map((result) =>
387 (result.AttachedPolicies ?? [])
388 .map((policy) => policy.PolicyArn)
389 .filter((policyArn): policyArn is string => Boolean(policyArn)),
390 ),
391 );
392
393 const attachManagedPolicies = Effect.fn(function* ({
394 roleName,
395 managedPolicyArns,
396 }: {
397 roleName: string;
398 managedPolicyArns: string[];
399 }) {
400 const attached = new Set(yield* listAttachedPolicyArns(roleName));
401 for (const policyArn of managedPolicyArns) {
402 if (!attached.has(policyArn)) {
403 yield* iam.attachRolePolicy({
404 RoleName: roleName,
405 PolicyArn: policyArn,
406 });
407 }
408 }
409 });
410
411 const ensureManagedRole = Effect.fn(function* ({
412 id,
413 roleName,
414 managedPolicyArns,
415 }: {
416 id: string;
417 roleName: string;
418 managedPolicyArns: string[];
419 }) {
420 const { accountId } = yield* AWSEnvironment.current;
421 const tags = yield* createInternalTags(id);
422 const role = yield* iam
423 .createRole({
424 RoleName: roleName,
425 AssumeRolePolicyDocument: JSON.stringify({
426 Version: "2012-10-17",
427 Statement: [
428 {
429 Effect: "Allow",
430 Principal: {
431 Service: "ec2.amazonaws.com",
432 },
433 Action: "sts:AssumeRole",
434 },
435 ],
436 }),
437 Tags: createTagsList(tags),
438 })
439 .pipe(
440 Effect.catchTag("EntityAlreadyExistsException", () =>
441 iam.getRole({ RoleName: roleName }).pipe(
442 Effect.filterOrFail(
443 (existing) => hasTags(tags, existing.Role?.Tags),
444 () =>
445 new EC2HostedConflict({
446 message: `Role '${roleName}' already exists and is not managed by alchemy`,
447 }),
448 ),
449 ),
450 ),
451 );
452
453 yield* attachManagedPolicies({
454 roleName,
455 managedPolicyArns,
456 });
457
458 return role.Role?.Arn ?? `arn:aws:iam::${accountId}:role/${roleName}`;
459 });
460
461 const ensureManagedInstanceProfile = Effect.fn(function* ({
462 id,
463 profileName,
464 roleName,
465 }: {
466 id: string;
467 profileName: string;
468 roleName: string;
469 }) {
470 const tags = yield* createInternalTags(id);
471 yield* iam
472 .createInstanceProfile({
473 InstanceProfileName: profileName,
474 Tags: createTagsList(tags),
475 })
476 .pipe(Effect.catchTag("EntityAlreadyExistsException", () => Effect.void));
477
478 const profile = yield* iam.getInstanceProfile({
479 InstanceProfileName: profileName,
480 });
481 const currentRoleName = profile.InstanceProfile.Roles?.[0]?.RoleName;
482
483 if (currentRoleName && currentRoleName !== roleName) {
484 yield* iam
485 .removeRoleFromInstanceProfile({
486 InstanceProfileName: profileName,
487 RoleName: currentRoleName,
488 })
489 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
490 }
491
492 if (currentRoleName !== roleName) {
493 yield* iam.addRoleToInstanceProfile({
494 InstanceProfileName: profileName,
495 RoleName: roleName,
496 });
497 }
498
499 const refreshed = yield* iam.getInstanceProfile({
500 InstanceProfileName: profileName,
501 });
502 return {
503 instanceProfileName: refreshed.InstanceProfile.InstanceProfileName,
504 instanceProfileArn: refreshed.InstanceProfile.Arn,
505 };
506 });
507
508 const attachHostedBindings = Effect.fn(function* ({
509 roleName,
510 policyName,
511 assetPrefix,
512 bindings,
513 }: {
514 roleName: string;
515 policyName: string;
516 assetPrefix: string;
517 bindings: ResourceBinding<Ec2HostedBinding>[];
518 }) {
519 const activeBindings = bindings.filter(
520 (binding: ResourceBinding<Ec2HostedBinding> & { action?: string }) =>
521 binding.action !== "delete",
522 );
523
524 const env = activeBindings
525 .map((binding) => binding?.data?.env)
526 .reduce((acc, value) => ({ ...acc, ...value }), {});
527
528 const policyStatements = activeBindings.flatMap(
529 (binding) =>
530 binding?.data?.policyStatements?.map((statement) => ({
531 ...statement,
532 Sid: statement.Sid?.replace(/[^A-Za-z0-9]+/gi, ""),
533 })) ?? [],
534 );
535
536 policyStatements.push({
537 Sid: undefined,
538 Effect: "Allow",
539 Action: ["s3:GetObject"],
540 Resource: [`arn:aws:s3:::${yield* Assets.BucketName}/${assetPrefix}/*`],
541 });
542
543 yield* iam.putRolePolicy({
544 RoleName: roleName,
545 PolicyName: policyName,
546 PolicyDocument: JSON.stringify({
547 Version: "2012-10-17",
548 Statement: policyStatements,
549 }),
550 });
551
552 return env;
553 });
554
555 const uploadHostedArtifacts = Effect.fn(function* ({
556 bundleKey,
557 envKey,
558 archive,
559 env,
560 }: {
561 bundleKey: string;
562 envKey: string;
563 archive: Uint8Array<ArrayBufferLike>;
564 env: Record<string, any>;
565 }) {
566 const assets = yield* Assets;
567 const contentHash = yield* sha256(archive);
568 const uploadedAssetKey = yield* assets.uploadAsset(contentHash, archive);
569 yield* s3.copyObject({
570 Bucket: yield* assets.bucketName,
571 Key: bundleKey,
572 CopySource: `${yield* assets.bucketName}/${uploadedAssetKey}`,
573 });
574 yield* s3.putObject({
575 Bucket: yield* assets.bucketName,
576 Key: envKey,
577 Body: renderEnvFile(env),
578 ContentType: "text/plain; charset=utf-8",
579 });
580 });
581
582 const resolveHostedRuntime = Effect.fn(function* ({
583 id,
584 news,
585 bindings,
586 output,
587 }: {
588 id: string;
589 news: Ec2HostedProps;
590 bindings: ResourceBinding<Ec2HostedBinding>[];
591 output?: Ec2HostedRuntimeState;
592 }) {
593 if (!news.main) {
594 return {
595 userData: news.userData,
596 roleName: output?.roleName,
597 roleArn: output?.roleArn,
598 policyName: output?.policyName,
599 instanceProfileName: news.instanceProfileName ?? output?.instanceProfileName,
600 instanceProfileArn: output?.instanceProfileArn,
601 managedIam: output?.managedIam ?? false,
602 runtimeUnitName: output?.runtimeUnitName,
603 assetPrefix: output?.assetPrefix,
604 code: output?.code,
605 } satisfies Ec2HostedRuntimeState;
606 }
607
608 if (news.instanceProfileName && (news.roleManagedPolicyArns?.length ?? 0) > 0) {
609 return yield* new EC2HostedInvalidProps({
610 message: `${resourceType} does not support roleManagedPolicyArns with a custom instanceProfileName in host mode`,
611 });
612 }
613
614 const { region } = yield* AWSEnvironment.current;
615 const runtimeUnitName = output?.runtimeUnitName ?? (yield* createRuntimeUnitName(id));
616 const assetPrefix = output?.assetPrefix ?? `ec2/${runtimeUnitName}`;
617 const bundleKey = `${assetPrefix}/bundle.zip`;
618 const envKey = `${assetPrefix}/env`;
619 const policyName = output?.policyName ?? (yield* createPolicyName(id));
620
621 const managedIam = !news.instanceProfileName;
622 let roleName: string;
623 let roleArn: string | undefined;
624 let instanceProfileName: string | undefined;
625 let instanceProfileArn: string | undefined;
626
627 if (managedIam) {
628 roleName = output?.roleName ?? (yield* createRoleName(id));
629 roleArn =
630 output?.roleArn ??
631 (yield* ensureManagedRole({
632 id,
633 roleName,
634 managedPolicyArns: news.roleManagedPolicyArns ?? [],
635 }));
636 const profileName = output?.instanceProfileName ?? (yield* createManagedProfileName(id));
637 const profile = yield* ensureManagedInstanceProfile({
638 id,
639 profileName,
640 roleName,
641 });
642 instanceProfileName = profile.instanceProfileName;
643 instanceProfileArn = profile.instanceProfileArn;
644 } else {
645 const profile = yield* iam.getInstanceProfile({
646 InstanceProfileName: news.instanceProfileName!,
647 });
648 const role = profile.InstanceProfile.Roles?.[0];
649 if (!role?.RoleName) {
650 return yield* new EC2HostedInvalidProps({
651 message: `Instance profile '${news.instanceProfileName}' must have a role attached for host mode`,
652 });
653 }
654 roleName = role.RoleName;
655 roleArn = role.Arn;
656 instanceProfileName = profile.InstanceProfile.InstanceProfileName;
657 instanceProfileArn = profile.InstanceProfile.Arn;
658 }
659
660 const bindingEnv = yield* attachHostedBindings({
661 roleName,
662 policyName,
663 assetPrefix,
664 bindings,
665 });
666 const env = {
667 ...bindingEnv,
668 ...alchemyEnv,
669 // Lambda injects AWS_REGION natively; an EC2 systemd service does not
670 // get one, and the runtime's `Region.fromEnv()` (and any composition
671 // code that reads the region, e.g. EC2.Network's runtime AZ branch)
672 // dies without it.
673 AWS_REGION: region,
674 ...(news.port !== undefined ? { PORT: news.port } : {}),
675 ...news.env,
676 };
677
678 const { archive, hash } = yield* bundleProgram(id, news);
679 yield* uploadHostedArtifacts({
680 bundleKey,
681 envKey,
682 archive,
683 env,
684 });
685
686 const hostedUserData = yield* renderHostedUserData({
687 unitName: runtimeUnitName,
688 bundleKey,
689 envKey,
690 region,
691 });
692
693 return {
694 userData: mergeUserData(hostedUserData, news.userData),
695 roleName,
696 roleArn,
697 policyName,
698 instanceProfileName,
699 instanceProfileArn,
700 managedIam,
701 runtimeUnitName,
702 assetPrefix,
703 code: {
704 hash,
705 },
706 } satisfies Ec2HostedRuntimeState;
707 });
708
709 const cleanupHostedRuntime = Effect.fn(function* ({
710 output,
711 session,
712 }: {
713 output: Ec2HostedCleanupState;
714 session?: Pick<ScopedPlanStatusSession, "note">;
715 }) {
716 if (output.roleName && output.policyName) {
717 yield* iam
718 .deleteRolePolicy({
719 RoleName: output.roleName,
720 PolicyName: output.policyName,
721 })
722 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
723 }
724
725 if (output.managedIam && output.roleName) {
726 const roleName = output.roleName;
727 // State written before the instance profile name was recorded (e.g.
728 // LaunchTemplate) lacks it: find the managed role's profiles instead.
729 const instanceProfileNames = output.instanceProfileName
730 ? [output.instanceProfileName]
731 : yield* iam.listInstanceProfilesForRole({ RoleName: roleName }).pipe(
732 Effect.map((result) =>
733 (result.InstanceProfiles ?? []).map((profile) => profile.InstanceProfileName),
734 ),
735 Effect.catchTag("NoSuchEntityException", () => Effect.succeed([])),
736 );
737 const attachedPolicyArns = yield* listAttachedPolicyArns(roleName).pipe(
738 Effect.orElseSucceed(() => []),
739 );
740 for (const instanceProfileName of instanceProfileNames) {
741 yield* iam
742 .removeRoleFromInstanceProfile({
743 InstanceProfileName: instanceProfileName,
744 RoleName: roleName,
745 })
746 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
747 yield* iam
748 .deleteInstanceProfile({
749 InstanceProfileName: instanceProfileName,
750 })
751 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
752 }
753 for (const policyArn of attachedPolicyArns) {
754 yield* iam
755 .detachRolePolicy({
756 RoleName: roleName,
757 PolicyArn: policyArn,
758 })
759 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
760 }
761 yield* iam
762 .deleteRole({
763 RoleName: roleName,
764 })
765 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
766 }
767
768 if (output.assetPrefix) {
769 for (const key of [`${output.assetPrefix}/bundle.zip`, `${output.assetPrefix}/env`]) {
770 yield* s3
771 .deleteObject({
772 Bucket: yield* Assets.BucketName,
773 Key: key,
774 })
775 .pipe(Effect.catchTag("NoSuchKey", () => Effect.void));
776 }
777 }
778
779 if (session) {
780 yield* session.note(`Cleaned hosted assets for ${resourceType}`);
781 }
782 });
783
784 const buildEc2NetworkData = ({
785 subnetId,
786 securityGroupIds,
787 associatePublicIpAddress,
788 privateIpAddress,
789 }: Pick<
790 Ec2HostedProps,
791 "subnetId" | "securityGroupIds" | "associatePublicIpAddress" | "privateIpAddress"
792 >) => {
793 const groups = normalizeSecurityGroups(securityGroupIds);
794 const usePrimaryNetworkInterface =
795 subnetId !== undefined ||
796 associatePublicIpAddress !== undefined ||
797 privateIpAddress !== undefined;
798
799 return {
800 usePrimaryNetworkInterface,
801 groups,
802 networkInterfaces: usePrimaryNetworkInterface
803 ? [
804 {
805 DeviceIndex: 0,
806 SubnetId: subnetId,
807 Groups: groups.length > 0 ? groups : undefined,
808 AssociatePublicIpAddress: associatePublicIpAddress,
809 PrivateIpAddress: privateIpAddress,
810 DeleteOnTermination: true,
811 },
812 ]
813 : undefined,
814 };
815 };
816
817 const buildLaunchTemplateData = (
818 news: Pick<
819 Ec2HostedProps,
820 | "imageId"
821 | "instanceType"
822 | "keyName"
823 | "subnetId"
824 | "securityGroupIds"
825 | "associatePublicIpAddress"
826 | "privateIpAddress"
827 | "availabilityZone"
828 | "tags"
829 | "metadataOptions"
830 >,
831 runtime: Pick<Ec2HostedRuntimeState, "userData" | "instanceProfileName">,
832 ) => {
833 const encodedUserData = runtime.userData
834 ? Buffer.from(runtime.userData).toString("base64")
835 : undefined;
836 const network = buildEc2NetworkData(news);
837 const instanceTags = {
838 ...news.tags,
839 };
840
841 return {
842 ImageId: news.imageId,
843 InstanceType: news.instanceType,
844 KeyName: news.keyName as string | undefined,
845 IamInstanceProfile: runtime.instanceProfileName
846 ? {
847 Name: runtime.instanceProfileName,
848 }
849 : undefined,
850 UserData: encodedUserData,
851 Placement: news.availabilityZone
852 ? {
853 AvailabilityZone: news.availabilityZone,
854 }
855 : undefined,
856 NetworkInterfaces: network.networkInterfaces,
857 SubnetId: network.usePrimaryNetworkInterface ? undefined : news.subnetId,
858 SecurityGroupIds: network.usePrimaryNetworkInterface
859 ? undefined
860 : network.groups.length > 0
861 ? network.groups
862 : undefined,
863 PrivateIpAddress: network.usePrimaryNetworkInterface ? undefined : news.privateIpAddress,
864 MetadataOptions: news.metadataOptions
865 ? {
866 HttpTokens: news.metadataOptions.httpTokens,
867 HttpPutResponseHopLimit: news.metadataOptions.httpPutResponseHopLimit,
868 HttpEndpoint: news.metadataOptions.httpEndpoint,
869 HttpProtocolIpv6: news.metadataOptions.httpProtocolIpv6,
870 InstanceMetadataTags: news.metadataOptions.instanceMetadataTags,
871 }
872 : undefined,
873 TagSpecifications:
874 Object.keys(instanceTags).length > 0
875 ? [
876 {
877 ResourceType: "instance",
878 Tags: createTagsList(instanceTags),
879 },
880 ]
881 : undefined,
882 };
883 };
884
885 return {
886 normalizeSecurityGroups,
887 buildLaunchTemplateData,
888 bundleProgram,
889 resolveHostedRuntime,
890 cleanupHostedRuntime,
891 };
892 };