The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as aas from "@distilled.cloud/aws/application-auto-scaling"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import { diffTags, hasAlchemyTags, createInternalTags } from "alchemy/Tags"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Stream from "effect/Stream"; |
| 9 | import type { Providers } from "../Providers.ts"; |
| 10 | import { SERVICE_NAMESPACES } from "./internal.ts"; |
| 11 | |
| 12 | export interface ScalableTargetProps { |
| 13 | /** |
| 14 | * The namespace of the AWS service that provides the resource, |
| 15 | * e.g. `ecs`, `dynamodb`, `lambda`. |
| 16 | * |
| 17 | * Changing this triggers a replacement. |
| 18 | */ |
| 19 | serviceNamespace: aas.ServiceNamespace; |
| 20 | /** |
| 21 | * The identifier of the resource to scale, in the format the service |
| 22 | * expects — e.g. `service/{clusterName}/{serviceName}` for an ECS service |
| 23 | * or `table/{tableName}` for a DynamoDB table. |
| 24 | * |
| 25 | * Changing this triggers a replacement. |
| 26 | */ |
| 27 | resourceId: string; |
| 28 | /** |
| 29 | * The scalable dimension of the resource, |
| 30 | * e.g. `ecs:service:DesiredCount` or `dynamodb:table:ReadCapacityUnits`. |
| 31 | * |
| 32 | * Changing this triggers a replacement. |
| 33 | */ |
| 34 | scalableDimension: aas.ScalableDimension; |
| 35 | /** |
| 36 | * The minimum capacity that Application Auto Scaling may scale in to. |
| 37 | */ |
| 38 | minCapacity: number; |
| 39 | /** |
| 40 | * The maximum capacity that Application Auto Scaling may scale out to. |
| 41 | */ |
| 42 | maxCapacity: number; |
| 43 | /** |
| 44 | * IAM role that allows Application Auto Scaling to modify the scalable |
| 45 | * target on your behalf. For services that support service-linked roles |
| 46 | * (ECS, DynamoDB, Lambda, ...) omit this — AWS creates and uses the |
| 47 | * service-linked role automatically. |
| 48 | */ |
| 49 | roleArn?: string; |
| 50 | /** |
| 51 | * Suspend/resume the target's dynamic and scheduled scaling activities. |
| 52 | */ |
| 53 | suspendedState?: aas.SuspendedState; |
| 54 | /** |
| 55 | * User-defined tags to apply to the scalable target. |
| 56 | */ |
| 57 | tags?: Record<string, string>; |
| 58 | } |
| 59 | |
| 60 | export interface ScalableTarget extends Resource< |
| 61 | "AWS.ApplicationAutoScaling.ScalableTarget", |
| 62 | ScalableTargetProps, |
| 63 | { |
| 64 | /** |
| 65 | * Namespace of the AWS service that provides the resource. |
| 66 | */ |
| 67 | serviceNamespace: aas.ServiceNamespace; |
| 68 | /** |
| 69 | * Identifier of the scaled resource. |
| 70 | */ |
| 71 | resourceId: string; |
| 72 | /** |
| 73 | * Scalable dimension being managed. |
| 74 | */ |
| 75 | scalableDimension: aas.ScalableDimension; |
| 76 | /** |
| 77 | * ARN of the scalable target. |
| 78 | */ |
| 79 | scalableTargetArn: string; |
| 80 | /** |
| 81 | * Minimum capacity Application Auto Scaling may scale in to. |
| 82 | */ |
| 83 | minCapacity: number; |
| 84 | /** |
| 85 | * Maximum capacity Application Auto Scaling may scale out to. |
| 86 | */ |
| 87 | maxCapacity: number; |
| 88 | /** |
| 89 | * IAM role Application Auto Scaling uses to modify the target |
| 90 | * (service-linked role when none was supplied). |
| 91 | */ |
| 92 | roleArn: string; |
| 93 | /** |
| 94 | * Suspension state of dynamic and scheduled scaling activities. |
| 95 | */ |
| 96 | suspendedState: aas.SuspendedState | undefined; |
| 97 | /** |
| 98 | * Tags on the scalable target, as observed. Lets `alchemy drift` |
| 99 | * detect out-of-band changes. |
| 100 | */ |
| 101 | tags?: Record<string, string>; |
| 102 | }, |
| 103 | never, |
| 104 | Providers |
| 105 | > {} |
| 106 | |
| 107 | /** |
| 108 | * An Application Auto Scaling scalable target — registers a resource's |
| 109 | * capacity dimension (an ECS service's desired count, a DynamoDB table's |
| 110 | * read capacity, Lambda provisioned concurrency, ...) so that scaling |
| 111 | * policies and scheduled actions can act on it. |
| 112 | * |
| 113 | * A scalable target is uniquely identified by the |
| 114 | * (`serviceNamespace`, `resourceId`, `scalableDimension`) triple; changing |
| 115 | * any part of the triple replaces the target. Deregistering a scalable |
| 116 | * target deletes the scaling policies and scheduled actions associated |
| 117 | * with it. |
| 118 | * ### Creating Scalable Targets |
| 119 | * **Example:** Scale an ECS Service |
| 120 | * ```typescript |
| 121 | * const target = yield* ScalableTarget("ApiScaling", { |
| 122 | * serviceNamespace: "ecs", |
| 123 | * resourceId: Output.interpolate`service/${cluster.clusterName}/${service.serviceName}`, |
| 124 | * scalableDimension: "ecs:service:DesiredCount", |
| 125 | * minCapacity: 1, |
| 126 | * maxCapacity: 3, |
| 127 | * }); |
| 128 | * ``` |
| 129 | * |
| 130 | * **Example:** Scale DynamoDB Read Capacity |
| 131 | * ```typescript |
| 132 | * const target = yield* ScalableTarget("TableReadScaling", { |
| 133 | * serviceNamespace: "dynamodb", |
| 134 | * resourceId: Output.interpolate`table/${table.tableName}`, |
| 135 | * scalableDimension: "dynamodb:table:ReadCapacityUnits", |
| 136 | * minCapacity: 1, |
| 137 | * maxCapacity: 10, |
| 138 | * }); |
| 139 | * ``` |
| 140 | * |
| 141 | * ### Suspending Scaling |
| 142 | * **Example:** Suspend Dynamic Scale-In |
| 143 | * ```typescript |
| 144 | * yield* ScalableTarget("ApiScaling", { |
| 145 | * serviceNamespace: "ecs", |
| 146 | * resourceId: Output.interpolate`service/${cluster.clusterName}/${service.serviceName}`, |
| 147 | * scalableDimension: "ecs:service:DesiredCount", |
| 148 | * minCapacity: 1, |
| 149 | * maxCapacity: 3, |
| 150 | * suspendedState: { DynamicScalingInSuspended: true }, |
| 151 | * }); |
| 152 | * ``` |
| 153 | * |
| 154 | * @resource |
| 155 | */ |
| 156 | export const ScalableTarget = Resource<ScalableTarget>("AWS.ApplicationAutoScaling.ScalableTarget"); |
| 157 | |
| 158 | export const ScalableTargetProvider = () => |
| 159 | Provider.effect( |
| 160 | ScalableTarget, |
| 161 | Effect.gen(function* () { |
| 162 | const describe = (props: { |
| 163 | serviceNamespace: aas.ServiceNamespace; |
| 164 | resourceId: string; |
| 165 | scalableDimension: aas.ScalableDimension; |
| 166 | }) => |
| 167 | aas |
| 168 | .describeScalableTargets({ |
| 169 | ServiceNamespace: props.serviceNamespace, |
| 170 | ResourceIds: [props.resourceId], |
| 171 | ScalableDimension: props.scalableDimension, |
| 172 | }) |
| 173 | .pipe( |
| 174 | Effect.map((res) => |
| 175 | res.ScalableTargets?.find( |
| 176 | (t) => |
| 177 | t.ResourceId === props.resourceId && |
| 178 | t.ScalableDimension === props.scalableDimension, |
| 179 | ), |
| 180 | ), |
| 181 | ); |
| 182 | |
| 183 | const toAttributes = (target: aas.ScalableTarget): ScalableTarget["Attributes"] => ({ |
| 184 | serviceNamespace: target.ServiceNamespace, |
| 185 | resourceId: target.ResourceId, |
| 186 | scalableDimension: target.ScalableDimension, |
| 187 | scalableTargetArn: target.ScalableTargetARN ?? "", |
| 188 | minCapacity: target.MinCapacity, |
| 189 | maxCapacity: target.MaxCapacity, |
| 190 | roleArn: target.RoleARN, |
| 191 | suspendedState: target.SuspendedState, |
| 192 | }); |
| 193 | |
| 194 | const observedTags = (scalableTargetArn: string) => |
| 195 | aas.listTagsForResource({ ResourceARN: scalableTargetArn }).pipe( |
| 196 | Effect.map((res) => |
| 197 | Object.fromEntries( |
| 198 | Object.entries(res.Tags ?? {}).filter( |
| 199 | (entry): entry is [string, string] => entry[1] !== undefined, |
| 200 | ), |
| 201 | ), |
| 202 | ), |
| 203 | Effect.catchTag("ResourceNotFoundException", () => |
| 204 | Effect.succeed({} as Record<string, string>), |
| 205 | ), |
| 206 | ); |
| 207 | |
| 208 | // Derive the (namespace, resourceId, dimension) identity triple. |
| 209 | // `output` is preferred (it always survives state persistence); |
| 210 | // props may have lost Output-valued fields in a `creating`-state |
| 211 | // round-trip, so tolerate undefined and report "unknown identity". |
| 212 | const identityOf = ( |
| 213 | output: |
| 214 | | Pick< |
| 215 | ScalableTarget["Attributes"], |
| 216 | "serviceNamespace" | "resourceId" | "scalableDimension" |
| 217 | > |
| 218 | | undefined, |
| 219 | props: Partial<ScalableTargetProps> | undefined, |
| 220 | ) => { |
| 221 | const serviceNamespace = output?.serviceNamespace ?? props?.serviceNamespace; |
| 222 | const resourceId = output?.resourceId ?? props?.resourceId; |
| 223 | const scalableDimension = output?.scalableDimension ?? props?.scalableDimension; |
| 224 | return serviceNamespace !== undefined && |
| 225 | resourceId !== undefined && |
| 226 | scalableDimension !== undefined |
| 227 | ? { serviceNamespace, resourceId, scalableDimension } |
| 228 | : undefined; |
| 229 | }; |
| 230 | |
| 231 | return { |
| 232 | stables: ["serviceNamespace", "resourceId", "scalableDimension", "scalableTargetArn"], |
| 233 | |
| 234 | // Account/region-wide enumeration. The describe API requires a |
| 235 | // `ServiceNamespace` filter, so union the per-namespace pages over |
| 236 | // every known namespace. |
| 237 | list: () => |
| 238 | Effect.forEach( |
| 239 | SERVICE_NAMESPACES, |
| 240 | (namespace) => |
| 241 | aas.describeScalableTargets.pages({ ServiceNamespace: namespace }).pipe( |
| 242 | Stream.runCollect, |
| 243 | Effect.map((chunk) => |
| 244 | Array.from(chunk).flatMap((page) => |
| 245 | (page.ScalableTargets ?? []).map(toAttributes), |
| 246 | ), |
| 247 | ), |
| 248 | ), |
| 249 | { concurrency: 4 }, |
| 250 | ).pipe(Effect.map((groups) => groups.flat())), |
| 251 | |
| 252 | diff: Effect.fn(function* ({ news, olds }) { |
| 253 | if (!isResolved(news)) return undefined; |
| 254 | // The identity triple is immutable — any change replaces the |
| 255 | // target. Only compare sides that are actually known: a |
| 256 | // half-created state row may have lost Output-valued props. |
| 257 | for (const key of ["serviceNamespace", "resourceId", "scalableDimension"] as const) { |
| 258 | const oldValue = olds?.[key]; |
| 259 | if (oldValue !== undefined && isResolved(oldValue) && oldValue !== news[key]) { |
| 260 | return { action: "replace" } as const; |
| 261 | } |
| 262 | } |
| 263 | }), |
| 264 | |
| 265 | read: Effect.fn(function* ({ id, olds, output }) { |
| 266 | const identity = identityOf(output, olds); |
| 267 | if (identity === undefined) return undefined; |
| 268 | const found = yield* describe(identity); |
| 269 | if (!found) return undefined; |
| 270 | const tags = found.ScalableTargetARN ? yield* observedTags(found.ScalableTargetARN) : {}; |
| 271 | const attrs = { ...toAttributes(found), tags }; |
| 272 | return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs); |
| 273 | }), |
| 274 | |
| 275 | reconcile: Effect.fn(function* ({ id, news, session }) { |
| 276 | const identity = { |
| 277 | serviceNamespace: news.serviceNamespace, |
| 278 | resourceId: news.resourceId, |
| 279 | scalableDimension: news.scalableDimension, |
| 280 | }; |
| 281 | const internalTags = yield* createInternalTags(id); |
| 282 | const desiredTags = { ...news.tags, ...internalTags }; |
| 283 | |
| 284 | // Observe — cloud state is authoritative. |
| 285 | const existing = yield* describe(identity); |
| 286 | |
| 287 | // Ensure + sync capacity — `registerScalableTarget` is an upsert |
| 288 | // (a put keyed by the identity triple), so one call both creates |
| 289 | // a missing target and converges min/max/role/suspendedState on |
| 290 | // an existing one. Tags in the request only apply on creation; |
| 291 | // existing targets are converged by the tag sync below. |
| 292 | yield* aas.registerScalableTarget({ |
| 293 | ServiceNamespace: identity.serviceNamespace, |
| 294 | ResourceId: identity.resourceId, |
| 295 | ScalableDimension: identity.scalableDimension, |
| 296 | MinCapacity: news.minCapacity, |
| 297 | MaxCapacity: news.maxCapacity, |
| 298 | RoleARN: news.roleArn, |
| 299 | SuspendedState: news.suspendedState, |
| 300 | ...(existing === undefined ? { Tags: desiredTags } : {}), |
| 301 | }); |
| 302 | |
| 303 | // Re-observe to pick up the generated ARN and the service-linked |
| 304 | // role AWS resolved. |
| 305 | const found = yield* describe(identity); |
| 306 | const scalableTargetArn = found?.ScalableTargetARN ?? existing?.ScalableTargetARN; |
| 307 | |
| 308 | // Sync tags — diff observed cloud tags against desired. |
| 309 | if (scalableTargetArn) { |
| 310 | const currentTags = yield* observedTags(scalableTargetArn); |
| 311 | const { removed, upsert } = diffTags(currentTags, desiredTags); |
| 312 | if (upsert.length > 0) { |
| 313 | yield* aas.tagResource({ |
| 314 | ResourceARN: scalableTargetArn, |
| 315 | Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value] as const)), |
| 316 | }); |
| 317 | } |
| 318 | if (removed.length > 0) { |
| 319 | yield* aas.untagResource({ |
| 320 | ResourceARN: scalableTargetArn, |
| 321 | TagKeys: removed, |
| 322 | }); |
| 323 | } |
| 324 | } |
| 325 | |
| 326 | yield* session.note(`${identity.serviceNamespace}/${identity.resourceId}`); |
| 327 | |
| 328 | return { |
| 329 | serviceNamespace: identity.serviceNamespace, |
| 330 | resourceId: identity.resourceId, |
| 331 | scalableDimension: identity.scalableDimension, |
| 332 | scalableTargetArn: scalableTargetArn ?? "", |
| 333 | minCapacity: found?.MinCapacity ?? news.minCapacity, |
| 334 | maxCapacity: found?.MaxCapacity ?? news.maxCapacity, |
| 335 | roleArn: found?.RoleARN ?? news.roleArn ?? "", |
| 336 | suspendedState: found?.SuspendedState ?? news.suspendedState, |
| 337 | tags: desiredTags, |
| 338 | }; |
| 339 | }), |
| 340 | |
| 341 | // Deregistering also deletes any scaling policies and scheduled |
| 342 | // actions still attached to the target; already-gone targets |
| 343 | // surface as the typed `ObjectNotFoundException` and are success. |
| 344 | delete: Effect.fn(function* ({ output }) { |
| 345 | yield* aas |
| 346 | .deregisterScalableTarget({ |
| 347 | ServiceNamespace: output.serviceNamespace, |
| 348 | ResourceId: output.resourceId, |
| 349 | ScalableDimension: output.scalableDimension, |
| 350 | }) |
| 351 | .pipe(Effect.catchTag("ObjectNotFoundException", () => Effect.void)); |
| 352 | }), |
| 353 | }; |
| 354 | }), |
| 355 | ); |