@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, 04:45 UTC

main
ts 375 lines 13.7 KB
Raw
1 import * as imagebuilder from "@distilled.cloud/aws/imagebuilder";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11 import {
12 imageBuilderArn,
13 immutableVersionKeysChanged,
14 retryWhileDependedOn,
15 syncImageBuilderTags,
16 toTagRecord,
17 } from "./internal.ts";
18
19 export class ComponentUnexpectedResponse extends Data.TaggedError("ComponentUnexpectedResponse")<{
20 readonly message: string;
21 readonly cause?: unknown;
22 }> {}
23
24 /**
25 * A Component must define its document inline (`data`) or point at an S3
26 * object (`uri`) — exactly one of the two.
27 */
28 export class ComponentSourceInvalid extends Data.TaggedError(
29 "AWS::ImageBuilder::ComponentSourceInvalid",
30 )<{
31 message: string;
32 }> {}
33
34 /**
35 * Image Builder component versions are immutable — the deployed document
36 * differs from the desired one but the semantic version was not bumped, so
37 * the cloud state cannot be converged.
38 */
39 export class ComponentVersionImmutable extends Data.TaggedError(
40 "AWS::ImageBuilder::ComponentVersionImmutable",
41 )<{
42 message: string;
43 }> {}
44
45 export interface ComponentProps {
46 /**
47 * Name of the component. If omitted, a deterministic physical name is
48 * generated. Changing the name replaces the component.
49 */
50 componentName?: string;
51 /**
52 * Semantic version of the component (`major.minor.patch`). Components
53 * are immutable — bump the version when changing `data`/`uri`. Changing
54 * the version replaces the component.
55 * @default "1.0.0"
56 */
57 semanticVersion?: string;
58 /**
59 * Operating system platform of the component. Changing the platform
60 * replaces the component.
61 */
62 platform: "Linux" | "Windows" | "macOS";
63 /**
64 * Inline YAML component document (AWSTOMC schema) defining the build /
65 * validate / test phases. Mutually exclusive with `uri`. Changing the
66 * data replaces the component.
67 */
68 data?: string;
69 /**
70 * S3 URI of a YAML component document. Use for documents larger than
71 * 64 KB. Mutually exclusive with `data`. Changing the URI replaces the
72 * component.
73 */
74 uri?: string;
75 /**
76 * Description of the component. Changing the description replaces the
77 * component (component versions are immutable).
78 */
79 description?: string;
80 /**
81 * Description of the change in this version compared to the previous
82 * one. Changing it replaces the component.
83 */
84 changeDescription?: string;
85 /**
86 * Operating system versions supported by the component
87 * (e.g. `["Amazon Linux 2023"]`). Changing them replaces the component.
88 */
89 supportedOsVersions?: string[];
90 /**
91 * KMS key used to encrypt the component. Changing it replaces the
92 * component.
93 */
94 kmsKeyId?: string;
95 /**
96 * User-defined tags for the component.
97 */
98 tags?: Record<string, string>;
99 }
100
101 export interface Component extends Resource<
102 "AWS.ImageBuilder.Component",
103 ComponentProps,
104 {
105 /** The name of the component. */
106 componentName: string;
107 /** The ARN of this component build version. */
108 componentBuildVersionArn: string;
109 /** The semantic version of the component. */
110 semanticVersion: string;
111 /** The OS platform of the component (`Linux` / `Windows`). */
112 platform: string;
113 /** Whether the component is a `BUILD` or `TEST` component. */
114 type: string | undefined;
115 /** When the component was created. */
116 dateCreated: string | undefined;
117 },
118 never,
119 Providers
120 > {}
121
122 /**
123 * An EC2 Image Builder component — a YAML document that defines the build,
124 * validation, and test steps applied to an instance during image creation.
125 *
126 * Components are immutable versions: every property except `tags` replaces
127 * the component. Bump `semanticVersion` when changing the document.
128 * ### Creating a Component
129 * **Example:** Inline Build Component
130 * ```typescript
131 * const component = yield* ImageBuilder.Component("Setup", {
132 * platform: "Linux",
133 * semanticVersion: "1.0.0",
134 * data: [
135 * "name: setup",
136 * "description: install packages",
137 * "schemaVersion: 1.2",
138 * "phases:",
139 * " - name: build",
140 * " steps:",
141 * " - name: install",
142 * " action: ExecuteBash",
143 * " inputs:",
144 * " commands:",
145 * " - dnf install -y htop",
146 * ].join("\n"),
147 * });
148 * ```
149 *
150 * ### Using in an Image Recipe
151 * **Example:** Reference from a Recipe
152 * ```typescript
153 * const recipe = yield* ImageBuilder.ImageRecipe("Recipe", {
154 * parentImage: "arn:aws:imagebuilder:us-west-2:aws:image/amazon-linux-2023-x86/x.x.x",
155 * components: [{ componentArn: component.componentBuildVersionArn }],
156 * });
157 * ```
158 *
159 * @resource
160 */
161 export const Component = Resource<Component>("AWS.ImageBuilder.Component");
162
163 export const ComponentProvider = () =>
164 Provider.effect(
165 Component,
166 Effect.gen(function* () {
167 const toName = (id: string, props: ComponentProps) =>
168 props.componentName
169 ? Effect.succeed(props.componentName)
170 : createPhysicalName({ id, maxLength: 126 });
171
172 const toVersion = (props: ComponentProps) => props.semanticVersion ?? "1.0.0";
173
174 /**
175 * CreateComponent always mints build version 1 for a fresh
176 * name/version pair (subsequent creates of the same pair are
177 * rejected), so the build-version ARN is deterministic.
178 */
179 const toBuildVersionArn = (name: string, version: string) =>
180 imageBuilderArn("component", `${name}/${version}/1`);
181
182 const getComponent = Effect.fn(function* (arn: string) {
183 const response = yield* imagebuilder
184 .getComponent({ componentBuildVersionArn: arn })
185 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
186 return response?.component;
187 });
188
189 const toAttrs = Effect.fn(function* (component: imagebuilder.Component) {
190 if (!component.arn || !component.name || !component.version) {
191 return yield* new ComponentUnexpectedResponse({
192 message: "Image Builder component is missing its ARN, name, or version",
193 });
194 }
195 return {
196 componentName: component.name,
197 componentBuildVersionArn: component.arn,
198 semanticVersion: component.version,
199 platform: component.platform ?? "",
200 type: component.type,
201 dateCreated: component.dateCreated,
202 };
203 });
204
205 return {
206 stables: ["componentName", "semanticVersion"],
207
208 // Components are immutable — any changed property except tags
209 // replaces. Individual keys may still hold unresolved Outputs at
210 // plan time; compare per key so a resolved change still plans a
211 // replacement, and let the reconcile immutability guard catch
212 // drift hidden behind an unresolved key.
213 diff: Effect.fn(function* ({ olds, news }) {
214 const immutableKeys = [
215 "componentName",
216 "semanticVersion",
217 "platform",
218 "data",
219 "uri",
220 "description",
221 "changeDescription",
222 "supportedOsVersions",
223 "kmsKeyId",
224 ] as const;
225 if (immutableVersionKeysChanged(olds, news, immutableKeys)) {
226 return { action: "replace" } as const;
227 }
228 }),
229
230 read: Effect.fn(function* ({ id, olds, output }) {
231 const arn =
232 output?.componentBuildVersionArn ??
233 (yield* toBuildVersionArn(yield* toName(id, olds), toVersion(olds)));
234 const component = yield* getComponent(arn);
235 if (component === undefined) return undefined;
236 const attrs = yield* toAttrs(component);
237 const tags = toTagRecord(component.tags);
238 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
239 }),
240
241 reconcile: Effect.fn(function* ({ id, news, output, session }) {
242 // One idempotency token per reconcile — retries within this run
243 // are deduplicated by the API.
244 const clientToken = yield* Effect.sync(() => crypto.randomUUID());
245 if ((news.data === undefined) === (news.uri === undefined)) {
246 return yield* new ComponentSourceInvalid({
247 message:
248 "Specify exactly one of `data` (inline YAML) or `uri` (S3 object) for an Image Builder component",
249 });
250 }
251 const name = output?.componentName ?? (yield* toName(id, news));
252 const version = output?.semanticVersion ?? toVersion(news);
253 const internalTags = yield* createInternalTags(id);
254 const desiredTags = { ...internalTags, ...news.tags };
255
256 // 1. Observe — cloud state is authoritative; output only caches
257 // the build-version ARN.
258 const arn = output?.componentBuildVersionArn ?? (yield* toBuildVersionArn(name, version));
259 let observed = yield* getComponent(arn);
260
261 // Immutability guard — the version already exists in the cloud
262 // with a different document. It cannot be converged in place; the
263 // user must bump `semanticVersion` (which replaces the component).
264 if (observed !== undefined && news.data !== undefined && observed.data !== news.data) {
265 return yield* new ComponentVersionImmutable({
266 message: `Image Builder component '${name}' version '${version}' already exists with a different document — bump semanticVersion to publish the change`,
267 });
268 }
269
270 // 2. Ensure — components are immutable, so a missing component is
271 // the only create path. A same-name/version conflict (race or
272 // an unbumped document change on a fixed name) surfaces as the
273 // API's typed error.
274 if (observed === undefined) {
275 const created = yield* imagebuilder.createComponent({
276 name,
277 semanticVersion: version,
278 platform: news.platform,
279 data: news.data,
280 uri: news.uri,
281 description: news.description,
282 changeDescription: news.changeDescription,
283 supportedOsVersions: news.supportedOsVersions,
284 kmsKeyId: news.kmsKeyId,
285 tags: desiredTags,
286 clientToken,
287 });
288 if (!created.componentBuildVersionArn) {
289 return yield* new ComponentUnexpectedResponse({
290 message: "CreateComponent returned no componentBuildVersionArn",
291 });
292 }
293 observed = yield* getComponent(created.componentBuildVersionArn);
294 if (observed === undefined) {
295 return yield* new ComponentUnexpectedResponse({
296 message: `created Image Builder component '${name}' is not readable`,
297 });
298 }
299 }
300
301 // 3. Sync — tags are the only mutable aspect; diff against
302 // OBSERVED cloud tags.
303 if (observed.arn) {
304 yield* syncImageBuilderTags(observed.arn, desiredTags);
305 }
306
307 // 4. Return fresh attributes.
308 yield* session.note(name);
309 return yield* toAttrs(observed);
310 }),
311
312 delete: Effect.fn(function* ({ output }) {
313 yield* retryWhileDependedOn(
314 imagebuilder.deleteComponent({
315 componentBuildVersionArn: output.componentBuildVersionArn,
316 }),
317 ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
318 }),
319
320 list: () =>
321 imagebuilder.listComponents.pages({ owner: "Self" }).pipe(
322 Stream.runCollect,
323 Effect.map((chunk) =>
324 Array.from(chunk).flatMap((page) =>
325 (page.componentVersionList ?? []).filter(
326 (
327 version,
328 ): version is imagebuilder.ComponentVersion & {
329 arn: string;
330 } => version.arn !== undefined,
331 ),
332 ),
333 ),
334 Effect.flatMap(
335 Effect.forEach(
336 (version) =>
337 imagebuilder
338 .listComponentBuildVersions({
339 componentVersionArn: version.arn,
340 })
341 .pipe(
342 Effect.map((response) =>
343 (response.componentSummaryList ?? []).filter(
344 (
345 summary,
346 ): summary is imagebuilder.ComponentSummary & {
347 arn: string;
348 name: string;
349 version: string;
350 } =>
351 summary.arn !== undefined &&
352 summary.name !== undefined &&
353 summary.version !== undefined,
354 ),
355 ),
356 // Tolerate a delete race — drop the version.
357 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed([])),
358 ),
359 { concurrency: 4 },
360 ),
361 ),
362 Effect.map((groups) =>
363 groups.flat().map((summary) => ({
364 componentName: summary.name,
365 componentBuildVersionArn: summary.arn,
366 semanticVersion: summary.version,
367 platform: summary.platform ?? "",
368 type: summary.type,
369 dateCreated: summary.dateCreated,
370 })),
371 ),
372 ),
373 };
374 }),
375 );