@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 600 lines 20 KB
Raw
1 import type { Credentials } from "@distilled.cloud/aws/Credentials";
2 import * as ec2 from "@distilled.cloud/aws/ec2";
3 import { Region } from "@distilled.cloud/aws/Region";
4 import * as Bundle from "alchemy/Bundle/Bundle";
5 import { deepEqual, isResolved } from "alchemy/Diff";
6 import type { Input } from "alchemy/Input";
7 import { createPhysicalName } from "alchemy/PhysicalName";
8 import { Platform, type Main, type PlatformProps } from "alchemy/Platform";
9 import * as Provider from "alchemy/Provider";
10 import { Resource } from "alchemy/Resource";
11 import { Stack } from "alchemy/Stack";
12 import { Stage } from "alchemy/Stage";
13 import { createInternalTags, diffTags, hasTags } from "alchemy/Tags";
14 import * as Data from "effect/Data";
15 import * as Effect from "effect/Effect";
16 import * as FileSystem from "effect/FileSystem";
17 import * as Stream from "effect/Stream";
18 import type * as rolldown from "rolldown";
19 import {
20 createEc2HostRuntimeContext,
21 createEc2HostedSupport,
22 type Ec2HostRuntimeContext,
23 type InstanceMetadataOptions,
24 } from "../EC2/hosted.ts";
25 import type { SecurityGroupId } from "../EC2/SecurityGroup.ts";
26 import type { AccountID } from "../Environment.ts";
27 import type { PolicyStatement } from "../IAM/Policy.ts";
28 import { AWSEnvironment } from "../index.ts";
29 import type { Providers } from "../Providers.ts";
30 import type { RegionID } from "../Region.ts";
31
32 export class LaunchTemplateUnexpectedResponse extends Data.TaggedError(
33 "LaunchTemplateUnexpectedResponse",
34 )<{
35 readonly message: string;
36 readonly cause?: unknown;
37 }> {}
38
39 export class LaunchTemplateConflict extends Data.TaggedError("LaunchTemplateConflict")<{
40 readonly message: string;
41 readonly cause?: unknown;
42 }> {}
43
44 export type LaunchTemplateId = `lt-${string}`;
45 export type LaunchTemplateName = string;
46 export type LaunchTemplateArn =
47 `arn:aws:ec2:${RegionID}:${AccountID}:launch-template/${LaunchTemplateId}`;
48
49 export interface LaunchTemplateProps extends PlatformProps {
50 /**
51 * Launch template name. If omitted, a deterministic name is generated.
52 */
53 launchTemplateName?: string;
54 /**
55 * AMI ID to launch.
56 */
57 imageId: string;
58 /**
59 * EC2 instance type, such as `t3.micro`.
60 */
61 instanceType: string;
62 /**
63 * Security groups to attach to the primary network interface.
64 */
65 securityGroupIds?: Input<SecurityGroupId>[];
66 /**
67 * Optional EC2 key pair name for SSH access.
68 */
69 keyName?: string;
70 /**
71 * Optional IAM instance profile name to attach at launch.
72 */
73 instanceProfileName?: string;
74 /**
75 * User data script to provide at launch time.
76 */
77 userData?: string;
78 /**
79 * Whether to associate a public IPv4 address on launch.
80 */
81 associatePublicIpAddress?: boolean;
82 /**
83 * Instance Metadata Service (IMDS) options for launched instances, e.g.
84 * requiring IMDSv2 and limiting the hop count. Changes publish a new
85 * template version. Unset fields keep the AMI / account defaults.
86 */
87 metadataOptions?: InstanceMetadataOptions;
88 /**
89 * User-defined tags to apply to the launch template and launched instances.
90 */
91 tags?: Record<string, string>;
92 /**
93 * Module entrypoint for the bundled instance program.
94 * When omitted, the launch template behaves as a low-level EC2 primitive.
95 */
96 main?: string;
97 /**
98 * Named export to load from `main`.
99 * @default "default"
100 */
101 handler?: string;
102 /**
103 * Port exposed by the process, if any.
104 * @default 3000
105 */
106 port?: number;
107 /**
108 * Additional environment variables for the hosted process.
109 */
110 env?: Record<string, any>;
111 /**
112 * Bundler configuration for the hosted process entrypoint.
113 */
114 build?: {
115 input?: Partial<rolldown.InputOptions>;
116 output?: Partial<rolldown.OutputOptions>;
117 };
118 /**
119 * Additional managed policy ARNs for the managed instance role.
120 * This can only be used when Alchemy manages the instance profile.
121 */
122 roleManagedPolicyArns?: string[];
123 }
124
125 export interface LaunchTemplate extends Resource<
126 "AWS.AutoScaling.LaunchTemplate",
127 LaunchTemplateProps,
128 {
129 /**
130 * ID of the launch template (`lt-...`).
131 */
132 launchTemplateId: LaunchTemplateId;
133 /**
134 * ARN of the launch template.
135 */
136 launchTemplateArn: LaunchTemplateArn;
137 /**
138 * Name of the launch template.
139 */
140 launchTemplateName: LaunchTemplateName;
141 /**
142 * Version number launched by default.
143 */
144 defaultVersionNumber: number;
145 /**
146 * Most recently created version number.
147 */
148 latestVersionNumber: number;
149 /**
150 * Tags on the launch template.
151 */
152 tags: Record<string, string>;
153 /**
154 * ARN of the managed instance role, when Alchemy manages IAM.
155 */
156 roleArn?: string;
157 /**
158 * Name of the managed instance role, when Alchemy manages IAM.
159 */
160 roleName?: string;
161 /**
162 * Name of the inline policy on the managed instance role.
163 */
164 policyName?: string;
165 /**
166 * Name of the instance profile launched instances use; the managed one
167 * when Alchemy manages IAM.
168 */
169 instanceProfileName?: string;
170 /**
171 * Whether Alchemy manages the instance profile/role for the hosted
172 * program.
173 */
174 managedIam?: boolean;
175 /**
176 * systemd unit name running the hosted program on instances.
177 */
178 runtimeUnitName?: string;
179 /**
180 * S3 key prefix where the bundled program assets are staged.
181 */
182 assetPrefix?: string;
183 /**
184 * Bundled program code metadata.
185 */
186 code?: {
187 /**
188 * Content hash of the bundled entrypoint.
189 */
190 hash: string;
191 };
192 },
193 {
194 /**
195 * Environment variables contributed by bindings to the hosted process.
196 */
197 env?: Record<string, any>;
198 /**
199 * IAM policy statements contributed by bindings to the instance role.
200 */
201 policyStatements?: PolicyStatement[];
202 },
203 Providers
204 > {}
205
206 export type LaunchTemplateServices = Credentials | Region;
207
208 export type LaunchTemplateShape = Main<LaunchTemplateServices>;
209
210 export type LaunchTemplateRuntimeContext = Ec2HostRuntimeContext;
211
212 /**
213 * A launch template that preserves the `Host` authoring model used by
214 * `AWS.EC2.Instance`, but packages that host configuration for use with an
215 * Auto Scaling Group.
216 * ### Creating a Launch Template
217 * **Example:** Basic Launch Template
218 * ```typescript
219 * import { LaunchTemplate } from "@alchemy.run/aws/AutoScaling";
220 *
221 * const template = yield* LaunchTemplate("Template", {
222 * imageId: "ami-0abcdef1234567890",
223 * instanceType: "t3.micro",
224 * });
225 * ```
226 *
227 * **Example:** Launch a fleet from the template
228 * ```typescript
229 * import { AutoScalingGroup } from "@alchemy.run/aws/AutoScaling";
230 *
231 * const group = yield* AutoScalingGroup("Fleet", {
232 * launchTemplate: template,
233 * subnetIds: [subnet.subnetId],
234 * minSize: 1,
235 * maxSize: 3,
236 * });
237 * ```
238 *
239 * ### Hosting Processes
240 * **Example:** Hosted HTTP Launch Template
241 * ```typescript
242 * const template = yield* Effect.gen(function* () {
243 * yield* Http.serve(HttpServerResponse.json({ ok: true }));
244 *
245 * return {
246 * main: import.meta.url,
247 * imageId,
248 * instanceType: "t3.small",
249 * securityGroupIds: [securityGroup.groupId],
250 * port: 3000,
251 * };
252 * }).pipe(
253 * Effect.provide(AWS.EC2.HttpServer),
254 * AWS.AutoScaling.LaunchTemplate("ApiTemplate"),
255 * );
256 * ```
257 *
258 * @resource
259 */
260 export const LaunchTemplate: Platform<
261 LaunchTemplate,
262 LaunchTemplateServices,
263 LaunchTemplateShape,
264 LaunchTemplateRuntimeContext
265 > = Platform("AWS.AutoScaling.LaunchTemplate", {
266 createRuntimeContext: createEc2HostRuntimeContext("AWS.AutoScaling.LaunchTemplate"),
267 });
268
269 export const LaunchTemplateProvider = () =>
270 Provider.effect(
271 LaunchTemplate,
272 Effect.gen(function* () {
273 const stack = yield* Stack;
274 const stage = yield* Stage;
275 const fs = yield* FileSystem.FileSystem;
276 const virtualEntryPlugin = yield* Bundle.virtualEntryPlugin;
277
278 const hosted = createEc2HostedSupport({
279 stackName: stack.name,
280 stage,
281 fs,
282 virtualEntryPlugin,
283 resourceType: "AWS.AutoScaling.LaunchTemplate",
284 });
285
286 const toName = (id: string, props: { launchTemplateName?: string } = {}) =>
287 props.launchTemplateName
288 ? Effect.succeed(props.launchTemplateName)
289 : createPhysicalName({ id, maxLength: 128, lowercase: true });
290
291 const toArn = (launchTemplateId: LaunchTemplateId) =>
292 AWSEnvironment.current.pipe(
293 Effect.map(
294 (env) =>
295 `arn:aws:ec2:${env.region}:${env.accountId}:launch-template/${launchTemplateId}` as LaunchTemplateArn,
296 ),
297 );
298
299 const describeById = (launchTemplateId: string) =>
300 ec2
301 .describeLaunchTemplates({
302 LaunchTemplateIds: [launchTemplateId],
303 } as any)
304 .pipe(
305 Effect.map((result) => result.LaunchTemplates?.[0]),
306 Effect.catchIf(isLaunchTemplateNotFound, () => Effect.undefined),
307 );
308
309 const describeByName = (launchTemplateName: string) =>
310 ec2
311 .describeLaunchTemplates({
312 LaunchTemplateNames: [launchTemplateName],
313 } as any)
314 .pipe(
315 Effect.map((result) => result.LaunchTemplates?.[0]),
316 Effect.catchIf(isLaunchTemplateNotFound, () => Effect.undefined),
317 );
318
319 const syncTemplateTags = Effect.fn(function* ({
320 launchTemplateId,
321 oldTags,
322 newTags,
323 }: {
324 launchTemplateId: LaunchTemplateId;
325 oldTags: Record<string, string>;
326 newTags: Record<string, string>;
327 }) {
328 const { removed, upsert } = diffTags(oldTags, newTags);
329 if (removed.length > 0) {
330 yield* ec2.deleteTags({
331 Resources: [launchTemplateId],
332 Tags: removed.map((key) => ({ Key: key })),
333 });
334 }
335 if (upsert.length > 0) {
336 yield* ec2.createTags({
337 Resources: [launchTemplateId],
338 Tags: upsert,
339 });
340 }
341 });
342
343 const createVersion = Effect.fn(function* ({
344 launchTemplateId,
345 news,
346 runtime,
347 }: {
348 launchTemplateId: LaunchTemplateId;
349 news: LaunchTemplateProps;
350 runtime: {
351 userData?: string;
352 instanceProfileName?: string;
353 code?: {
354 hash: string;
355 };
356 };
357 }) {
358 const created = yield* ec2.createLaunchTemplateVersion({
359 LaunchTemplateId: launchTemplateId,
360 VersionDescription: runtime.code?.hash ?? "alchemy-update",
361 LaunchTemplateData: hosted.buildLaunchTemplateData(
362 {
363 imageId: news.imageId,
364 instanceType: news.instanceType,
365 keyName: news.keyName,
366 securityGroupIds: news.securityGroupIds as string[] | undefined,
367 associatePublicIpAddress: news.associatePublicIpAddress,
368 metadataOptions: news.metadataOptions,
369 tags: news.tags,
370 },
371 runtime,
372 ),
373 } as any);
374
375 const versionNumber = created.LaunchTemplateVersion?.VersionNumber;
376 if (versionNumber === undefined) {
377 return yield* new LaunchTemplateUnexpectedResponse({
378 message: `createLaunchTemplateVersion returned no version for '${launchTemplateId}'`,
379 });
380 }
381
382 yield* ec2.modifyLaunchTemplate({
383 LaunchTemplateId: launchTemplateId,
384 DefaultVersion: String(versionNumber),
385 } as any);
386
387 return Number(versionNumber);
388 });
389
390 const toAttributes = Effect.fn(function* (
391 template: ec2.LaunchTemplate,
392 runtime: Partial<LaunchTemplate["Attributes"]> = {},
393 ) {
394 return {
395 launchTemplateId: template.LaunchTemplateId as LaunchTemplateId,
396 launchTemplateArn: yield* toArn(template.LaunchTemplateId as LaunchTemplateId),
397 launchTemplateName: template.LaunchTemplateName!,
398 defaultVersionNumber: Number(template.DefaultVersionNumber ?? 1),
399 latestVersionNumber: Number(
400 template.LatestVersionNumber ?? template.DefaultVersionNumber ?? 1,
401 ),
402 tags: toTagRecord(template.Tags),
403 roleArn: runtime.roleArn,
404 roleName: runtime.roleName,
405 policyName: runtime.policyName,
406 instanceProfileName: runtime.instanceProfileName,
407 managedIam: runtime.managedIam,
408 runtimeUnitName: runtime.runtimeUnitName,
409 assetPrefix: runtime.assetPrefix,
410 code: runtime.code,
411 } satisfies LaunchTemplate["Attributes"];
412 });
413
414 return {
415 stables: ["launchTemplateId", "launchTemplateArn", "launchTemplateName"],
416 diff: Effect.fn(function* ({ id, olds, news: _news, output }) {
417 if (!isResolved(_news)) return undefined;
418 const news = _news as typeof olds;
419 const oldName = yield* toName(id, olds ?? {});
420 const newName = yield* toName(id, news ?? {});
421 if (oldName !== newName) {
422 return { action: "replace" } as const;
423 }
424
425 if (!deepEqual(olds, news)) {
426 return {
427 action: "update",
428 stables: ["launchTemplateId", "launchTemplateArn", "launchTemplateName"],
429 } as const;
430 }
431
432 // The hosted bundle hash participates in planning: a change confined
433 // to the runtime program (or its imports) leaves every prop equal,
434 // so re-bundle and compare against the deployed hash. A mismatch
435 // plans an in-place update, whose reconcile publishes a new template
436 // version carrying the new bundle.
437 if (news.main && output?.code?.hash) {
438 const { hash } = yield* hosted.bundleProgram(id, news);
439 if (hash !== output.code.hash) {
440 return {
441 action: "update",
442 stables: ["launchTemplateId", "launchTemplateArn", "launchTemplateName"],
443 } as const;
444 }
445 }
446 }),
447 read: Effect.fn(function* ({ id, olds, output }) {
448 const template =
449 (output?.launchTemplateId && (yield* describeById(output.launchTemplateId))) ??
450 (yield* describeByName(yield* toName(id, olds ?? {})));
451
452 return template
453 ? yield* toAttributes(template, {
454 roleArn: output?.roleArn,
455 roleName: output?.roleName,
456 policyName: output?.policyName,
457 instanceProfileName: output?.instanceProfileName,
458 managedIam: output?.managedIam,
459 runtimeUnitName: output?.runtimeUnitName,
460 assetPrefix: output?.assetPrefix,
461 code: output?.code,
462 })
463 : undefined;
464 }),
465 list: () =>
466 ec2.describeLaunchTemplates.pages({}).pipe(
467 Stream.runCollect,
468 Effect.flatMap((chunk) =>
469 Effect.forEach(
470 Array.from(chunk).flatMap((page) => page.LaunchTemplates ?? []),
471 (template) => toAttributes(template),
472 ),
473 ),
474 ),
475 reconcile: Effect.fn(function* ({ id, news, output, bindings, session }) {
476 const launchTemplateName = output?.launchTemplateName ?? (yield* toName(id, news));
477 const desiredTags = {
478 ...(yield* createInternalTags(id)),
479 ...news.tags,
480 };
481 const runtime = yield* hosted.resolveHostedRuntime({
482 id,
483 news,
484 bindings,
485 output,
486 });
487
488 // Observe — fetch live cloud state. We try both lookup paths
489 // (id from output, name from desired) so the reconciler
490 // converges whether `output` is fresh, stale, or missing.
491 let existing =
492 (output?.launchTemplateId && (yield* describeById(output.launchTemplateId))) ||
493 (yield* describeByName(launchTemplateName));
494
495 // Ensure — create the launch template if missing. We must
496 // verify alchemy ownership via tags here (since this resource
497 // does not implement `read` adoption gating).
498 if (!existing) {
499 const created = yield* ec2.createLaunchTemplate({
500 LaunchTemplateName: launchTemplateName,
501 VersionDescription: runtime.code?.hash ?? "alchemy-create",
502 TagSpecifications: [
503 {
504 ResourceType: "launch-template",
505 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
506 Key,
507 Value,
508 })),
509 },
510 ],
511 LaunchTemplateData: hosted.buildLaunchTemplateData(
512 {
513 imageId: news.imageId,
514 instanceType: news.instanceType,
515 keyName: news.keyName,
516 securityGroupIds: news.securityGroupIds as string[] | undefined,
517 associatePublicIpAddress: news.associatePublicIpAddress,
518 metadataOptions: news.metadataOptions,
519 tags: desiredTags,
520 },
521 runtime,
522 ),
523 } as any);
524 const template = created.LaunchTemplate;
525 if (!template?.LaunchTemplateId || !template.LaunchTemplateName) {
526 return yield* new LaunchTemplateUnexpectedResponse({
527 message: `createLaunchTemplate returned no launch template for '${id}'`,
528 });
529 }
530 yield* session.note(template.LaunchTemplateId);
531 return yield* toAttributes(template as ec2.LaunchTemplate, runtime);
532 }
533
534 if (!hasTags(desiredTags, toTagRecord(existing.Tags))) {
535 return yield* new LaunchTemplateConflict({
536 message: `Launch template '${launchTemplateName}' already exists and is not managed by alchemy`,
537 });
538 }
539
540 // Sync version — each reconcile creates a new version pinned as
541 // the default. ASGs that reference `$Default` automatically
542 // pick up the new version.
543 yield* createVersion({
544 launchTemplateId: existing.LaunchTemplateId as LaunchTemplateId,
545 news,
546 runtime,
547 });
548
549 // Sync tags — diff observed cloud tags against desired.
550 yield* syncTemplateTags({
551 launchTemplateId: existing.LaunchTemplateId as LaunchTemplateId,
552 oldTags: toTagRecord(existing.Tags),
553 newTags: desiredTags,
554 });
555
556 const refreshed = yield* describeById(existing.LaunchTemplateId!);
557 if (!refreshed) {
558 return yield* new LaunchTemplateUnexpectedResponse({
559 message: `Launch template '${launchTemplateName}' was not readable after reconcile`,
560 });
561 }
562 yield* session.note(refreshed.LaunchTemplateId!);
563 return yield* toAttributes(refreshed, runtime);
564 }),
565 delete: Effect.fn(function* ({ output, session }) {
566 yield* ec2
567 .deleteLaunchTemplate({
568 LaunchTemplateId: output.launchTemplateId,
569 } as any)
570 .pipe(Effect.catchIf(isLaunchTemplateNotFound, () => Effect.void));
571
572 yield* hosted.cleanupHostedRuntime({ output, session });
573 }),
574 };
575 }),
576 );
577
578 const isLaunchTemplateNotFound = (error: unknown) => {
579 const tag = (error as { _tag?: string })?._tag;
580 return (
581 tag === "InvalidLaunchTemplateNameNotFoundException" ||
582 tag === "InvalidLaunchTemplateIdNotFoundException" ||
583 tag === "InvalidLaunchTemplateId.Malformed" ||
584 tag === "InvalidLaunchTemplateId.NotFound" ||
585 // Live `describeLaunchTemplates` surfaces the dot-form codes, which the
586 // ec2 SDK leaves untyped — a missing template on the read-before-create
587 // probe otherwise fails the whole plan.
588 tag === "InvalidLaunchTemplateName.NotFoundException" ||
589 tag === "InvalidLaunchTemplateId.NotFoundException"
590 );
591 };
592
593 const toTagRecord = (tags?: Array<{ Key?: string; Value?: string }>) =>
594 Object.fromEntries(
595 (tags ?? [])
596 .filter((tag): tag is { Key: string; Value: string } =>
597 Boolean(tag.Key && tag.Value !== undefined),
598 )
599 .map((tag) => [tag.Key, tag.Value]),
600 );