The best way to control Claude Code, Codex and more from any computer or phone

main
ts 390 lines 14.6 KB
Raw
1 import * as aas from "@distilled.cloud/aws/application-auto-scaling";
2 import * as cloudwatch from "@distilled.cloud/aws/cloudwatch";
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 * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import { plainJson } from "../internal/Observe.ts";
11 import type { Providers } from "../Providers.ts";
12 import { SERVICE_NAMESPACES, retryWhileTargetPropagates } from "./internal.ts";
13
14 export interface ScalingPolicyProps {
15 /**
16 * Policy name. If omitted, a deterministic name is generated.
17 *
18 * Changing this triggers a replacement.
19 */
20 policyName?: string;
21 /**
22 * The namespace of the AWS service that provides the scalable target,
23 * e.g. `ecs`, `dynamodb`.
24 *
25 * Changing this triggers a replacement.
26 */
27 serviceNamespace: aas.ServiceNamespace;
28 /**
29 * The identifier of the resource the policy's scalable target scales,
30 * e.g. `service/{clusterName}/{serviceName}` or `table/{tableName}`.
31 *
32 * Changing this triggers a replacement.
33 */
34 resourceId: string;
35 /**
36 * The scalable dimension of the scalable target,
37 * e.g. `ecs:service:DesiredCount` or `dynamodb:table:ReadCapacityUnits`.
38 *
39 * Changing this triggers a replacement.
40 */
41 scalableDimension: aas.ScalableDimension;
42 /**
43 * Target tracking configuration — track a predefined metric
44 * (e.g. `ECSServiceAverageCPUUtilization`) or a customized CloudWatch
45 * metric specification against a target value.
46 *
47 * Exactly one of `targetTracking` or `stepScaling` must be provided.
48 */
49 targetTracking?: aas.TargetTrackingScalingPolicyConfiguration;
50 /**
51 * Step scaling configuration — apply step adjustments in response to a
52 * CloudWatch alarm you manage.
53 *
54 * Exactly one of `targetTracking` or `stepScaling` must be provided.
55 */
56 stepScaling?: aas.StepScalingPolicyConfiguration;
57 }
58
59 export interface ScalingPolicy extends Resource<
60 "AWS.ApplicationAutoScaling.ScalingPolicy",
61 ScalingPolicyProps,
62 {
63 /**
64 * Name of the scaling policy.
65 */
66 policyName: string;
67 /**
68 * ARN of the scaling policy.
69 */
70 policyArn: string;
71 /**
72 * Namespace of the AWS service that provides the scalable target.
73 */
74 serviceNamespace: aas.ServiceNamespace;
75 /**
76 * Identifier of the scaled resource.
77 */
78 resourceId: string;
79 /**
80 * Scalable dimension the policy applies to.
81 */
82 scalableDimension: aas.ScalableDimension;
83 /**
84 * Policy type (`TargetTrackingScaling` or `StepScaling`).
85 */
86 policyType: aas.PolicyType;
87 /**
88 * CloudWatch alarms created and managed by Application Auto Scaling for
89 * a target tracking policy.
90 */
91 alarms: { alarmName: string; alarmArn: string }[];
92 /**
93 * Target-tracking configuration, as observed. Lets `alchemy drift`
94 * detect out-of-band changes.
95 */
96 targetTracking?: unknown;
97 /**
98 * Step-scaling configuration, as observed. Lets `alchemy drift` detect
99 * out-of-band changes.
100 */
101 stepScaling?: unknown;
102 },
103 never,
104 Providers
105 > {}
106
107 /**
108 * An Application Auto Scaling scaling policy attached to a scalable target.
109 *
110 * Supports `TargetTrackingScaling` (Application Auto Scaling creates and
111 * manages the CloudWatch alarms) and `StepScaling` (you attach the policy to
112 * your own alarm). The policy applies to the scalable target identified by
113 * the (`serviceNamespace`, `resourceId`, `scalableDimension`) triple, which
114 * must be registered (see {@link ScalableTarget}) before the policy is
115 * created — pass the target's outputs so deployment orders correctly.
116 * ### Target Tracking
117 * **Example:** Track ECS Service CPU
118 * ```typescript
119 * const target = yield* ScalableTarget("ApiScaling", {
120 * serviceNamespace: "ecs",
121 * resourceId: Output.interpolate`service/${cluster.clusterName}/${service.serviceName}`,
122 * scalableDimension: "ecs:service:DesiredCount",
123 * minCapacity: 1,
124 * maxCapacity: 3,
125 * });
126 *
127 * yield* ScalingPolicy("ApiCpuPolicy", {
128 * serviceNamespace: target.serviceNamespace,
129 * resourceId: target.resourceId,
130 * scalableDimension: target.scalableDimension,
131 * targetTracking: {
132 * TargetValue: 60,
133 * PredefinedMetricSpecification: {
134 * PredefinedMetricType: "ECSServiceAverageCPUUtilization",
135 * },
136 * ScaleOutCooldown: 60,
137 * ScaleInCooldown: 60,
138 * },
139 * });
140 * ```
141 *
142 * **Example:** Track a Customized Metric
143 * ```typescript
144 * yield* ScalingPolicy("QueueDepthPolicy", {
145 * serviceNamespace: target.serviceNamespace,
146 * resourceId: target.resourceId,
147 * scalableDimension: target.scalableDimension,
148 * targetTracking: {
149 * TargetValue: 100,
150 * CustomizedMetricSpecification: {
151 * MetricName: "ApproximateNumberOfMessagesVisible",
152 * Namespace: "AWS/SQS",
153 * Dimensions: [{ Name: "QueueName", Value: "my-queue" }],
154 * Statistic: "Average",
155 * },
156 * },
157 * });
158 * ```
159 *
160 * ### Step Scaling
161 * **Example:** Step Adjustments
162 * ```typescript
163 * yield* ScalingPolicy("ApiStepPolicy", {
164 * serviceNamespace: target.serviceNamespace,
165 * resourceId: target.resourceId,
166 * scalableDimension: target.scalableDimension,
167 * stepScaling: {
168 * AdjustmentType: "ChangeInCapacity",
169 * Cooldown: 60,
170 * MetricAggregationType: "Average",
171 * StepAdjustments: [
172 * { MetricIntervalLowerBound: 0, ScalingAdjustment: 1 },
173 * ],
174 * },
175 * });
176 * ```
177 *
178 * @resource
179 */
180 export const ScalingPolicy = Resource<ScalingPolicy>("AWS.ApplicationAutoScaling.ScalingPolicy");
181
182 /**
183 * Raised before any AWS call when a `ScalingPolicy` declares both or neither
184 * of `targetTracking` / `stepScaling` — the two configurations are mutually
185 * exclusive and exactly one is required.
186 */
187 export class ScalingPolicyConfigurationConflict extends Data.TaggedError(
188 "ScalingPolicyConfigurationConflict",
189 )<{ message: string }> {}
190
191 const validateConfiguration = (props: {
192 targetTracking?: aas.TargetTrackingScalingPolicyConfiguration;
193 stepScaling?: aas.StepScalingPolicyConfiguration;
194 }) =>
195 (props.targetTracking === undefined) === (props.stepScaling === undefined)
196 ? Effect.fail(
197 new ScalingPolicyConfigurationConflict({
198 message: "Exactly one of targetTracking or stepScaling must be provided.",
199 }),
200 )
201 : Effect.void;
202
203 export const ScalingPolicyProvider = () =>
204 Provider.effect(
205 ScalingPolicy,
206 Effect.gen(function* () {
207 const toName = (id: string, props: { policyName?: string } = {}) =>
208 props.policyName
209 ? Effect.succeed(props.policyName)
210 : createPhysicalName({ id, maxLength: 255 });
211
212 // Narrow by the target triple only when it is complete: the API rejects
213 // a ScalableDimension without a ResourceId ("Scalable dimension cannot
214 // be provided without a resource ID"), and a row persisted by an
215 // interrupted create can carry one without the other — which would
216 // wedge `read` and therefore every destroy of the stack.
217 const describe = (props: {
218 serviceNamespace: aas.ServiceNamespace;
219 policyName: string;
220 resourceId?: string;
221 scalableDimension?: aas.ScalableDimension;
222 }) =>
223 aas
224 .describeScalingPolicies({
225 ServiceNamespace: props.serviceNamespace,
226 PolicyNames: [props.policyName],
227 ...(props.resourceId !== undefined && props.scalableDimension !== undefined
228 ? {
229 ResourceId: props.resourceId,
230 ScalableDimension: props.scalableDimension,
231 }
232 : {}),
233 })
234 .pipe(
235 Effect.map((res) =>
236 res.ScalingPolicies?.find((p) => p.PolicyName === props.policyName),
237 ),
238 );
239
240 const toAttributes = (policy: aas.ScalingPolicy): ScalingPolicy["Attributes"] => ({
241 policyName: policy.PolicyName,
242 policyArn: policy.PolicyARN,
243 serviceNamespace: policy.ServiceNamespace,
244 resourceId: policy.ResourceId,
245 scalableDimension: policy.ScalableDimension,
246 policyType: policy.PolicyType,
247 alarms: (policy.Alarms ?? []).map((alarm) => ({
248 alarmName: alarm.AlarmName,
249 alarmArn: alarm.AlarmARN,
250 })),
251 targetTracking: plainJson(policy.TargetTrackingScalingPolicyConfiguration),
252 stepScaling: plainJson(policy.StepScalingPolicyConfiguration),
253 });
254
255 return {
256 stables: ["policyName", "policyArn", "serviceNamespace", "resourceId", "scalableDimension"],
257
258 // Account/region-wide enumeration; the describe API requires a
259 // `ServiceNamespace` filter, so union the per-namespace pages.
260 list: () =>
261 Effect.forEach(
262 SERVICE_NAMESPACES,
263 (namespace) =>
264 aas.describeScalingPolicies.pages({ ServiceNamespace: namespace }).pipe(
265 Stream.runCollect,
266 Effect.map((chunk) =>
267 Array.from(chunk).flatMap((page) =>
268 (page.ScalingPolicies ?? []).map(toAttributes),
269 ),
270 ),
271 ),
272 { concurrency: 4 },
273 ).pipe(Effect.map((groups) => groups.flat())),
274
275 diff: Effect.fn(function* ({ id, news, olds }) {
276 if (!isResolved(news)) return undefined;
277 const oldName = yield* toName(id, olds ?? {});
278 const newName = yield* toName(id, news);
279 if (oldName !== newName) {
280 return { action: "replace" } as const;
281 }
282 // The target triple pins the policy to a scalable target — any
283 // change replaces the policy. Only compare sides that are known:
284 // a half-created state row may have lost Output-valued props.
285 for (const key of ["serviceNamespace", "resourceId", "scalableDimension"] as const) {
286 const oldValue = olds?.[key];
287 if (oldValue !== undefined && isResolved(oldValue) && oldValue !== news[key]) {
288 return { action: "replace" } as const;
289 }
290 }
291 }),
292
293 read: Effect.fn(function* ({ id, olds, output }) {
294 const serviceNamespace = output?.serviceNamespace ?? olds?.serviceNamespace;
295 if (serviceNamespace === undefined) return undefined;
296 const policyName = output?.policyName ?? (yield* toName(id, olds ?? {}));
297 const policy = yield* describe({
298 serviceNamespace,
299 policyName,
300 resourceId: output?.resourceId ?? olds?.resourceId,
301 scalableDimension: output?.scalableDimension ?? olds?.scalableDimension,
302 });
303 return policy ? toAttributes(policy) : undefined;
304 }),
305
306 reconcile: Effect.fn(function* ({ id, news, session }) {
307 yield* validateConfiguration(news);
308 const policyName = yield* toName(id, news);
309 const policyType: aas.PolicyType = news.targetTracking
310 ? "TargetTrackingScaling"
311 : "StepScaling";
312
313 // Ensure + sync — `putScalingPolicy` is the single
314 // create-or-update API, keyed by (name, target triple); it
315 // overwrites the policy configuration on every call, so one
316 // unconditional put converges any starting state. A put issued
317 // immediately after the target registers can race its
318 // propagation — retry the typed ObjectNotFoundException briefly.
319 yield* retryWhileTargetPropagates(
320 aas.putScalingPolicy({
321 PolicyName: policyName,
322 ServiceNamespace: news.serviceNamespace,
323 ResourceId: news.resourceId,
324 ScalableDimension: news.scalableDimension,
325 PolicyType: policyType,
326 TargetTrackingScalingPolicyConfiguration: news.targetTracking,
327 StepScalingPolicyConfiguration: news.stepScaling,
328 }),
329 );
330
331 // Observe final state so attributes carry the generated ARN and
332 // the CloudWatch alarms Application Auto Scaling manages.
333 const policy = yield* describe({
334 serviceNamespace: news.serviceNamespace,
335 policyName,
336 resourceId: news.resourceId,
337 scalableDimension: news.scalableDimension,
338 });
339 if (policy === undefined) {
340 return yield* aas.ObjectNotFoundException.make({
341 message: `Scaling policy '${policyName}' was not readable after PutScalingPolicy`,
342 });
343 }
344
345 yield* session.note(policy.PolicyARN);
346 return toAttributes(policy);
347 }),
348
349 // Deleting the parent scalable target implicitly deletes its
350 // policies, so a policy that is already gone (typed
351 // `ObjectNotFoundException`) is success.
352 delete: Effect.fn(function* ({ olds, output }) {
353 // Observe before deleting: resolve the live policy by name (a row
354 // persisted by an interrupted create can lack the target triple)
355 // and delete with ITS triple; a policy that no longer exists is
356 // already gone.
357 const policy = yield* describe({
358 serviceNamespace: output.serviceNamespace,
359 policyName: output.policyName,
360 resourceId: output.resourceId ?? olds?.resourceId,
361 scalableDimension: output.scalableDimension ?? olds?.scalableDimension,
362 });
363 if (policy?.ResourceId && policy.ScalableDimension) {
364 yield* aas
365 .deleteScalingPolicy({
366 PolicyName: output.policyName,
367 ServiceNamespace: output.serviceNamespace,
368 ResourceId: policy.ResourceId,
369 ScalableDimension: policy.ScalableDimension,
370 })
371 .pipe(Effect.catchTag("ObjectNotFoundException", () => Effect.void));
372 }
373 // Reap the managed CloudWatch alarms of a target tracking policy.
374 // Application Auto Scaling deletes them asynchronously (and not at
375 // all when the policy went away via target deregistration), so an
376 // explicit delete keeps teardown deterministic. DeleteAlarms
377 // ignores names that no longer exist.
378 const alarms = [
379 ...(output.alarms ?? []).map((alarm) => alarm.alarmName),
380 ...(policy?.Alarms ?? []).map((alarm) => alarm.AlarmName),
381 ].filter((name, i, all) => all.indexOf(name) === i);
382 if (alarms.length > 0) {
383 yield* cloudwatch
384 .deleteAlarms({ AlarmNames: alarms })
385 .pipe(Effect.catchTag("ResourceNotFound", () => Effect.void));
386 }
387 }),
388 };
389 }),
390 );