@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
ts 344 lines 13.7 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { ScalableTarget, ScalingPolicy } from "@alchemy.run/aws/ApplicationAutoScaling";
3 import { Table } from "@alchemy.run/aws/DynamoDB";
4 import { expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as aas from "@distilled.cloud/aws/application-auto-scaling";
7 import * as Output from "alchemy/Output";
8 import * as Provider from "alchemy/Provider";
9 import { Stack } from "alchemy/Stack";
10 import { State, type ResourceState } from "alchemy/State";
11 import * as Effect from "effect/Effect";
12 import * as Schedule from "effect/Schedule";
13 import { driftActions, repairDrift, waitForDrift } from "../drift.ts";
14
15 const { test } = Test.make({ providers: AWS.providers() });
16
17 const describePolicy = (policyName: string) =>
18 aas
19 .describeScalingPolicies({
20 ServiceNamespace: "dynamodb",
21 PolicyNames: [policyName],
22 })
23 .pipe(Effect.map((res) => res.ScalingPolicies?.find((p) => p.PolicyName === policyName)));
24
25 const waitUntilPolicyGone = (policyName: string) =>
26 describePolicy(policyName).pipe(
27 Effect.repeat({
28 schedule: Schedule.spaced("2 seconds"),
29 until: (policy) => policy === undefined,
30 times: 10,
31 }),
32 );
33
34 // Target-tracking lifecycle against a provisioned DynamoDB table: put a
35 // DynamoDBReadCapacityUtilization tracking policy on a fresh scalable target
36 // (exercising the target-propagation retry), verify the managed CloudWatch
37 // alarms out-of-band, update the target value in place (same policy ARN),
38 // then destroy and verify deletion.
39 test.provider(
40 "target tracking policy lifecycle (dynamodb)",
41 (stack) =>
42 Effect.gen(function* () {
43 yield* stack.destroy();
44
45 const deploy = (targetValue: number) =>
46 stack.deploy(
47 Effect.gen(function* () {
48 const table = yield* Table("AasPolicyTable", {
49 partitionKey: "id",
50 attributes: { id: "S" },
51 billingMode: "PROVISIONED",
52 provisionedThroughput: {
53 ReadCapacityUnits: 1,
54 WriteCapacityUnits: 1,
55 },
56 });
57 const target = yield* ScalableTarget("AasPolicyTarget", {
58 serviceNamespace: "dynamodb",
59 resourceId: Output.interpolate`table/${table.tableName}`,
60 scalableDimension: "dynamodb:table:ReadCapacityUnits",
61 minCapacity: 1,
62 maxCapacity: 5,
63 });
64 const policy = yield* ScalingPolicy("AasTrackingPolicy", {
65 serviceNamespace: target.serviceNamespace,
66 resourceId: target.resourceId,
67 scalableDimension: target.scalableDimension,
68 targetTracking: {
69 TargetValue: targetValue,
70 PredefinedMetricSpecification: {
71 PredefinedMetricType: "DynamoDBReadCapacityUtilization",
72 },
73 ScaleOutCooldown: 60,
74 ScaleInCooldown: 60,
75 },
76 });
77 return {
78 resourceId: target.resourceId.as<string>(),
79 policyName: policy.policyName.as<string>(),
80 policyArn: policy.policyArn.as<string>(),
81 policyType: policy.policyType.as<string>(),
82 };
83 }),
84 );
85
86 const created = yield* deploy(70);
87 expect(created.policyType).toBe("TargetTrackingScaling");
88 expect(created.policyArn).toContain("scalingPolicy");
89
90 // Out-of-band: the policy tracks the requested value and Application
91 // Auto Scaling created its managed CloudWatch alarms.
92 const observed = yield* describePolicy(created.policyName);
93 expect(observed?.PolicyType).toBe("TargetTrackingScaling");
94 expect(observed?.TargetTrackingScalingPolicyConfiguration?.TargetValue).toBe(70);
95 expect((observed?.Alarms ?? []).length).toBeGreaterThan(0);
96
97 // #2688: `read` must observe the tracking configuration and the
98 // target's tags, or out-of-band changes read as `unchanged`.
99 const allUnchanged = (actions: Record<string, string | undefined>) =>
100 Object.values(actions).every((action) => action === "unchanged");
101 expect(allUnchanged(yield* driftActions(stack))).toBe(true);
102 yield* aas.putScalingPolicy({
103 PolicyName: created.policyName,
104 ServiceNamespace: "dynamodb",
105 ResourceId: created.resourceId,
106 ScalableDimension: "dynamodb:table:ReadCapacityUnits",
107 PolicyType: "TargetTrackingScaling",
108 TargetTrackingScalingPolicyConfiguration: {
109 ...observed!.TargetTrackingScalingPolicyConfiguration!,
110 TargetValue: 40,
111 },
112 });
113 const target = (yield* aas.describeScalableTargets({
114 ServiceNamespace: "dynamodb",
115 ResourceIds: [created.resourceId],
116 })).ScalableTargets?.[0];
117 yield* aas.tagResource({
118 ResourceARN: target!.ScalableTargetARN!,
119 Tags: { team: "out-of-band" },
120 });
121 expect(
122 (yield* waitForDrift(stack, "AasTrackingPolicy", "drifted"))?.attr?.targetTracking
123 ?.TargetValue,
124 ).toBe(40);
125 expect((yield* waitForDrift(stack, "AasPolicyTarget", "drifted"))?.attr?.tags?.team).toBe(
126 "out-of-band",
127 );
128 yield* repairDrift(stack);
129 expect(allUnchanged(yield* driftActions(stack))).toBe(true);
130 expect(
131 (yield* describePolicy(created.policyName))?.TargetTrackingScalingPolicyConfiguration
132 ?.TargetValue,
133 ).toBe(70);
134
135 // Update in place — same name and ARN, new target value.
136 const updated = yield* deploy(60);
137 expect(updated.policyArn).toEqual(created.policyArn);
138 const observedAfterUpdate = yield* describePolicy(created.policyName);
139 expect(observedAfterUpdate?.TargetTrackingScalingPolicyConfiguration?.TargetValue).toBe(60);
140
141 yield* stack.destroy();
142 const gone = yield* waitUntilPolicyGone(created.policyName);
143 expect(gone).toBeUndefined();
144
145 // The target is deregistered too.
146 const targets = yield* aas.describeScalableTargets({
147 ServiceNamespace: "dynamodb",
148 ResourceIds: [created.resourceId],
149 ScalableDimension: "dynamodb:table:ReadCapacityUnits",
150 });
151 expect(targets.ScalableTargets ?? []).toHaveLength(0);
152 }),
153 {
154 tags: ["provider:aws", "provider:aws:applicationautoscaling", "provider:aws:dynamodb", "live"],
155 timeout: 240_000,
156 },
157 );
158
159 // Deregistering a scalable target implicitly deletes its policies. Simulate
160 // an out-of-band deregistration and assert destroy still converges: the
161 // policy delete observes the typed ObjectNotFoundException and succeeds.
162 test.provider(
163 "destroy tolerates a target deregistered out-of-band (implicit policy deletion)",
164 (stack) =>
165 Effect.gen(function* () {
166 yield* stack.destroy();
167
168 const created = yield* stack.deploy(
169 Effect.gen(function* () {
170 const table = yield* Table("AasDeregTable", {
171 partitionKey: "id",
172 attributes: { id: "S" },
173 billingMode: "PROVISIONED",
174 provisionedThroughput: {
175 ReadCapacityUnits: 1,
176 WriteCapacityUnits: 1,
177 },
178 });
179 const target = yield* ScalableTarget("AasDeregTarget", {
180 serviceNamespace: "dynamodb",
181 resourceId: Output.interpolate`table/${table.tableName}`,
182 scalableDimension: "dynamodb:table:ReadCapacityUnits",
183 minCapacity: 1,
184 maxCapacity: 3,
185 });
186 // NOTE: DynamoDB targets only support TargetTrackingScaling —
187 // putScalingPolicy with StepScaling is rejected (step-scaling
188 // coverage lives in EcsServiceScaling.test.ts).
189 const policy = yield* ScalingPolicy("AasDeregPolicy", {
190 serviceNamespace: target.serviceNamespace,
191 resourceId: target.resourceId,
192 scalableDimension: target.scalableDimension,
193 targetTracking: {
194 TargetValue: 70,
195 PredefinedMetricSpecification: {
196 PredefinedMetricType: "DynamoDBReadCapacityUtilization",
197 },
198 },
199 });
200 return {
201 resourceId: target.resourceId.as<string>(),
202 policyName: policy.policyName.as<string>(),
203 policyType: policy.policyType.as<string>(),
204 };
205 }),
206 );
207 expect(created.policyType).toBe("TargetTrackingScaling");
208
209 // Deregister the target out-of-band — AWS implicitly deletes the
210 // attached scaling policy.
211 yield* aas.deregisterScalableTarget({
212 ServiceNamespace: "dynamodb",
213 ResourceId: created.resourceId,
214 ScalableDimension: "dynamodb:table:ReadCapacityUnits",
215 });
216 const gone = yield* waitUntilPolicyGone(created.policyName);
217 expect(gone).toBeUndefined();
218
219 // Destroy must still converge: deleteScalingPolicy and
220 // deregisterScalableTarget both hit ObjectNotFoundException and treat
221 // it as success.
222 yield* stack.destroy();
223 }),
224 {
225 tags: ["provider:aws", "provider:aws:applicationautoscaling", "provider:aws:dynamodb", "live"],
226 timeout: 240_000,
227 },
228 );
229
230 const getState = Effect.fn(function* (fqn: string) {
231 const state = yield* yield* State;
232 const stk = yield* Stack;
233 return (yield* state.get({
234 stack: stk.name,
235 stage: stk.stage,
236 fqn,
237 })) as ResourceState | undefined;
238 });
239
240 const setState = Effect.fn(function* (fqn: string, value: ResourceState) {
241 const state = yield* yield* State;
242 const stk = yield* Stack;
243 yield* state.set({ stack: stk.name, stage: stk.stage, fqn, value });
244 });
245
246 // An apply interrupted mid-create (Ctrl-C, crash, CI timeout) can persist a
247 // policy row WITHOUT its target triple — `scalableDimension` set,
248 // `resourceId` missing. Application Auto Scaling treats ResourceId and
249 // ScalableDimension as a pair: one without the other is
250 // "ValidationException: Scalable dimension cannot be provided without a
251 // resource ID", which used to fail `read` (so every plan) and `delete` (so
252 // every destroy of the stack — and every resource depending on the policy
253 // was skipped with it). The provider must converge from that row: a
254 // re-deploy observes the live policy by name and restores the triple, and a
255 // destroy deletes it with the triple the live policy reports.
256 test.provider(
257 "read and destroy converge from a row persisted by an interrupted create",
258 (stack) =>
259 Effect.gen(function* () {
260 yield* stack.destroy();
261
262 const program = Effect.gen(function* () {
263 const table = yield* Table("AasPartialTable", {
264 partitionKey: "id",
265 attributes: { id: "S" },
266 billingMode: "PROVISIONED",
267 provisionedThroughput: {
268 ReadCapacityUnits: 1,
269 WriteCapacityUnits: 1,
270 },
271 });
272 const target = yield* ScalableTarget("AasPartialTarget", {
273 serviceNamespace: "dynamodb",
274 resourceId: Output.interpolate`table/${table.tableName}`,
275 scalableDimension: "dynamodb:table:ReadCapacityUnits",
276 minCapacity: 1,
277 maxCapacity: 3,
278 });
279 const policy = yield* ScalingPolicy("AasPartialPolicy", {
280 serviceNamespace: target.serviceNamespace,
281 resourceId: target.resourceId,
282 scalableDimension: target.scalableDimension,
283 targetTracking: {
284 TargetValue: 70,
285 PredefinedMetricSpecification: {
286 PredefinedMetricType: "DynamoDBReadCapacityUtilization",
287 },
288 },
289 });
290 return {
291 resourceId: target.resourceId.as<string>(),
292 policyName: policy.policyName.as<string>(),
293 policyResourceId: policy.resourceId.as<string>(),
294 };
295 });
296
297 const created = yield* stack.deploy(program);
298 expect(created.policyResourceId).toBe(created.resourceId);
299
300 // Simulate the interrupted create: the persisted attrs lose their
301 // resourceId but keep the scalable dimension.
302 const row = yield* getState("AasPartialPolicy");
303 expect(row?.status).toBe("created");
304 if (row?.status !== "created") return;
305 const attr = row.attr as { resourceId?: string; [key: string]: unknown };
306 expect(attr.resourceId).toBe(created.resourceId);
307 const { resourceId: _dropped, ...partialAttr } = attr;
308 const partialRow: ResourceState = { ...row, attr: partialAttr };
309 const readResourceId = Effect.map(
310 getState("AasPartialPolicy"),
311 (r) => (r?.status === "created" ? r.attr : undefined)?.resourceId,
312 );
313 yield* setState("AasPartialPolicy", partialRow);
314 expect(yield* readResourceId).toBe(undefined);
315
316 // `read` (refresh/sync/adopt) must observe the live policy by name
317 // and report the full triple rather than fail on the partial row —
318 // including when the Output-valued `resourceId` prop was lost too.
319 const provider = yield* Provider.findProvider(ScalingPolicy);
320 const { resourceId: _droppedProp, ...partialProps } = partialRow.props as {
321 resourceId?: string;
322 [key: string]: unknown;
323 };
324 const observed = yield* provider.read!({
325 id: "AasPartialPolicy",
326 fqn: partialRow.fqn,
327 instanceId: partialRow.instanceId,
328 olds: partialProps as unknown as ScalingPolicy["Props"],
329 output: partialAttr as ScalingPolicy["Attributes"],
330 });
331 expect(observed?.resourceId).toBe(created.resourceId);
332 expect(observed?.scalableDimension).toBe("dynamodb:table:ReadCapacityUnits");
333
334 // And `delete` (every destroy) must converge from the partial row
335 // instead of wedging the stack.
336 yield* stack.destroy();
337 const gone = yield* waitUntilPolicyGone(created.policyName);
338 expect(gone).toBeUndefined();
339 }),
340 {
341 tags: ["provider:aws", "provider:aws:applicationautoscaling", "provider:aws:dynamodb", "live"],
342 timeout: 240_000,
343 },
344 );