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

main
ts 386 lines 13.9 KB
Raw
1 import * as imagebuilder from "@distilled.cloud/aws/imagebuilder";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
8 import { toWireMinutes } from "alchemy/Util/Duration";
9 import * as Data from "effect/Data";
10 import type * as Duration from "effect/Duration";
11 import * as Effect from "effect/Effect";
12 import * as Stream from "effect/Stream";
13 import type { Providers } from "../Providers.ts";
14 import {
15 deleteImageBuilderLogGroup,
16 driftedFrom,
17 imageBuilderArn,
18 retryWhileDependedOn,
19 syncImageBuilderTags,
20 toTagRecord,
21 } from "./internal.ts";
22
23 export class ImagePipelineUnexpectedResponse extends Data.TaggedError(
24 "ImagePipelineUnexpectedResponse",
25 )<{
26 readonly message: string;
27 readonly cause?: unknown;
28 }> {}
29
30 /**
31 * Image test settings applied to builds of the pipeline. Mirrors the wire
32 * `ImageTestsConfiguration`, with the timeout expressed as a
33 * {@link Duration.Input} instead of raw minutes.
34 */
35 export interface ImageTestsConfiguration {
36 /**
37 * Whether to run tests on the output image.
38 * @default true
39 */
40 imageTestsEnabled?: boolean;
41 /**
42 * Maximum time tests may run before they are considered failed
43 * (e.g. `"90 minutes"`). AWS accepts 1 hour to 24 hours, in whole
44 * minutes on the wire.
45 * @default "12 hours"
46 */
47 timeout?: Duration.Input;
48 }
49
50 /** Convert the duration-typed test settings to the wire shape. */
51 const toWireImageTests = (
52 config: ImageTestsConfiguration | undefined,
53 ): imagebuilder.ImageTestsConfiguration | undefined =>
54 config === undefined
55 ? undefined
56 : {
57 imageTestsEnabled: config.imageTestsEnabled,
58 timeoutMinutes: toWireMinutes(config.timeout),
59 };
60
61 export interface ImagePipelineProps {
62 /**
63 * Name of the image pipeline. If omitted, a deterministic physical name
64 * is generated. Changing the name replaces the pipeline.
65 */
66 imagePipelineName?: string;
67 /**
68 * ARN of the image recipe that the pipeline builds. Exactly one of
69 * `imageRecipeArn` / `containerRecipeArn` is required.
70 */
71 imageRecipeArn?: string;
72 /**
73 * ARN of the container recipe that the pipeline builds.
74 */
75 containerRecipeArn?: string;
76 /**
77 * ARN of the infrastructure configuration used to build images.
78 */
79 infrastructureConfigurationArn: string;
80 /**
81 * ARN of the distribution configuration applied to output images.
82 */
83 distributionConfigurationArn?: string;
84 /**
85 * Description of the pipeline.
86 */
87 description?: string;
88 /**
89 * Image test settings (enable/disable tests, timeout).
90 */
91 imageTestsConfiguration?: ImageTestsConfiguration;
92 /**
93 * Collect additional information about the image being created,
94 * including the operating system and packages.
95 * @default true
96 */
97 enhancedImageMetadataEnabled?: boolean;
98 /**
99 * Build schedule (cron expression + start condition). Without a
100 * schedule the pipeline only builds on manual invocation.
101 */
102 schedule?: imagebuilder.Schedule;
103 /**
104 * Whether the pipeline schedule is active.
105 * @default "ENABLED"
106 */
107 status?: "ENABLED" | "DISABLED";
108 /**
109 * Image scanning (Amazon Inspector) settings for output images.
110 */
111 imageScanningConfiguration?: imagebuilder.ImageScanningConfiguration;
112 /**
113 * Custom build/test workflows to run.
114 */
115 workflows?: imagebuilder.WorkflowConfiguration[];
116 /**
117 * IAM role (name or ARN) that Image Builder assumes to run workflows.
118 */
119 executionRole?: string;
120 /**
121 * User-defined tags for the pipeline.
122 */
123 tags?: Record<string, string>;
124 }
125
126 export interface ImagePipeline extends Resource<
127 "AWS.ImageBuilder.ImagePipeline",
128 ImagePipelineProps,
129 {
130 /** The name of the image pipeline. */
131 imagePipelineName: string;
132 /** The ARN of the image pipeline. */
133 imagePipelineArn: string;
134 /** The OS platform of the pipeline's recipe (`Linux` / `Windows`). */
135 platform: string | undefined;
136 /** Whether the pipeline is `ENABLED` or `DISABLED`. */
137 status: string | undefined;
138 /** When the pipeline was created. */
139 dateCreated: string | undefined;
140 },
141 never,
142 Providers
143 > {}
144
145 /**
146 * An EC2 Image Builder image pipeline — wires a recipe to an infrastructure
147 * configuration (and optionally a distribution configuration) and automates
148 * image builds on a schedule or on demand.
149 *
150 * Creating the pipeline does not start a build; builds start on the
151 * configured schedule or when explicitly invoked.
152 * ### Creating an Image Pipeline
153 * **Example:** Manual-Only Pipeline
154 * ```typescript
155 * const pipeline = yield* ImageBuilder.ImagePipeline("Pipeline", {
156 * imageRecipeArn: recipe.imageRecipeArn,
157 * infrastructureConfigurationArn: infra.infrastructureConfigurationArn,
158 * status: "DISABLED",
159 * });
160 * ```
161 *
162 * **Example:** Scheduled Pipeline with Distribution
163 * ```typescript
164 * const pipeline = yield* ImageBuilder.ImagePipeline("Nightly", {
165 * imageRecipeArn: recipe.imageRecipeArn,
166 * infrastructureConfigurationArn: infra.infrastructureConfigurationArn,
167 * distributionConfigurationArn: distribution.distributionConfigurationArn,
168 * schedule: {
169 * scheduleExpression: "cron(0 9 * * ? *)",
170 * pipelineExecutionStartCondition:
171 * "EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE",
172 * },
173 * });
174 * ```
175 *
176 * @resource
177 */
178 export const ImagePipeline = Resource<ImagePipeline>("AWS.ImageBuilder.ImagePipeline");
179
180 export const ImagePipelineProvider = () =>
181 Provider.effect(
182 ImagePipeline,
183 Effect.gen(function* () {
184 const toName = (id: string, props: ImagePipelineProps) =>
185 props.imagePipelineName
186 ? Effect.succeed(props.imagePipelineName)
187 : createPhysicalName({ id, maxLength: 126 });
188
189 const toArn = (name: string) => imageBuilderArn("image-pipeline", name);
190
191 const getPipeline = Effect.fn(function* (arn: string) {
192 const response = yield* imagebuilder
193 .getImagePipeline({ imagePipelineArn: arn })
194 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
195 return response?.imagePipeline;
196 });
197
198 const toAttrs = Effect.fn(function* (pipeline: imagebuilder.ImagePipeline) {
199 if (!pipeline.arn || !pipeline.name) {
200 return yield* new ImagePipelineUnexpectedResponse({
201 message: "Image Builder image pipeline is missing its ARN or name",
202 });
203 }
204 return {
205 imagePipelineName: pipeline.name,
206 imagePipelineArn: pipeline.arn,
207 platform: pipeline.platform,
208 status: pipeline.status,
209 dateCreated: pipeline.dateCreated,
210 };
211 });
212
213 /** Mutable aspects synced by a full-PUT update. */
214 const mutableKeys = [
215 "description",
216 "imageRecipeArn",
217 "containerRecipeArn",
218 "infrastructureConfigurationArn",
219 "distributionConfigurationArn",
220 "imageTestsConfiguration",
221 "enhancedImageMetadataEnabled",
222 "schedule",
223 "status",
224 "imageScanningConfiguration",
225 "workflows",
226 "executionRole",
227 ] as const;
228
229 return {
230 stables: ["imagePipelineName", "imagePipelineArn"],
231
232 diff: Effect.fn(function* ({ id, olds, news }) {
233 if (!isResolved(news)) return undefined;
234 if ((yield* toName(id, olds)) !== (yield* toName(id, news))) {
235 return { action: "replace" } as const;
236 }
237 }),
238
239 read: Effect.fn(function* ({ id, olds, output }) {
240 const arn = output?.imagePipelineArn ?? (yield* toArn(yield* toName(id, olds)));
241 const pipeline = yield* getPipeline(arn);
242 if (pipeline === undefined) return undefined;
243 const attrs = yield* toAttrs(pipeline);
244 const tags = toTagRecord(pipeline.tags);
245 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
246 }),
247
248 reconcile: Effect.fn(function* ({ id, news, olds, output, session }) {
249 // One idempotency token per reconcile — retries within this run
250 // are deduplicated by the API.
251 const clientToken = yield* Effect.sync(() => crypto.randomUUID());
252 const name = output?.imagePipelineName ?? (yield* toName(id, news));
253 const internalTags = yield* createInternalTags(id);
254 const desiredTags = { ...internalTags, ...news.tags };
255 // Desired state in wire shape (Duration timeout → whole minutes)
256 // so create/update/drift all compare like against like.
257 const desired = {
258 ...news,
259 imageTestsConfiguration: toWireImageTests(news.imageTestsConfiguration),
260 };
261
262 // 1. Observe.
263 const arn = output?.imagePipelineArn ?? (yield* toArn(name));
264 let observed = yield* getPipeline(arn);
265
266 // 2. Ensure — create if missing; tolerate an AlreadyExists race.
267 if (observed === undefined) {
268 const created = yield* imagebuilder
269 .createImagePipeline({
270 name,
271 description: news.description,
272 imageRecipeArn: news.imageRecipeArn,
273 containerRecipeArn: news.containerRecipeArn,
274 infrastructureConfigurationArn: news.infrastructureConfigurationArn,
275 distributionConfigurationArn: news.distributionConfigurationArn,
276 imageTestsConfiguration: desired.imageTestsConfiguration,
277 enhancedImageMetadataEnabled: news.enhancedImageMetadataEnabled,
278 schedule: news.schedule,
279 status: news.status,
280 imageScanningConfiguration: news.imageScanningConfiguration,
281 workflows: news.workflows,
282 executionRole: news.executionRole,
283 tags: desiredTags,
284 clientToken,
285 })
286 .pipe(Effect.catchTag("ResourceAlreadyExistsException", () => Effect.undefined));
287 observed = yield* getPipeline(created?.imagePipelineArn ?? arn);
288 if (observed === undefined) {
289 return yield* new ImagePipelineUnexpectedResponse({
290 message: `created Image Builder pipeline '${name}' is not readable`,
291 });
292 }
293 }
294
295 // 3. Sync — compare OBSERVED cloud state against the desired
296 // props; a full-PUT update converges any drift (`olds` is only
297 // a hint for removed props).
298 const drifted = mutableKeys.some(
299 (key) =>
300 driftedFrom(observed?.[key], desired[key]) ||
301 (desired[key] === undefined && olds?.[key] !== undefined),
302 );
303 if (drifted && observed.arn) {
304 yield* imagebuilder.updateImagePipeline({
305 imagePipelineArn: observed.arn,
306 description: news.description,
307 imageRecipeArn: news.imageRecipeArn,
308 containerRecipeArn: news.containerRecipeArn,
309 infrastructureConfigurationArn: news.infrastructureConfigurationArn,
310 distributionConfigurationArn: news.distributionConfigurationArn,
311 imageTestsConfiguration: desired.imageTestsConfiguration,
312 enhancedImageMetadataEnabled: news.enhancedImageMetadataEnabled,
313 schedule: news.schedule,
314 status: news.status,
315 imageScanningConfiguration: news.imageScanningConfiguration,
316 workflows: news.workflows,
317 executionRole: news.executionRole,
318 clientToken,
319 });
320 observed = (yield* getPipeline(observed.arn)) ?? observed;
321 }
322
323 // 3b. Sync tags — diff against OBSERVED cloud tags.
324 if (observed.arn) {
325 yield* syncImageBuilderTags(observed.arn, desiredTags);
326 }
327
328 // 4. Return fresh attributes.
329 yield* session.note(name);
330 return yield* toAttrs(observed);
331 }),
332
333 delete: Effect.fn(function* ({ output }) {
334 yield* retryWhileDependedOn(
335 imagebuilder.deleteImagePipeline({
336 imagePipelineArn: output.imagePipelineArn,
337 }),
338 ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
339
340 // Image Builder creates this fixed group outside of the pipeline
341 // API. Delete only the exact group derived from this owned output,
342 // and only after the pipeline itself is observed absent.
343 for (let attempt = 0; attempt < 30; attempt++) {
344 if ((yield* getPipeline(output.imagePipelineArn)) === undefined) {
345 yield* deleteImageBuilderLogGroup(
346 `/aws/imagebuilder/pipeline/${output.imagePipelineName.toLowerCase()}`,
347 );
348 return;
349 }
350 yield* Effect.sleep("1 second");
351 }
352 return yield* Effect.die(
353 new Error(
354 `Image Builder pipeline ${output.imagePipelineArn} remained observable 30 seconds after delete`,
355 ),
356 );
357 }),
358
359 list: () =>
360 imagebuilder.listImagePipelines.pages({}).pipe(
361 Stream.runCollect,
362 Effect.map((chunk) =>
363 Array.from(chunk).flatMap((page) =>
364 (page.imagePipelineList ?? []).filter(
365 (
366 pipeline,
367 ): pipeline is imagebuilder.ImagePipeline & {
368 arn: string;
369 name: string;
370 } => pipeline.arn !== undefined && pipeline.name !== undefined,
371 ),
372 ),
373 ),
374 Effect.map((pipelines) =>
375 pipelines.map((pipeline) => ({
376 imagePipelineName: pipeline.name,
377 imagePipelineArn: pipeline.arn,
378 platform: pipeline.platform,
379 status: pipeline.status,
380 dateCreated: pipeline.dateCreated,
381 })),
382 ),
383 ),
384 };
385 }),
386 );