The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as imagebuilder from "@distilled.cloud/aws/imagebuilder"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { deepEqual } 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 * as Data from "effect/Data"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as Stream from "effect/Stream"; |
| 11 | import type { Providers } from "../Providers.ts"; |
| 12 | import { |
| 13 | deleteImageBuilderLogGroup, |
| 14 | imageBuilderArn, |
| 15 | immutableVersionKeysChanged, |
| 16 | retryWhileDependedOn, |
| 17 | syncImageBuilderTags, |
| 18 | toTagRecord, |
| 19 | } from "./internal.ts"; |
| 20 | |
| 21 | export class ImageRecipeUnexpectedResponse extends Data.TaggedError( |
| 22 | "ImageRecipeUnexpectedResponse", |
| 23 | )<{ |
| 24 | readonly message: string; |
| 25 | readonly cause?: unknown; |
| 26 | }> {} |
| 27 | |
| 28 | /** |
| 29 | * Image Builder image recipe versions are immutable — the deployed recipe |
| 30 | * differs from the desired one but the semantic version was not bumped, so |
| 31 | * the cloud state cannot be converged. |
| 32 | */ |
| 33 | export class ImageRecipeVersionImmutable extends Data.TaggedError( |
| 34 | "AWS::ImageBuilder::ImageRecipeVersionImmutable", |
| 35 | )<{ |
| 36 | message: string; |
| 37 | }> {} |
| 38 | |
| 39 | export interface RecipeComponentParameter { |
| 40 | /** Name of the component parameter to set. */ |
| 41 | name: string; |
| 42 | /** Value(s) to assign to the parameter. */ |
| 43 | value: string[]; |
| 44 | } |
| 45 | |
| 46 | export interface RecipeComponent { |
| 47 | /** |
| 48 | * Build-version ARN of the component to apply |
| 49 | * (e.g. `component.componentBuildVersionArn`). |
| 50 | */ |
| 51 | componentArn: string; |
| 52 | /** Parameter overrides for parameterized components. */ |
| 53 | parameters?: RecipeComponentParameter[]; |
| 54 | } |
| 55 | |
| 56 | export interface ImageRecipeProps { |
| 57 | /** |
| 58 | * Name of the image recipe. If omitted, a deterministic physical name is |
| 59 | * generated. Changing the name replaces the recipe. |
| 60 | */ |
| 61 | imageRecipeName?: string; |
| 62 | /** |
| 63 | * Semantic version of the recipe (`major.minor.patch`). Recipes are |
| 64 | * immutable — bump the version when changing any property. Changing the |
| 65 | * version replaces the recipe. |
| 66 | * @default "1.0.0" |
| 67 | */ |
| 68 | semanticVersion?: string; |
| 69 | /** |
| 70 | * Base image of the recipe: an Image Builder image ARN (e.g. the |
| 71 | * AWS-managed `arn:aws:imagebuilder:us-west-2:aws:image/amazon-linux-2023-x86/x.x.x`), |
| 72 | * an AMI ID, or an SSM parameter reference (`ssm:/path/to/parameter`). |
| 73 | * Changing the parent image replaces the recipe. |
| 74 | */ |
| 75 | parentImage: string; |
| 76 | /** |
| 77 | * Components applied to the image, in order. Changing the component list |
| 78 | * replaces the recipe. |
| 79 | */ |
| 80 | components: RecipeComponent[]; |
| 81 | /** |
| 82 | * Description of the recipe. Changing it replaces the recipe. |
| 83 | */ |
| 84 | description?: string; |
| 85 | /** |
| 86 | * Block device mappings for instances built from the recipe. Changing |
| 87 | * them replaces the recipe. |
| 88 | */ |
| 89 | blockDeviceMappings?: imagebuilder.InstanceBlockDeviceMapping[]; |
| 90 | /** |
| 91 | * Working directory used during build and test workflows. |
| 92 | * Changing it replaces the recipe. |
| 93 | * @default "/tmp" |
| 94 | */ |
| 95 | workingDirectory?: string; |
| 96 | /** |
| 97 | * Additional instance configuration (SSM agent removal, user data |
| 98 | * override). Changing it replaces the recipe. |
| 99 | */ |
| 100 | additionalInstanceConfiguration?: imagebuilder.AdditionalInstanceConfiguration; |
| 101 | /** |
| 102 | * Tags applied to output AMIs created from the recipe. Changing them |
| 103 | * replaces the recipe. |
| 104 | */ |
| 105 | amiTags?: Record<string, string>; |
| 106 | /** |
| 107 | * User-defined tags for the recipe. |
| 108 | */ |
| 109 | tags?: Record<string, string>; |
| 110 | } |
| 111 | |
| 112 | export interface ImageRecipe extends Resource< |
| 113 | "AWS.ImageBuilder.ImageRecipe", |
| 114 | ImageRecipeProps, |
| 115 | { |
| 116 | /** The name of the image recipe. */ |
| 117 | imageRecipeName: string; |
| 118 | /** The ARN of the image recipe. */ |
| 119 | imageRecipeArn: string; |
| 120 | /** The semantic version of the recipe. */ |
| 121 | semanticVersion: string; |
| 122 | /** The OS platform of the recipe (`Linux` / `Windows`). */ |
| 123 | platform: string | undefined; |
| 124 | /** The base image the recipe builds on. */ |
| 125 | parentImage: string | undefined; |
| 126 | /** When the recipe was created. */ |
| 127 | dateCreated: string | undefined; |
| 128 | }, |
| 129 | never, |
| 130 | Providers |
| 131 | > {} |
| 132 | |
| 133 | /** |
| 134 | * An EC2 Image Builder image recipe — the blueprint that combines a parent |
| 135 | * image with an ordered list of components to produce a new AMI. |
| 136 | * |
| 137 | * Recipes are immutable versions: every property except `tags` replaces the |
| 138 | * recipe. Bump `semanticVersion` when changing the definition. |
| 139 | * ### Creating an Image Recipe |
| 140 | * **Example:** Recipe from an AWS-Managed Parent Image |
| 141 | * ```typescript |
| 142 | * const recipe = yield* ImageBuilder.ImageRecipe("Recipe", { |
| 143 | * parentImage: "arn:aws:imagebuilder:us-west-2:aws:image/amazon-linux-2023-x86/x.x.x", |
| 144 | * semanticVersion: "1.0.0", |
| 145 | * components: [{ componentArn: component.componentBuildVersionArn }], |
| 146 | * }); |
| 147 | * ``` |
| 148 | * |
| 149 | * ### Using in a Pipeline |
| 150 | * **Example:** Wire into an Image Pipeline |
| 151 | * ```typescript |
| 152 | * const pipeline = yield* ImageBuilder.ImagePipeline("Pipeline", { |
| 153 | * imageRecipeArn: recipe.imageRecipeArn, |
| 154 | * infrastructureConfigurationArn: infra.infrastructureConfigurationArn, |
| 155 | * }); |
| 156 | * ``` |
| 157 | * |
| 158 | * @resource |
| 159 | */ |
| 160 | export const ImageRecipe = Resource<ImageRecipe>("AWS.ImageBuilder.ImageRecipe"); |
| 161 | |
| 162 | export const ImageRecipeProvider = () => |
| 163 | Provider.effect( |
| 164 | ImageRecipe, |
| 165 | Effect.gen(function* () { |
| 166 | const toName = (id: string, props: ImageRecipeProps) => |
| 167 | props.imageRecipeName |
| 168 | ? Effect.succeed(props.imageRecipeName) |
| 169 | : createPhysicalName({ id, maxLength: 126 }); |
| 170 | |
| 171 | const toVersion = (props: ImageRecipeProps) => props.semanticVersion ?? "1.0.0"; |
| 172 | |
| 173 | const toArn = (name: string, version: string) => |
| 174 | imageBuilderArn("image-recipe", `${name}/${version}`); |
| 175 | |
| 176 | const getRecipe = Effect.fn(function* (arn: string) { |
| 177 | const response = yield* imagebuilder |
| 178 | .getImageRecipe({ imageRecipeArn: arn }) |
| 179 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 180 | return response?.imageRecipe; |
| 181 | }); |
| 182 | |
| 183 | const toAttrs = Effect.fn(function* (recipe: imagebuilder.ImageRecipe) { |
| 184 | if (!recipe.arn || !recipe.name || !recipe.version) { |
| 185 | return yield* new ImageRecipeUnexpectedResponse({ |
| 186 | message: "Image Builder image recipe is missing its ARN, name, or version", |
| 187 | }); |
| 188 | } |
| 189 | return { |
| 190 | imageRecipeName: recipe.name, |
| 191 | imageRecipeArn: recipe.arn, |
| 192 | semanticVersion: recipe.version, |
| 193 | platform: recipe.platform, |
| 194 | parentImage: recipe.parentImage, |
| 195 | dateCreated: recipe.dateCreated, |
| 196 | }; |
| 197 | }); |
| 198 | |
| 199 | return { |
| 200 | stables: ["imageRecipeName", "semanticVersion"], |
| 201 | |
| 202 | // Recipes are immutable — any changed property except tags |
| 203 | // replaces. Individual keys may still hold unresolved Outputs at |
| 204 | // plan time (e.g. the ARN of a component being replaced in the |
| 205 | // same deploy); compare per key so a resolved change (like a |
| 206 | // semanticVersion bump) still plans a replacement, and let the |
| 207 | // reconcile immutability guard catch drift hidden behind an |
| 208 | // unresolved key. |
| 209 | diff: Effect.fn(function* ({ olds, news }) { |
| 210 | const immutableKeys = [ |
| 211 | "imageRecipeName", |
| 212 | "semanticVersion", |
| 213 | "parentImage", |
| 214 | "components", |
| 215 | "description", |
| 216 | "blockDeviceMappings", |
| 217 | "workingDirectory", |
| 218 | "additionalInstanceConfiguration", |
| 219 | "amiTags", |
| 220 | ] as const; |
| 221 | if (immutableVersionKeysChanged(olds, news, immutableKeys)) { |
| 222 | return { action: "replace" } as const; |
| 223 | } |
| 224 | }), |
| 225 | |
| 226 | read: Effect.fn(function* ({ id, olds, output }) { |
| 227 | const arn = |
| 228 | output?.imageRecipeArn ?? (yield* toArn(yield* toName(id, olds), toVersion(olds))); |
| 229 | const recipe = yield* getRecipe(arn); |
| 230 | if (recipe === undefined) return undefined; |
| 231 | const attrs = yield* toAttrs(recipe); |
| 232 | const tags = toTagRecord(recipe.tags); |
| 233 | return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs); |
| 234 | }), |
| 235 | |
| 236 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 237 | // One idempotency token per reconcile — retries within this run |
| 238 | // are deduplicated by the API. |
| 239 | const clientToken = yield* Effect.sync(() => crypto.randomUUID()); |
| 240 | const name = output?.imageRecipeName ?? (yield* toName(id, news)); |
| 241 | const version = output?.semanticVersion ?? toVersion(news); |
| 242 | const internalTags = yield* createInternalTags(id); |
| 243 | const desiredTags = { ...internalTags, ...news.tags }; |
| 244 | |
| 245 | // 1. Observe — the recipe ARN is deterministic from name+version. |
| 246 | const arn = output?.imageRecipeArn ?? (yield* toArn(name, version)); |
| 247 | let observed = yield* getRecipe(arn); |
| 248 | |
| 249 | // Immutability guard — the version already exists in the cloud |
| 250 | // with a different definition (e.g. a component was replaced |
| 251 | // without bumping the recipe version). It cannot be converged in |
| 252 | // place; the user must bump `semanticVersion`. |
| 253 | if (observed !== undefined) { |
| 254 | const observedComponents = (observed.components ?? []).map( |
| 255 | (component) => component.componentArn, |
| 256 | ); |
| 257 | const desiredComponents = news.components.map((component) => component.componentArn); |
| 258 | if ( |
| 259 | !deepEqual(observedComponents, desiredComponents) || |
| 260 | observed.parentImage !== news.parentImage |
| 261 | ) { |
| 262 | return yield* new ImageRecipeVersionImmutable({ |
| 263 | message: `Image Builder recipe '${name}' version '${version}' already exists with a different definition — bump semanticVersion to publish the change`, |
| 264 | }); |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | // 2. Ensure — recipes are immutable; missing is the only create |
| 269 | // path. |
| 270 | if (observed === undefined) { |
| 271 | const created = yield* imagebuilder.createImageRecipe({ |
| 272 | name, |
| 273 | semanticVersion: version, |
| 274 | parentImage: news.parentImage, |
| 275 | components: news.components, |
| 276 | description: news.description, |
| 277 | blockDeviceMappings: news.blockDeviceMappings, |
| 278 | workingDirectory: news.workingDirectory, |
| 279 | additionalInstanceConfiguration: news.additionalInstanceConfiguration, |
| 280 | amiTags: news.amiTags, |
| 281 | tags: desiredTags, |
| 282 | clientToken, |
| 283 | }); |
| 284 | if (!created.imageRecipeArn) { |
| 285 | return yield* new ImageRecipeUnexpectedResponse({ |
| 286 | message: "CreateImageRecipe returned no imageRecipeArn", |
| 287 | }); |
| 288 | } |
| 289 | observed = yield* getRecipe(created.imageRecipeArn); |
| 290 | if (observed === undefined) { |
| 291 | return yield* new ImageRecipeUnexpectedResponse({ |
| 292 | message: `created Image Builder recipe '${name}' is not readable`, |
| 293 | }); |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | // 3. Sync — tags are the only mutable aspect. |
| 298 | if (observed.arn) { |
| 299 | yield* syncImageBuilderTags(observed.arn, desiredTags); |
| 300 | } |
| 301 | |
| 302 | // 4. Return fresh attributes. |
| 303 | yield* session.note(name); |
| 304 | return yield* toAttrs(observed); |
| 305 | }), |
| 306 | |
| 307 | delete: Effect.fn(function* ({ output }) { |
| 308 | yield* retryWhileDependedOn( |
| 309 | imagebuilder.deleteImageRecipe({ |
| 310 | imageRecipeArn: output.imageRecipeArn, |
| 311 | }), |
| 312 | ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)); |
| 313 | |
| 314 | // Do not discard state until Image Builder confirms the owned |
| 315 | // version is gone. The auto-created recipe log group is shared by |
| 316 | // every version with the same name, so delete it only when no live |
| 317 | // same-name recipe remains (including a replacement version). |
| 318 | for (let attempt = 0; attempt < 30; attempt++) { |
| 319 | if ((yield* getRecipe(output.imageRecipeArn)) === undefined) break; |
| 320 | if (attempt === 29) { |
| 321 | return yield* Effect.die( |
| 322 | new Error( |
| 323 | `Image Builder recipe ${output.imageRecipeArn} remained observable 30 seconds after delete`, |
| 324 | ), |
| 325 | ); |
| 326 | } |
| 327 | yield* Effect.sleep("1 second"); |
| 328 | } |
| 329 | |
| 330 | const summaries = yield* imagebuilder.listImageRecipes.pages({ owner: "Self" }).pipe( |
| 331 | Stream.runCollect, |
| 332 | Effect.map((pages) => |
| 333 | Array.from(pages).flatMap((page) => page.imageRecipeSummaryList ?? []), |
| 334 | ), |
| 335 | ); |
| 336 | const sameName = summaries.filter( |
| 337 | (summary) => summary.name === output.imageRecipeName && summary.arn !== undefined, |
| 338 | ); |
| 339 | const liveSameName = yield* Effect.forEach( |
| 340 | sameName, |
| 341 | (summary) => getRecipe(summary.arn!), |
| 342 | { concurrency: 4 }, |
| 343 | ); |
| 344 | if (liveSameName.every((recipe) => recipe === undefined)) { |
| 345 | yield* deleteImageBuilderLogGroup(`/aws/imagebuilder/${output.imageRecipeName}`); |
| 346 | } |
| 347 | }), |
| 348 | |
| 349 | list: () => |
| 350 | imagebuilder.listImageRecipes.pages({ owner: "Self" }).pipe( |
| 351 | Stream.runCollect, |
| 352 | Effect.map((chunk) => |
| 353 | Array.from(chunk).flatMap((page) => |
| 354 | (page.imageRecipeSummaryList ?? []).filter( |
| 355 | ( |
| 356 | summary, |
| 357 | ): summary is imagebuilder.ImageRecipeSummary & { |
| 358 | arn: string; |
| 359 | } => summary.arn !== undefined, |
| 360 | ), |
| 361 | ), |
| 362 | ), |
| 363 | Effect.flatMap( |
| 364 | Effect.forEach( |
| 365 | (summary) => |
| 366 | getRecipe(summary.arn).pipe( |
| 367 | Effect.flatMap((recipe) => |
| 368 | recipe === undefined ? Effect.undefined : toAttrs(recipe), |
| 369 | ), |
| 370 | ), |
| 371 | { concurrency: 4 }, |
| 372 | ), |
| 373 | ), |
| 374 | Effect.map((items) => items.filter((item) => item !== undefined)), |
| 375 | ), |
| 376 | }; |
| 377 | }), |
| 378 | ); |