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
| 1 | import * as autoscaling from "@distilled.cloud/aws/auto-scaling"; |
| 2 | import { deepEqual, isResolved } from "alchemy/Diff"; |
| 3 | import type { Input } from "alchemy/Input"; |
| 4 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 5 | import * as Provider from "alchemy/Provider"; |
| 6 | import { Resource } from "alchemy/Resource"; |
| 7 | import { createInternalTags, diffTags } from "alchemy/Tags"; |
| 8 | import { toSeconds } 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 Schedule from "effect/Schedule"; |
| 13 | import * as Stream from "effect/Stream"; |
| 14 | import type { SubnetId } from "../EC2/Subnet.ts"; |
| 15 | import type { Providers } from "../Providers.ts"; |
| 16 | import type { |
| 17 | LaunchTemplateId, |
| 18 | LaunchTemplateName, |
| 19 | LaunchTemplate as LaunchTemplateResource, |
| 20 | } from "./LaunchTemplate.ts"; |
| 21 | |
| 22 | export class AutoScalingGroupUnexpectedResponse extends Data.TaggedError( |
| 23 | "AutoScalingGroupUnexpectedResponse", |
| 24 | )<{ |
| 25 | readonly message: string; |
| 26 | readonly cause?: unknown; |
| 27 | }> {} |
| 28 | |
| 29 | export class AutoScalingGroupNotReady extends Data.TaggedError("AutoScalingGroupNotReady")<{ |
| 30 | readonly message: string; |
| 31 | readonly cause?: unknown; |
| 32 | }> {} |
| 33 | |
| 34 | export type AutoScalingGroupName = string; |
| 35 | |
| 36 | export interface LaunchTemplateReference { |
| 37 | /** |
| 38 | * ID of the launch template (`lt-...`). Provide either the ID or the name, |
| 39 | * not both. |
| 40 | */ |
| 41 | launchTemplateId?: Input<LaunchTemplateId>; |
| 42 | /** |
| 43 | * Name of the launch template. Provide either the ID or the name, not both. |
| 44 | */ |
| 45 | launchTemplateName?: Input<LaunchTemplateName>; |
| 46 | /** |
| 47 | * Template version to launch. |
| 48 | * @default "$Default" |
| 49 | */ |
| 50 | version?: Input<string | number>; |
| 51 | } |
| 52 | |
| 53 | export interface AutoScalingGroupProps { |
| 54 | /** |
| 55 | * Auto Scaling Group name. If omitted, a deterministic name is generated. |
| 56 | */ |
| 57 | autoScalingGroupName?: string; |
| 58 | /** |
| 59 | * Launch template used for instances in the fleet. |
| 60 | */ |
| 61 | launchTemplate: Input<LaunchTemplateReference> | LaunchTemplateResource; |
| 62 | /** |
| 63 | * Subnets to place the fleet into. |
| 64 | */ |
| 65 | subnetIds: Input<SubnetId[]>; |
| 66 | /** |
| 67 | * Minimum number of instances. |
| 68 | */ |
| 69 | minSize: number; |
| 70 | /** |
| 71 | * Maximum number of instances. |
| 72 | */ |
| 73 | maxSize: number; |
| 74 | /** |
| 75 | * Desired number of instances. When omitted, updates leave the live value |
| 76 | * alone so external scalers (e.g. ECS managed scaling) keep control. |
| 77 | * @default minSize |
| 78 | */ |
| 79 | desiredCapacity?: number; |
| 80 | /** |
| 81 | * Target groups to attach to the fleet. |
| 82 | */ |
| 83 | targetGroupArns?: Input<string[]>; |
| 84 | /** |
| 85 | * Health check type. |
| 86 | * @default "ELB" when target groups are present, otherwise "EC2" |
| 87 | */ |
| 88 | healthCheckType?: "EC2" | "ELB"; |
| 89 | /** |
| 90 | * Grace period before health checks start, e.g. `"5 minutes"` or |
| 91 | * `Duration.seconds(300)` (whole seconds on the wire). |
| 92 | */ |
| 93 | healthCheckGracePeriod?: Duration.Input; |
| 94 | /** |
| 95 | * Default cooldown between scaling activities, e.g. `"5 minutes"` or |
| 96 | * `Duration.seconds(300)` (whole seconds on the wire). |
| 97 | */ |
| 98 | defaultCooldown?: Duration.Input; |
| 99 | /** |
| 100 | * Termination policies for scale-in. |
| 101 | */ |
| 102 | terminationPolicies?: string[]; |
| 103 | /** |
| 104 | * Instance attributes (vCPUs, memory, burstable, generations, …) to launch |
| 105 | * by instead of the launch template's instance type. Auto Scaling picks |
| 106 | * every instance type that matches. |
| 107 | * |
| 108 | * When set, the group is configured with a mixed instances policy whose |
| 109 | * single override carries these requirements; removing it switches the |
| 110 | * group back to the plain launch template. |
| 111 | */ |
| 112 | instanceRequirements?: autoscaling.InstanceRequirements; |
| 113 | /** |
| 114 | * How capacity is spread across Availability Zones. Removing it resets the |
| 115 | * group to the AWS default. |
| 116 | * @default { CapacityDistributionStrategy: "balanced-best-effort" } |
| 117 | */ |
| 118 | availabilityZoneDistribution?: autoscaling.AvailabilityZoneDistribution; |
| 119 | /** |
| 120 | * Tags to apply to the Auto Scaling Group itself. |
| 121 | */ |
| 122 | tags?: Record<string, string>; |
| 123 | } |
| 124 | |
| 125 | export interface AutoScalingGroup extends Resource< |
| 126 | "AWS.AutoScaling.AutoScalingGroup", |
| 127 | AutoScalingGroupProps, |
| 128 | { |
| 129 | /** |
| 130 | * ARN of the Auto Scaling Group. |
| 131 | */ |
| 132 | autoScalingGroupArn: string; |
| 133 | /** |
| 134 | * Name of the Auto Scaling Group. |
| 135 | */ |
| 136 | autoScalingGroupName: AutoScalingGroupName; |
| 137 | /** |
| 138 | * ID of the launch template used by the fleet. |
| 139 | */ |
| 140 | launchTemplateId?: string; |
| 141 | /** |
| 142 | * Name of the launch template used by the fleet. |
| 143 | */ |
| 144 | launchTemplateName?: string; |
| 145 | /** |
| 146 | * Launch template version used by the fleet (e.g. `"$Default"` or a |
| 147 | * version number). |
| 148 | */ |
| 149 | launchTemplateVersion?: string; |
| 150 | /** |
| 151 | * Subnets the fleet is placed into. |
| 152 | */ |
| 153 | subnetIds: string[]; |
| 154 | /** |
| 155 | * Minimum number of instances. |
| 156 | */ |
| 157 | minSize: number; |
| 158 | /** |
| 159 | * Maximum number of instances. |
| 160 | */ |
| 161 | maxSize: number; |
| 162 | /** |
| 163 | * Desired number of instances. |
| 164 | */ |
| 165 | desiredCapacity: number; |
| 166 | /** |
| 167 | * Load balancer target groups the fleet is registered with. |
| 168 | */ |
| 169 | targetGroupArns: string[]; |
| 170 | /** |
| 171 | * Health check type (`EC2` or `ELB`). |
| 172 | */ |
| 173 | healthCheckType?: string; |
| 174 | /** |
| 175 | * Grace period in seconds before health checks start. |
| 176 | */ |
| 177 | healthCheckGracePeriod?: number; |
| 178 | /** |
| 179 | * Default cooldown in seconds between scaling activities. |
| 180 | */ |
| 181 | defaultCooldown?: number; |
| 182 | /** |
| 183 | * Termination policies applied on scale-in. |
| 184 | */ |
| 185 | terminationPolicies?: string[]; |
| 186 | /** |
| 187 | * Instance requirements of the group's mixed instances policy, when it |
| 188 | * launches by attributes rather than a fixed instance type. |
| 189 | */ |
| 190 | instanceRequirements?: autoscaling.InstanceRequirements; |
| 191 | /** |
| 192 | * How capacity is spread across Availability Zones. |
| 193 | */ |
| 194 | availabilityZoneDistribution?: autoscaling.AvailabilityZoneDistribution; |
| 195 | /** |
| 196 | * Tags on the Auto Scaling Group. |
| 197 | */ |
| 198 | tags: Record<string, string>; |
| 199 | }, |
| 200 | never, |
| 201 | Providers |
| 202 | > {} |
| 203 | |
| 204 | /** |
| 205 | * An EC2 Auto Scaling Group that manages a fleet of instances from a launch |
| 206 | * template and can register that fleet with one or more load balancer target |
| 207 | * groups. |
| 208 | * |
| 209 | * Pair with {@link ScalingPolicy} for target-tracking scaling, |
| 210 | * {@link ScheduledAction} for time-based capacity changes, and |
| 211 | * {@link consumeLifecycleActions} to run a Lambda handler while instances |
| 212 | * pause during launch/terminate transitions. |
| 213 | * ### Creating an Auto Scaling Group |
| 214 | * **Example:** Fleet from a Launch Template |
| 215 | * ```typescript |
| 216 | * import { AutoScalingGroup, LaunchTemplate } from "@alchemy.run/aws/AutoScaling"; |
| 217 | * import { Subnet, Vpc } from "@alchemy.run/aws/EC2"; |
| 218 | * |
| 219 | * const vpc = yield* Vpc("Vpc", { cidrBlock: "10.0.0.0/16" }); |
| 220 | * const subnet = yield* Subnet("Subnet", { |
| 221 | * vpcId: vpc.vpcId, |
| 222 | * cidrBlock: "10.0.1.0/24", |
| 223 | * }); |
| 224 | * |
| 225 | * const template = yield* LaunchTemplate("Template", { |
| 226 | * imageId: "ami-0abcdef1234567890", |
| 227 | * instanceType: "t3.micro", |
| 228 | * }); |
| 229 | * |
| 230 | * const group = yield* AutoScalingGroup("Fleet", { |
| 231 | * launchTemplate: template, |
| 232 | * subnetIds: [subnet.subnetId], |
| 233 | * minSize: 1, |
| 234 | * maxSize: 3, |
| 235 | * }); |
| 236 | * ``` |
| 237 | * |
| 238 | * **Example:** Reference an existing Launch Template by name |
| 239 | * ```typescript |
| 240 | * const group = yield* AutoScalingGroup("Fleet", { |
| 241 | * launchTemplate: { launchTemplateName: "my-template", version: 2 }, |
| 242 | * subnetIds: [subnet.subnetId], |
| 243 | * minSize: 0, |
| 244 | * maxSize: 0, |
| 245 | * desiredCapacity: 0, |
| 246 | * }); |
| 247 | * ``` |
| 248 | * |
| 249 | * ### Load Balancing |
| 250 | * **Example:** Register the fleet with a target group |
| 251 | * ```typescript |
| 252 | * const group = yield* AutoScalingGroup("WebFleet", { |
| 253 | * launchTemplate: template, |
| 254 | * subnetIds: [subnetA.subnetId, subnetB.subnetId], |
| 255 | * minSize: 2, |
| 256 | * maxSize: 6, |
| 257 | * targetGroupArns: [targetGroup.targetGroupArn], |
| 258 | * // healthCheckType defaults to "ELB" when target groups are attached |
| 259 | * healthCheckGracePeriod: "5 minutes", |
| 260 | * }); |
| 261 | * ``` |
| 262 | * |
| 263 | * ### Choosing Instance Types by Attributes |
| 264 | * **Example:** Launch any burstable type with 2 vCPUs and 4–8 GiB |
| 265 | * ```typescript |
| 266 | * const group = yield* AutoScalingGroup("Fleet", { |
| 267 | * launchTemplate: template, |
| 268 | * subnetIds: [subnetA.subnetId, subnetB.subnetId], |
| 269 | * minSize: 1, |
| 270 | * maxSize: 4, |
| 271 | * instanceRequirements: { |
| 272 | * VCpuCount: { Min: 2, Max: 2 }, |
| 273 | * MemoryMiB: { Min: 4096, Max: 8192 }, |
| 274 | * BurstablePerformance: "required", |
| 275 | * }, |
| 276 | * // keep zones strictly balanced instead of launching elsewhere |
| 277 | * availabilityZoneDistribution: { |
| 278 | * CapacityDistributionStrategy: "balanced-only", |
| 279 | * }, |
| 280 | * }); |
| 281 | * ``` |
| 282 | * |
| 283 | * ### Scaling |
| 284 | * **Example:** Track average CPU utilization |
| 285 | * ```typescript |
| 286 | * import { ScalingPolicy } from "@alchemy.run/aws/AutoScaling"; |
| 287 | * |
| 288 | * yield* ScalingPolicy("CpuPolicy", { |
| 289 | * autoScalingGroup: group, |
| 290 | * predefinedMetricType: "ASGAverageCPUUtilization", |
| 291 | * targetValue: 60, |
| 292 | * }); |
| 293 | * ``` |
| 294 | * |
| 295 | * @resource |
| 296 | */ |
| 297 | export const AutoScalingGroup = Resource<AutoScalingGroup>("AWS.AutoScaling.AutoScalingGroup"); |
| 298 | |
| 299 | const DEFAULT_CAPACITY_DISTRIBUTION_STRATEGY = "balanced-best-effort"; |
| 300 | |
| 301 | const sortStrings = (values: readonly string[] = []) => |
| 302 | [...values].sort((a, b) => a.localeCompare(b)); |
| 303 | |
| 304 | /** |
| 305 | * A launch template naming a just-created instance profile is rejected until |
| 306 | * IAM propagates it; retry that rejection (bounded, ~1 minute). |
| 307 | */ |
| 308 | const retryInstanceProfilePropagation = <A, R>( |
| 309 | effect: Effect.Effect< |
| 310 | A, |
| 311 | autoscaling.CreateAutoScalingGroupError | autoscaling.UpdateAutoScalingGroupError, |
| 312 | R |
| 313 | >, |
| 314 | ) => |
| 315 | effect.pipe( |
| 316 | Effect.retry({ |
| 317 | while: (error) => error._tag === "InvalidIamInstanceProfile", |
| 318 | schedule: Schedule.max([Schedule.recurs(10), Schedule.exponential("1 second")]), |
| 319 | }), |
| 320 | ); |
| 321 | |
| 322 | export const AutoScalingGroupProvider = () => |
| 323 | Provider.effect( |
| 324 | AutoScalingGroup, |
| 325 | Effect.gen(function* () { |
| 326 | const toName = (id: string, props: { autoScalingGroupName?: string } = {}) => |
| 327 | props.autoScalingGroupName |
| 328 | ? Effect.succeed(props.autoScalingGroupName) |
| 329 | : createPhysicalName({ id, maxLength: 255, lowercase: true }); |
| 330 | |
| 331 | const toLaunchTemplateSpec = (input: AutoScalingGroupProps["launchTemplate"]) => { |
| 332 | // A whole-resource `launchTemplate: template` resolves to the |
| 333 | // LaunchTemplate's bare Attributes before reaching the provider — |
| 334 | // the resource `Type` marker does not survive resolution — so narrow |
| 335 | // on the attributes shape (`launchTemplateArn` exists only on |
| 336 | // attributes, never on a LaunchTemplateReference). Attributes carry |
| 337 | // BOTH id and name, and the API rejects a spec with both, so send |
| 338 | // the id alone. |
| 339 | const attrs = input as Partial<LaunchTemplateResource["Attributes"]> | undefined; |
| 340 | if (typeof attrs?.launchTemplateArn === "string") { |
| 341 | return { |
| 342 | LaunchTemplateId: attrs.launchTemplateId as string | undefined, |
| 343 | LaunchTemplateName: undefined, |
| 344 | Version: |
| 345 | attrs.defaultVersionNumber === undefined |
| 346 | ? "$Default" |
| 347 | : String(attrs.defaultVersionNumber), |
| 348 | }; |
| 349 | } |
| 350 | |
| 351 | const spec = (input ?? {}) as LaunchTemplateReference; |
| 352 | return { |
| 353 | LaunchTemplateId: spec.launchTemplateId as string | undefined, |
| 354 | LaunchTemplateName: spec.launchTemplateName as string | undefined, |
| 355 | Version: |
| 356 | spec.version === undefined ? "$Default" : String(spec.version as string | number), |
| 357 | }; |
| 358 | }; |
| 359 | |
| 360 | const describeGroup = (autoScalingGroupName: string) => |
| 361 | autoscaling |
| 362 | .describeAutoScalingGroups({ |
| 363 | AutoScalingGroupNames: [autoScalingGroupName], |
| 364 | }) |
| 365 | .pipe(Effect.map((result) => result.AutoScalingGroups?.[0])); |
| 366 | |
| 367 | const toTags = (name: string, tags: Record<string, string>) => |
| 368 | Object.entries(tags).map(([Key, Value]) => ({ |
| 369 | ResourceId: name, |
| 370 | ResourceType: "auto-scaling-group", |
| 371 | Key, |
| 372 | Value, |
| 373 | PropagateAtLaunch: false, |
| 374 | })); |
| 375 | |
| 376 | const syncTargetGroups = Effect.fn(function* ({ |
| 377 | autoScalingGroupName, |
| 378 | oldTargetGroupArns, |
| 379 | newTargetGroupArns, |
| 380 | }: { |
| 381 | autoScalingGroupName: string; |
| 382 | oldTargetGroupArns: string[]; |
| 383 | newTargetGroupArns: string[]; |
| 384 | }) { |
| 385 | const oldSet = new Set(oldTargetGroupArns); |
| 386 | const newSet = new Set(newTargetGroupArns); |
| 387 | |
| 388 | const detached = oldTargetGroupArns.filter((arn) => !newSet.has(arn)); |
| 389 | const attached = newTargetGroupArns.filter((arn) => !oldSet.has(arn)); |
| 390 | |
| 391 | if (detached.length > 0) { |
| 392 | yield* autoscaling.detachLoadBalancerTargetGroups({ |
| 393 | AutoScalingGroupName: autoScalingGroupName, |
| 394 | TargetGroupARNs: detached, |
| 395 | } as any); |
| 396 | } |
| 397 | |
| 398 | if (attached.length > 0) { |
| 399 | yield* autoscaling.attachLoadBalancerTargetGroups({ |
| 400 | AutoScalingGroupName: autoScalingGroupName, |
| 401 | TargetGroupARNs: attached, |
| 402 | } as any); |
| 403 | } |
| 404 | }); |
| 405 | |
| 406 | const syncTags = Effect.fn(function* ({ |
| 407 | autoScalingGroupName, |
| 408 | oldTags, |
| 409 | newTags, |
| 410 | }: { |
| 411 | autoScalingGroupName: string; |
| 412 | oldTags: Record<string, string>; |
| 413 | newTags: Record<string, string>; |
| 414 | }) { |
| 415 | const { removed, upsert } = diffTags(oldTags, newTags); |
| 416 | |
| 417 | if (removed.length > 0) { |
| 418 | yield* autoscaling.deleteTags({ |
| 419 | Tags: removed.map((Key) => ({ |
| 420 | ResourceId: autoScalingGroupName, |
| 421 | ResourceType: "auto-scaling-group", |
| 422 | Key, |
| 423 | })), |
| 424 | } as any); |
| 425 | } |
| 426 | |
| 427 | if (upsert.length > 0) { |
| 428 | yield* autoscaling.createOrUpdateTags({ |
| 429 | Tags: upsert.map(({ Key, Value }) => ({ |
| 430 | ResourceId: autoScalingGroupName, |
| 431 | ResourceType: "auto-scaling-group", |
| 432 | Key, |
| 433 | Value, |
| 434 | PropagateAtLaunch: false, |
| 435 | })), |
| 436 | } as any); |
| 437 | } |
| 438 | }); |
| 439 | |
| 440 | const toAttributes = ( |
| 441 | group: autoscaling.AutoScalingGroup, |
| 442 | ): AutoScalingGroup["Attributes"] => { |
| 443 | // A group launching by attributes carries its template inside the |
| 444 | // mixed instances policy instead of `LaunchTemplate`. |
| 445 | const mixed = group.MixedInstancesPolicy?.LaunchTemplate; |
| 446 | const launchTemplate = group.LaunchTemplate ?? mixed?.LaunchTemplateSpecification; |
| 447 | return { |
| 448 | autoScalingGroupArn: group.AutoScalingGroupARN!, |
| 449 | autoScalingGroupName: group.AutoScalingGroupName!, |
| 450 | launchTemplateId: launchTemplate?.LaunchTemplateId, |
| 451 | launchTemplateName: launchTemplate?.LaunchTemplateName, |
| 452 | launchTemplateVersion: launchTemplate?.Version, |
| 453 | subnetIds: String(group.VPCZoneIdentifier ?? "") |
| 454 | .split(",") |
| 455 | .filter(Boolean), |
| 456 | minSize: group.MinSize ?? 0, |
| 457 | maxSize: group.MaxSize ?? 0, |
| 458 | desiredCapacity: group.DesiredCapacity ?? 0, |
| 459 | targetGroupArns: sortStrings(group.TargetGroupARNs ?? []), |
| 460 | healthCheckType: group.HealthCheckType, |
| 461 | healthCheckGracePeriod: group.HealthCheckGracePeriod, |
| 462 | defaultCooldown: group.DefaultCooldown, |
| 463 | terminationPolicies: group.TerminationPolicies ?? [], |
| 464 | instanceRequirements: mixed?.Overrides?.find((o) => o.InstanceRequirements) |
| 465 | ?.InstanceRequirements, |
| 466 | availabilityZoneDistribution: group.AvailabilityZoneDistribution, |
| 467 | tags: Object.fromEntries( |
| 468 | (group.Tags ?? []) |
| 469 | .filter((tag): tag is { Key: string; Value: string } => |
| 470 | Boolean(tag.Key && tag.Value !== undefined), |
| 471 | ) |
| 472 | .map((tag) => [tag.Key, tag.Value]), |
| 473 | ), |
| 474 | }; |
| 475 | }; |
| 476 | |
| 477 | return { |
| 478 | stables: ["autoScalingGroupArn", "autoScalingGroupName"], |
| 479 | list: () => |
| 480 | // `describeAutoScalingGroups` is paginated; collect every page and |
| 481 | // flatten the `AutoScalingGroups` array into full `Attributes`. |
| 482 | autoscaling.describeAutoScalingGroups.pages({}).pipe( |
| 483 | Stream.runCollect, |
| 484 | Effect.map((chunk) => |
| 485 | Array.from(chunk).flatMap((page) => (page.AutoScalingGroups ?? []).map(toAttributes)), |
| 486 | ), |
| 487 | ), |
| 488 | diff: Effect.fn(function* ({ id, olds, news: _news }) { |
| 489 | if (!isResolved(_news)) return undefined; |
| 490 | const news = _news as typeof olds; |
| 491 | const oldName = yield* toName(id, olds ?? {}); |
| 492 | const newName = yield* toName(id, news ?? {}); |
| 493 | if (oldName !== newName) { |
| 494 | return { action: "replace", deleteFirst: true } as const; |
| 495 | } |
| 496 | |
| 497 | if (!deepEqual(olds, news)) { |
| 498 | return { |
| 499 | action: "update", |
| 500 | stables: ["autoScalingGroupArn", "autoScalingGroupName"], |
| 501 | } as const; |
| 502 | } |
| 503 | }), |
| 504 | read: Effect.fn(function* ({ id, olds, output }) { |
| 505 | const name = output?.autoScalingGroupName ?? (yield* toName(id, olds ?? {})); |
| 506 | const group = yield* describeGroup(name); |
| 507 | return group ? toAttributes(group) : undefined; |
| 508 | }), |
| 509 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 510 | const autoScalingGroupName = output?.autoScalingGroupName ?? (yield* toName(id, news)); |
| 511 | const desiredTags = { |
| 512 | ...(yield* createInternalTags(id)), |
| 513 | ...news.tags, |
| 514 | }; |
| 515 | const targetGroupArns = sortStrings((news.targetGroupArns ?? []) as string[]); |
| 516 | // With instance requirements the template goes inside a mixed |
| 517 | // instances policy; without, it is the plain `LaunchTemplate`. |
| 518 | // Either form replaces the other on `updateAutoScalingGroup`. |
| 519 | const launchTemplate = news.instanceRequirements |
| 520 | ? { |
| 521 | MixedInstancesPolicy: { |
| 522 | LaunchTemplate: { |
| 523 | LaunchTemplateSpecification: toLaunchTemplateSpec(news.launchTemplate), |
| 524 | Overrides: [{ InstanceRequirements: news.instanceRequirements }], |
| 525 | }, |
| 526 | }, |
| 527 | } |
| 528 | : { LaunchTemplate: toLaunchTemplateSpec(news.launchTemplate) }; |
| 529 | const capacityDistributionStrategy = |
| 530 | news.availabilityZoneDistribution?.CapacityDistributionStrategy ?? |
| 531 | DEFAULT_CAPACITY_DISTRIBUTION_STRATEGY; |
| 532 | const healthCheckType = |
| 533 | news.healthCheckType ?? (targetGroupArns.length > 0 ? "ELB" : "EC2"); |
| 534 | |
| 535 | // Observe — fetch live state. `describeAutoScalingGroups` returns |
| 536 | // an empty list when the ASG is missing; we never trust `output` |
| 537 | // alone since the ASG may have been deleted out of band. |
| 538 | let existing = yield* describeGroup(autoScalingGroupName); |
| 539 | |
| 540 | // Ensure — create the ASG if missing. `createAutoScalingGroup` |
| 541 | // raises `AlreadyExistsFault` on a race; we fall through to the |
| 542 | // sync path on that case. |
| 543 | if (!existing) { |
| 544 | yield* autoscaling |
| 545 | .createAutoScalingGroup({ |
| 546 | AutoScalingGroupName: autoScalingGroupName, |
| 547 | MinSize: news.minSize, |
| 548 | MaxSize: news.maxSize, |
| 549 | DesiredCapacity: news.desiredCapacity ?? news.minSize, |
| 550 | ...launchTemplate, |
| 551 | AvailabilityZoneDistribution: { |
| 552 | CapacityDistributionStrategy: capacityDistributionStrategy, |
| 553 | }, |
| 554 | VPCZoneIdentifier: (news.subnetIds as string[]).join(","), |
| 555 | TargetGroupARNs: targetGroupArns, |
| 556 | HealthCheckType: healthCheckType, |
| 557 | HealthCheckGracePeriod: toSeconds(news.healthCheckGracePeriod), |
| 558 | DefaultCooldown: toSeconds(news.defaultCooldown), |
| 559 | TerminationPolicies: news.terminationPolicies, |
| 560 | Tags: toTags(autoScalingGroupName, desiredTags), |
| 561 | } as any) |
| 562 | .pipe( |
| 563 | retryInstanceProfilePropagation, |
| 564 | Effect.catchTag("AlreadyExistsFault", () => Effect.void), |
| 565 | ); |
| 566 | |
| 567 | existing = yield* describeGroup(autoScalingGroupName).pipe( |
| 568 | Effect.filterOrFail( |
| 569 | Boolean, |
| 570 | () => |
| 571 | new AutoScalingGroupUnexpectedResponse({ |
| 572 | message: `Auto Scaling Group '${autoScalingGroupName}' was not readable after create`, |
| 573 | }), |
| 574 | ), |
| 575 | Effect.retry({ |
| 576 | while: () => true, |
| 577 | schedule: Schedule.max([Schedule.recurs(8), Schedule.exponential("250 millis")]), |
| 578 | }), |
| 579 | ); |
| 580 | } |
| 581 | |
| 582 | // Sync core ASG configuration — `updateAutoScalingGroup` |
| 583 | // overwrites min/max/desired/template/subnets/health-check |
| 584 | // settings in one call, so we issue it unconditionally |
| 585 | // (idempotent for matching values). The zone distribution is |
| 586 | // diffed against the observed group (absent = the AWS default) |
| 587 | // and sent only when it differs. |
| 588 | const observedCapacityDistributionStrategy = |
| 589 | existing.AvailabilityZoneDistribution?.CapacityDistributionStrategy ?? |
| 590 | DEFAULT_CAPACITY_DISTRIBUTION_STRATEGY; |
| 591 | yield* autoscaling |
| 592 | .updateAutoScalingGroup({ |
| 593 | AutoScalingGroupName: autoScalingGroupName, |
| 594 | MinSize: news.minSize, |
| 595 | MaxSize: news.maxSize, |
| 596 | DesiredCapacity: news.desiredCapacity, |
| 597 | ...launchTemplate, |
| 598 | AvailabilityZoneDistribution: |
| 599 | observedCapacityDistributionStrategy === capacityDistributionStrategy |
| 600 | ? undefined |
| 601 | : { CapacityDistributionStrategy: capacityDistributionStrategy }, |
| 602 | VPCZoneIdentifier: (news.subnetIds as string[]).join(","), |
| 603 | HealthCheckType: healthCheckType, |
| 604 | HealthCheckGracePeriod: toSeconds(news.healthCheckGracePeriod), |
| 605 | DefaultCooldown: toSeconds(news.defaultCooldown), |
| 606 | TerminationPolicies: news.terminationPolicies, |
| 607 | } as any) |
| 608 | .pipe(retryInstanceProfilePropagation); |
| 609 | |
| 610 | // Sync target groups — observed cloud attachments vs desired. |
| 611 | const observedAttrs = toAttributes(existing); |
| 612 | yield* syncTargetGroups({ |
| 613 | autoScalingGroupName, |
| 614 | oldTargetGroupArns: sortStrings(existing.TargetGroupARNs ?? []), |
| 615 | newTargetGroupArns: targetGroupArns, |
| 616 | }); |
| 617 | |
| 618 | // Sync tags — observed cloud tags vs desired. Adoption brings |
| 619 | // tags through `existing.Tags`; we converge regardless of what |
| 620 | // was there before. |
| 621 | yield* syncTags({ |
| 622 | autoScalingGroupName, |
| 623 | oldTags: observedAttrs.tags, |
| 624 | newTags: desiredTags, |
| 625 | }); |
| 626 | |
| 627 | // Re-read final state so attributes reflect post-sync cloud |
| 628 | // state. |
| 629 | const group = yield* describeGroup(autoScalingGroupName).pipe( |
| 630 | Effect.filterOrFail( |
| 631 | Boolean, |
| 632 | () => |
| 633 | new AutoScalingGroupUnexpectedResponse({ |
| 634 | message: `Auto Scaling Group '${autoScalingGroupName}' was not readable after reconcile`, |
| 635 | }), |
| 636 | ), |
| 637 | ); |
| 638 | yield* session.note(autoScalingGroupName); |
| 639 | return toAttributes(group); |
| 640 | }), |
| 641 | delete: Effect.fn(function* ({ output }) { |
| 642 | const existing = yield* describeGroup(output.autoScalingGroupName); |
| 643 | if (!existing) { |
| 644 | return; |
| 645 | } |
| 646 | |
| 647 | yield* autoscaling.deleteAutoScalingGroup({ |
| 648 | AutoScalingGroupName: output.autoScalingGroupName, |
| 649 | ForceDelete: true, |
| 650 | } as any); |
| 651 | |
| 652 | yield* describeGroup(output.autoScalingGroupName).pipe( |
| 653 | Effect.flatMap((group) => |
| 654 | group |
| 655 | ? Effect.fail( |
| 656 | new AutoScalingGroupNotReady({ message: "AutoScalingGroupStillExists" }), |
| 657 | ) |
| 658 | : Effect.void, |
| 659 | ), |
| 660 | Effect.retry({ |
| 661 | while: (error) => |
| 662 | error._tag === "AutoScalingGroupNotReady" && |
| 663 | error.message === "AutoScalingGroupStillExists", |
| 664 | schedule: Schedule.max([Schedule.recurs(12), Schedule.exponential("250 millis")]), |
| 665 | }), |
| 666 | ); |
| 667 | }), |
| 668 | }; |
| 669 | }), |
| 670 | ); |