The best way to control Claude Code, Codex and more from any computer or phone
| 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 { toSeconds } from "alchemy/Util/Duration"; |
| 8 | import * as Data from "effect/Data"; |
| 9 | import type * as Duration from "effect/Duration"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as Stream from "effect/Stream"; |
| 12 | import type { Providers } from "../Providers.ts"; |
| 13 | import type { AutoScalingGroup as AutoScalingGroupResource } from "./AutoScalingGroup.ts"; |
| 14 | |
| 15 | export class ScalingPolicyUnexpectedResponse extends Data.TaggedError( |
| 16 | "ScalingPolicyUnexpectedResponse", |
| 17 | )<{ |
| 18 | readonly message: string; |
| 19 | readonly cause?: unknown; |
| 20 | }> {} |
| 21 | |
| 22 | export type ScalingPolicyName = string; |
| 23 | |
| 24 | export interface ScalingPolicyProps { |
| 25 | /** |
| 26 | * Policy name. If omitted, a deterministic name is generated. |
| 27 | */ |
| 28 | policyName?: string; |
| 29 | /** |
| 30 | * Auto Scaling Group to attach the policy to. |
| 31 | */ |
| 32 | autoScalingGroup: Input<string> | AutoScalingGroupResource; |
| 33 | /** |
| 34 | * Policy type. |
| 35 | * @default "TargetTrackingScaling" |
| 36 | */ |
| 37 | policyType?: "TargetTrackingScaling"; |
| 38 | /** |
| 39 | * Predefined scaling metric to track. |
| 40 | */ |
| 41 | predefinedMetricType: |
| 42 | | "ASGAverageCPUUtilization" |
| 43 | | "ASGAverageNetworkIn" |
| 44 | | "ASGAverageNetworkOut" |
| 45 | | "ALBRequestCountPerTarget"; |
| 46 | /** |
| 47 | * Desired target value for the metric. |
| 48 | */ |
| 49 | targetValue: number; |
| 50 | /** |
| 51 | * Disable scale-in while target tracking is active. |
| 52 | */ |
| 53 | disableScaleIn?: boolean; |
| 54 | /** |
| 55 | * Estimated warmup time for new instances, e.g. `"5 minutes"` or |
| 56 | * `Duration.seconds(300)` (whole seconds on the wire). |
| 57 | */ |
| 58 | estimatedInstanceWarmup?: Duration.Input; |
| 59 | } |
| 60 | |
| 61 | export interface ScalingPolicy extends Resource< |
| 62 | "AWS.AutoScaling.ScalingPolicy", |
| 63 | ScalingPolicyProps, |
| 64 | { |
| 65 | /** |
| 66 | * ARN of the scaling policy. |
| 67 | */ |
| 68 | policyArn: string; |
| 69 | /** |
| 70 | * Name of the scaling policy. |
| 71 | */ |
| 72 | policyName: ScalingPolicyName; |
| 73 | /** |
| 74 | * Name of the Auto Scaling Group the policy is attached to. |
| 75 | */ |
| 76 | autoScalingGroupName: string; |
| 77 | /** |
| 78 | * Policy type (e.g. `TargetTrackingScaling`). |
| 79 | */ |
| 80 | policyType: string; |
| 81 | /** |
| 82 | * Target value the tracked metric is held at. |
| 83 | */ |
| 84 | targetValue: number; |
| 85 | /** |
| 86 | * Predefined metric being tracked. |
| 87 | */ |
| 88 | predefinedMetricType: string; |
| 89 | /** |
| 90 | * CloudWatch alarms created by EC2 Auto Scaling to drive the policy. |
| 91 | */ |
| 92 | alarms: string[]; |
| 93 | }, |
| 94 | never, |
| 95 | Providers |
| 96 | > {} |
| 97 | |
| 98 | /** |
| 99 | * A target-tracking scaling policy for an Auto Scaling Group. EC2 Auto |
| 100 | * Scaling creates and manages the CloudWatch alarms that keep the tracked |
| 101 | * metric at `targetValue` by adjusting the group's desired capacity. |
| 102 | * ### Creating a Scaling Policy |
| 103 | * **Example:** Track average CPU utilization |
| 104 | * ```typescript |
| 105 | * import { AutoScalingGroup, ScalingPolicy } from "@alchemy.run/aws/AutoScaling"; |
| 106 | * |
| 107 | * const group = yield* AutoScalingGroup("Fleet", { |
| 108 | * launchTemplate: template, |
| 109 | * subnetIds: [subnet.subnetId], |
| 110 | * minSize: 1, |
| 111 | * maxSize: 4, |
| 112 | * }); |
| 113 | * |
| 114 | * const policy = yield* ScalingPolicy("CpuPolicy", { |
| 115 | * autoScalingGroup: group, |
| 116 | * predefinedMetricType: "ASGAverageCPUUtilization", |
| 117 | * targetValue: 60, |
| 118 | * }); |
| 119 | * ``` |
| 120 | * |
| 121 | * **Example:** Scale on ALB requests per target without scale-in |
| 122 | * ```typescript |
| 123 | * const policy = yield* ScalingPolicy("RequestPolicy", { |
| 124 | * autoScalingGroup: group, |
| 125 | * predefinedMetricType: "ALBRequestCountPerTarget", |
| 126 | * targetValue: 1000, |
| 127 | * disableScaleIn: true, |
| 128 | * estimatedInstanceWarmup: "3 minutes", |
| 129 | * }); |
| 130 | * ``` |
| 131 | * |
| 132 | * @resource |
| 133 | */ |
| 134 | export const ScalingPolicy = Resource<ScalingPolicy>("AWS.AutoScaling.ScalingPolicy"); |
| 135 | |
| 136 | export const ScalingPolicyProvider = () => |
| 137 | Provider.effect( |
| 138 | ScalingPolicy, |
| 139 | Effect.gen(function* () { |
| 140 | const toName = (id: string, props: { policyName?: string } = {}) => |
| 141 | props.policyName |
| 142 | ? Effect.succeed(props.policyName) |
| 143 | : createPhysicalName({ id, maxLength: 255, lowercase: true }); |
| 144 | |
| 145 | // Derive the group name from either spelling of `autoScalingGroup`. A |
| 146 | // whole AutoScalingGroup resource resolves to its bare Attributes |
| 147 | // before reaching the provider — the resource `Type` marker does not |
| 148 | // survive resolution — so narrow on the attributes shape, never on |
| 149 | // `Type`. May also receive `undefined`: an Output-valued |
| 150 | // `autoScalingGroup` doesn't survive a `creating`-state round-trip |
| 151 | // (it deserializes as `undefined`), and recovery paths hand those |
| 152 | // props back as `olds`. |
| 153 | const toAutoScalingGroupName = ( |
| 154 | input: ScalingPolicyProps["autoScalingGroup"] | undefined, |
| 155 | ): string | undefined => |
| 156 | typeof input === "string" |
| 157 | ? input |
| 158 | : typeof (input as { autoScalingGroupName?: unknown } | undefined) |
| 159 | ?.autoScalingGroupName === "string" |
| 160 | ? (input as unknown as { autoScalingGroupName: string }).autoScalingGroupName |
| 161 | : undefined; |
| 162 | |
| 163 | // `describePolicies` searches account-wide when no AutoScalingGroupName |
| 164 | // is given; policy names are unique physical names, so a name-only |
| 165 | // lookup still identifies our policy during state recovery. |
| 166 | const describePolicy = ({ |
| 167 | autoScalingGroupName, |
| 168 | policyName, |
| 169 | }: { |
| 170 | autoScalingGroupName: string | undefined; |
| 171 | policyName: string; |
| 172 | }) => |
| 173 | autoscaling |
| 174 | .describePolicies({ |
| 175 | AutoScalingGroupName: autoScalingGroupName, |
| 176 | PolicyNames: [policyName], |
| 177 | }) |
| 178 | .pipe(Effect.map((result) => result.ScalingPolicies?.[0])); |
| 179 | |
| 180 | const toAttributes = (policy: autoscaling.ScalingPolicy): ScalingPolicy["Attributes"] => ({ |
| 181 | policyArn: policy.PolicyARN!, |
| 182 | policyName: policy.PolicyName!, |
| 183 | autoScalingGroupName: policy.AutoScalingGroupName!, |
| 184 | policyType: policy.PolicyType!, |
| 185 | targetValue: |
| 186 | policy.TargetTrackingConfiguration?.TargetValue ?? |
| 187 | policy.StepAdjustments?.[0]?.MetricIntervalLowerBound ?? |
| 188 | 0, |
| 189 | predefinedMetricType: |
| 190 | policy.TargetTrackingConfiguration?.PredefinedMetricSpecification?.PredefinedMetricType ?? |
| 191 | "", |
| 192 | alarms: (policy.Alarms ?? []) |
| 193 | .map((alarm) => alarm.AlarmName) |
| 194 | .filter((alarm): alarm is string => Boolean(alarm)), |
| 195 | }); |
| 196 | |
| 197 | return { |
| 198 | stables: ["policyArn", "policyName", "autoScalingGroupName"], |
| 199 | // `describePolicies` enumerates every scaling policy across all Auto |
| 200 | // Scaling Groups in the account/region when no AutoScalingGroupName |
| 201 | // filter is supplied, so no parent enumeration is needed. |
| 202 | list: () => |
| 203 | autoscaling.describePolicies.pages({}).pipe( |
| 204 | Stream.runCollect, |
| 205 | Effect.map((chunk) => |
| 206 | Array.from(chunk).flatMap((page) => (page.ScalingPolicies ?? []).map(toAttributes)), |
| 207 | ), |
| 208 | ), |
| 209 | diff: Effect.fn(function* ({ id, olds, news: _news }) { |
| 210 | if (!isResolved(_news)) return undefined; |
| 211 | const news = _news as typeof olds; |
| 212 | const oldName = yield* toName(id, olds ?? {}); |
| 213 | const newName = yield* toName(id, news ?? {}); |
| 214 | // ASG change → replace, but only when both sides are known — a |
| 215 | // half-created state row may have lost an Output-valued |
| 216 | // `autoScalingGroup`, and an unknown old ASG must fall through to |
| 217 | // the create/update recovery path rather than force a replacement. |
| 218 | const oldGroupName = toAutoScalingGroupName(olds.autoScalingGroup); |
| 219 | const newGroupName = toAutoScalingGroupName(news.autoScalingGroup); |
| 220 | if ( |
| 221 | oldName !== newName || |
| 222 | (oldGroupName !== undefined && |
| 223 | newGroupName !== undefined && |
| 224 | oldGroupName !== newGroupName) |
| 225 | ) { |
| 226 | return { action: "replace" } as const; |
| 227 | } |
| 228 | |
| 229 | if (!deepEqual(olds, news)) { |
| 230 | return { |
| 231 | action: "update", |
| 232 | stables: ["policyArn", "policyName", "autoScalingGroupName"], |
| 233 | } as const; |
| 234 | } |
| 235 | }), |
| 236 | read: Effect.fn(function* ({ id, olds, output }) { |
| 237 | const autoScalingGroupName = |
| 238 | output?.autoScalingGroupName ?? toAutoScalingGroupName(olds?.autoScalingGroup); |
| 239 | const policyName = output?.policyName ?? (yield* toName(id, olds ?? {})); |
| 240 | const policy = yield* describePolicy({ |
| 241 | autoScalingGroupName, |
| 242 | policyName, |
| 243 | }); |
| 244 | return policy ? toAttributes(policy) : undefined; |
| 245 | }), |
| 246 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 247 | const autoScalingGroupName = |
| 248 | output?.autoScalingGroupName ?? toAutoScalingGroupName(news.autoScalingGroup); |
| 249 | const policyName = output?.policyName ?? (yield* toName(id, news)); |
| 250 | |
| 251 | // Ensure + Sync — `putScalingPolicy` is the single |
| 252 | // create-or-update API for a scaling policy. It's idempotent on |
| 253 | // matching params and overwrites policy type / target tracking |
| 254 | // config / estimated warmup on differences, so we issue it |
| 255 | // unconditionally. |
| 256 | yield* autoscaling.putScalingPolicy({ |
| 257 | AutoScalingGroupName: autoScalingGroupName, |
| 258 | PolicyName: policyName, |
| 259 | PolicyType: news.policyType ?? "TargetTrackingScaling", |
| 260 | TargetTrackingConfiguration: { |
| 261 | PredefinedMetricSpecification: { |
| 262 | PredefinedMetricType: news.predefinedMetricType, |
| 263 | }, |
| 264 | TargetValue: news.targetValue, |
| 265 | DisableScaleIn: news.disableScaleIn, |
| 266 | }, |
| 267 | EstimatedInstanceWarmup: toSeconds(news.estimatedInstanceWarmup), |
| 268 | } as any); |
| 269 | |
| 270 | // Observe final state — re-read so the returned attributes |
| 271 | // reflect the live cloud state (including the generated |
| 272 | // policyArn and any associated alarm names). |
| 273 | const policy = yield* describePolicy({ |
| 274 | autoScalingGroupName, |
| 275 | policyName, |
| 276 | }).pipe( |
| 277 | Effect.flatMap((policy) => |
| 278 | policy |
| 279 | ? Effect.succeed(policy) |
| 280 | : Effect.fail( |
| 281 | new ScalingPolicyUnexpectedResponse({ |
| 282 | message: `Scaling policy '${policyName}' was not readable after reconcile`, |
| 283 | }), |
| 284 | ), |
| 285 | ), |
| 286 | ); |
| 287 | yield* session.note(policyName); |
| 288 | return toAttributes(policy); |
| 289 | }), |
| 290 | delete: Effect.fn(function* ({ output }) { |
| 291 | yield* autoscaling.deletePolicy({ |
| 292 | AutoScalingGroupName: output.autoScalingGroupName, |
| 293 | PolicyName: output.policyName, |
| 294 | } as any); |
| 295 | }), |
| 296 | }; |
| 297 | }), |
| 298 | ); |