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 { 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 * as Data from "effect/Data"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as Schedule from "effect/Schedule"; |
| 11 | import * as Stream from "effect/Stream"; |
| 12 | import type { Providers } from "../Providers.ts"; |
| 13 | import { |
| 14 | driftedFrom, |
| 15 | imageBuilderArn, |
| 16 | retryWhileDependedOn, |
| 17 | syncImageBuilderTags, |
| 18 | toTagRecord, |
| 19 | } from "./internal.ts"; |
| 20 | |
| 21 | export class InfrastructureConfigurationUnexpectedResponse extends Data.TaggedError( |
| 22 | "InfrastructureConfigurationUnexpectedResponse", |
| 23 | )<{ |
| 24 | readonly message: string; |
| 25 | readonly cause?: unknown; |
| 26 | }> {} |
| 27 | |
| 28 | export interface InfrastructureConfigurationProps { |
| 29 | /** |
| 30 | * Name of the infrastructure configuration. If omitted, a deterministic |
| 31 | * physical name is generated. Changing the name replaces the |
| 32 | * configuration. |
| 33 | */ |
| 34 | infrastructureConfigurationName?: string; |
| 35 | /** |
| 36 | * Name of the IAM instance profile attached to build/test instances. |
| 37 | * The profile's role needs at least `EC2InstanceProfileForImageBuilder` |
| 38 | * and `AmazonSSMManagedInstanceCore`. |
| 39 | */ |
| 40 | instanceProfileName: string; |
| 41 | /** |
| 42 | * EC2 instance types to use when building. Image Builder picks the |
| 43 | * type with the most available capacity. |
| 44 | */ |
| 45 | instanceTypes?: string[]; |
| 46 | /** |
| 47 | * Security group IDs applied to build/test instances. |
| 48 | */ |
| 49 | securityGroupIds?: string[]; |
| 50 | /** |
| 51 | * Subnet in which to place build/test instances. |
| 52 | */ |
| 53 | subnetId?: string; |
| 54 | /** |
| 55 | * Description of the configuration. |
| 56 | */ |
| 57 | description?: string; |
| 58 | /** |
| 59 | * S3 logging configuration for build logs. |
| 60 | */ |
| 61 | logging?: imagebuilder.Logging; |
| 62 | /** |
| 63 | * EC2 key pair for debugging build instances. |
| 64 | */ |
| 65 | keyPair?: string; |
| 66 | /** |
| 67 | * Terminate the build instance when the build fails (set `false` to |
| 68 | * keep it for debugging). |
| 69 | * @default true |
| 70 | */ |
| 71 | terminateInstanceOnFailure?: boolean; |
| 72 | /** |
| 73 | * SNS topic ARN notified of image build events. |
| 74 | */ |
| 75 | snsTopicArn?: string; |
| 76 | /** |
| 77 | * Tags applied to the EC2 resources (instances, volumes) created |
| 78 | * during builds. |
| 79 | */ |
| 80 | resourceTags?: Record<string, string>; |
| 81 | /** |
| 82 | * Instance metadata service (IMDS) settings for build instances. |
| 83 | */ |
| 84 | instanceMetadataOptions?: imagebuilder.InstanceMetadataOptions; |
| 85 | /** |
| 86 | * Placement settings (availability zone, tenancy, host) for build |
| 87 | * instances. |
| 88 | */ |
| 89 | placement?: imagebuilder.Placement; |
| 90 | /** |
| 91 | * User-defined tags for the configuration. |
| 92 | */ |
| 93 | tags?: Record<string, string>; |
| 94 | } |
| 95 | |
| 96 | export interface InfrastructureConfiguration extends Resource< |
| 97 | "AWS.ImageBuilder.InfrastructureConfiguration", |
| 98 | InfrastructureConfigurationProps, |
| 99 | { |
| 100 | /** The name of the infrastructure configuration. */ |
| 101 | infrastructureConfigurationName: string; |
| 102 | /** The ARN of the infrastructure configuration. */ |
| 103 | infrastructureConfigurationArn: string; |
| 104 | /** The instance profile builds run with. */ |
| 105 | instanceProfileName: string | undefined; |
| 106 | /** When the infrastructure configuration was created. */ |
| 107 | dateCreated: string | undefined; |
| 108 | }, |
| 109 | never, |
| 110 | Providers |
| 111 | > {} |
| 112 | |
| 113 | /** |
| 114 | * An EC2 Image Builder infrastructure configuration — the environment |
| 115 | * (instance profile, instance types, network, logging) in which images are |
| 116 | * built and tested. |
| 117 | * ### Creating an Infrastructure Configuration |
| 118 | * **Example:** Minimal Configuration |
| 119 | * ```typescript |
| 120 | * const role = yield* IAM.Role("BuilderRole", { |
| 121 | * assumeRolePolicyDocument: { |
| 122 | * Version: "2012-10-17", |
| 123 | * Statement: [{ |
| 124 | * Effect: "Allow", |
| 125 | * Principal: { Service: "ec2.amazonaws.com" }, |
| 126 | * Action: ["sts:AssumeRole"], |
| 127 | * }], |
| 128 | * }, |
| 129 | * managedPolicyArns: [ |
| 130 | * "arn:aws:iam::aws:policy/EC2InstanceProfileForImageBuilder", |
| 131 | * "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore", |
| 132 | * ], |
| 133 | * }); |
| 134 | * const profile = yield* IAM.InstanceProfile("BuilderProfile", { |
| 135 | * roleName: role.roleName, |
| 136 | * }); |
| 137 | * const infra = yield* ImageBuilder.InfrastructureConfiguration("Infra", { |
| 138 | * instanceProfileName: profile.instanceProfileName, |
| 139 | * instanceTypes: ["t3.micro"], |
| 140 | * terminateInstanceOnFailure: true, |
| 141 | * }); |
| 142 | * ``` |
| 143 | * |
| 144 | * @resource |
| 145 | */ |
| 146 | export const InfrastructureConfiguration = Resource<InfrastructureConfiguration>( |
| 147 | "AWS.ImageBuilder.InfrastructureConfiguration", |
| 148 | ); |
| 149 | |
| 150 | /** |
| 151 | * A freshly created IAM instance profile takes a few seconds to become |
| 152 | * visible to Image Builder, which rejects it with |
| 153 | * `InvalidParameterValueException` ("The provided instance profile does not |
| 154 | * exist") in the interim — retry through the propagation window (bounded). |
| 155 | */ |
| 156 | const retryThroughIamPropagation = < |
| 157 | A, |
| 158 | E extends { readonly _tag: string; readonly message?: string }, |
| 159 | R, |
| 160 | >( |
| 161 | self: Effect.Effect<A, E, R>, |
| 162 | ): Effect.Effect<A, E, R> => |
| 163 | Effect.retry(self, { |
| 164 | while: (e) => |
| 165 | e._tag === "InvalidParameterValueException" && |
| 166 | (e.message?.includes("instance profile does not exist") ?? false), |
| 167 | schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(10)]), |
| 168 | }); |
| 169 | |
| 170 | export const InfrastructureConfigurationProvider = () => |
| 171 | Provider.effect( |
| 172 | InfrastructureConfiguration, |
| 173 | Effect.gen(function* () { |
| 174 | const toName = (id: string, props: InfrastructureConfigurationProps) => |
| 175 | props.infrastructureConfigurationName |
| 176 | ? Effect.succeed(props.infrastructureConfigurationName) |
| 177 | : createPhysicalName({ id, maxLength: 126 }); |
| 178 | |
| 179 | const toArn = (name: string) => imageBuilderArn("infrastructure-configuration", name); |
| 180 | |
| 181 | const getConfiguration = Effect.fn(function* (arn: string) { |
| 182 | const response = yield* imagebuilder |
| 183 | .getInfrastructureConfiguration({ |
| 184 | infrastructureConfigurationArn: arn, |
| 185 | }) |
| 186 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 187 | return response?.infrastructureConfiguration; |
| 188 | }); |
| 189 | |
| 190 | const toAttrs = Effect.fn(function* (config: imagebuilder.InfrastructureConfiguration) { |
| 191 | if (!config.arn || !config.name) { |
| 192 | return yield* new InfrastructureConfigurationUnexpectedResponse({ |
| 193 | message: "Image Builder infrastructure configuration is missing its ARN or name", |
| 194 | }); |
| 195 | } |
| 196 | return { |
| 197 | infrastructureConfigurationName: config.name, |
| 198 | infrastructureConfigurationArn: config.arn, |
| 199 | instanceProfileName: config.instanceProfileName, |
| 200 | dateCreated: config.dateCreated, |
| 201 | }; |
| 202 | }); |
| 203 | |
| 204 | /** |
| 205 | * Mutable aspects synced by a full-PUT update. Keys of both the |
| 206 | * observed struct and the Props (they share names). |
| 207 | */ |
| 208 | const mutableKeys = [ |
| 209 | "description", |
| 210 | "instanceTypes", |
| 211 | "instanceProfileName", |
| 212 | "securityGroupIds", |
| 213 | "subnetId", |
| 214 | "logging", |
| 215 | "keyPair", |
| 216 | "terminateInstanceOnFailure", |
| 217 | "snsTopicArn", |
| 218 | "resourceTags", |
| 219 | "instanceMetadataOptions", |
| 220 | "placement", |
| 221 | ] as const; |
| 222 | |
| 223 | return { |
| 224 | stables: ["infrastructureConfigurationName", "infrastructureConfigurationArn"], |
| 225 | |
| 226 | diff: Effect.fn(function* ({ id, olds, news }) { |
| 227 | if (!isResolved(news)) return undefined; |
| 228 | if ((yield* toName(id, olds)) !== (yield* toName(id, news))) { |
| 229 | return { action: "replace" } as const; |
| 230 | } |
| 231 | }), |
| 232 | |
| 233 | read: Effect.fn(function* ({ id, olds, output }) { |
| 234 | const arn = |
| 235 | output?.infrastructureConfigurationArn ?? (yield* toArn(yield* toName(id, olds))); |
| 236 | const config = yield* getConfiguration(arn); |
| 237 | if (config === undefined) return undefined; |
| 238 | const attrs = yield* toAttrs(config); |
| 239 | const tags = toTagRecord(config.tags); |
| 240 | return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs); |
| 241 | }), |
| 242 | |
| 243 | reconcile: Effect.fn(function* ({ id, news, olds, output, session }) { |
| 244 | // One idempotency token per reconcile — retries within this run |
| 245 | // are deduplicated by the API. |
| 246 | const clientToken = yield* Effect.sync(() => crypto.randomUUID()); |
| 247 | const name = output?.infrastructureConfigurationName ?? (yield* toName(id, news)); |
| 248 | const internalTags = yield* createInternalTags(id); |
| 249 | const desiredTags = { ...internalTags, ...news.tags }; |
| 250 | |
| 251 | // 1. Observe — the configuration ARN is deterministic from the |
| 252 | // name; cloud state is authoritative. |
| 253 | const arn = output?.infrastructureConfigurationArn ?? (yield* toArn(name)); |
| 254 | let observed = yield* getConfiguration(arn); |
| 255 | |
| 256 | // 2. Ensure — create if missing; tolerate an AlreadyExists race |
| 257 | // by re-observing. |
| 258 | if (observed === undefined) { |
| 259 | const created = yield* retryThroughIamPropagation( |
| 260 | imagebuilder.createInfrastructureConfiguration({ |
| 261 | name, |
| 262 | description: news.description, |
| 263 | instanceTypes: news.instanceTypes, |
| 264 | instanceProfileName: news.instanceProfileName, |
| 265 | securityGroupIds: news.securityGroupIds, |
| 266 | subnetId: news.subnetId, |
| 267 | logging: news.logging, |
| 268 | keyPair: news.keyPair, |
| 269 | terminateInstanceOnFailure: news.terminateInstanceOnFailure, |
| 270 | snsTopicArn: news.snsTopicArn, |
| 271 | resourceTags: news.resourceTags, |
| 272 | instanceMetadataOptions: news.instanceMetadataOptions, |
| 273 | placement: news.placement, |
| 274 | tags: desiredTags, |
| 275 | clientToken, |
| 276 | }), |
| 277 | ).pipe(Effect.catchTag("ResourceAlreadyExistsException", () => Effect.undefined)); |
| 278 | observed = yield* getConfiguration(created?.infrastructureConfigurationArn ?? arn); |
| 279 | if (observed === undefined) { |
| 280 | return yield* new InfrastructureConfigurationUnexpectedResponse({ |
| 281 | message: `created Image Builder infrastructure configuration '${name}' is not readable`, |
| 282 | }); |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | // 3. Sync — compare OBSERVED cloud state against the desired |
| 287 | // props; a full-PUT update converges any drift (including |
| 288 | // props the user removed since the last deploy — `olds` is |
| 289 | // only a hint for removals). |
| 290 | const drifted = mutableKeys.some( |
| 291 | (key) => |
| 292 | driftedFrom(observed?.[key], news[key]) || |
| 293 | (news[key] === undefined && olds?.[key] !== undefined), |
| 294 | ); |
| 295 | if (drifted && observed.arn) { |
| 296 | yield* imagebuilder.updateInfrastructureConfiguration({ |
| 297 | infrastructureConfigurationArn: observed.arn, |
| 298 | description: news.description, |
| 299 | instanceTypes: news.instanceTypes, |
| 300 | instanceProfileName: news.instanceProfileName, |
| 301 | securityGroupIds: news.securityGroupIds, |
| 302 | subnetId: news.subnetId, |
| 303 | logging: news.logging, |
| 304 | keyPair: news.keyPair, |
| 305 | terminateInstanceOnFailure: news.terminateInstanceOnFailure, |
| 306 | snsTopicArn: news.snsTopicArn, |
| 307 | resourceTags: news.resourceTags, |
| 308 | instanceMetadataOptions: news.instanceMetadataOptions, |
| 309 | placement: news.placement, |
| 310 | clientToken, |
| 311 | }); |
| 312 | observed = (yield* getConfiguration(observed.arn)) ?? observed; |
| 313 | } |
| 314 | |
| 315 | // 3b. Sync tags — diff against OBSERVED cloud tags. |
| 316 | if (observed.arn) { |
| 317 | yield* syncImageBuilderTags(observed.arn, desiredTags); |
| 318 | } |
| 319 | |
| 320 | // 4. Return fresh attributes. |
| 321 | yield* session.note(name); |
| 322 | return yield* toAttrs(observed); |
| 323 | }), |
| 324 | |
| 325 | delete: Effect.fn(function* ({ output }) { |
| 326 | yield* retryWhileDependedOn( |
| 327 | imagebuilder.deleteInfrastructureConfiguration({ |
| 328 | infrastructureConfigurationArn: output.infrastructureConfigurationArn, |
| 329 | }), |
| 330 | ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)); |
| 331 | }), |
| 332 | |
| 333 | list: () => |
| 334 | imagebuilder.listInfrastructureConfigurations.pages({}).pipe( |
| 335 | Stream.runCollect, |
| 336 | Effect.map((chunk) => |
| 337 | Array.from(chunk).flatMap((page) => |
| 338 | (page.infrastructureConfigurationSummaryList ?? []).filter( |
| 339 | ( |
| 340 | summary, |
| 341 | ): summary is imagebuilder.InfrastructureConfigurationSummary & { |
| 342 | arn: string; |
| 343 | name: string; |
| 344 | } => summary.arn !== undefined && summary.name !== undefined, |
| 345 | ), |
| 346 | ), |
| 347 | ), |
| 348 | Effect.map((summaries) => |
| 349 | summaries.map((summary) => ({ |
| 350 | infrastructureConfigurationName: summary.name, |
| 351 | infrastructureConfigurationArn: summary.arn, |
| 352 | instanceProfileName: summary.instanceProfileName, |
| 353 | dateCreated: summary.dateCreated, |
| 354 | })), |
| 355 | ), |
| 356 | ), |
| 357 | }; |
| 358 | }), |
| 359 | ); |