@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 286 lines 12 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { AutoScalingGroup, LaunchTemplate, ScalingPolicy } from "@alchemy.run/aws/AutoScaling";
3 import { amazonLinux2023, Subnet, Vpc } from "@alchemy.run/aws/EC2";
4 import { expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as autoscaling from "@distilled.cloud/aws/auto-scaling";
7 import * as ec2 from "@distilled.cloud/aws/ec2";
8 import * as Provider from "alchemy/Provider";
9 import { isResourceState, State, type ResourceState } from "alchemy/State";
10 import * as Effect from "effect/Effect";
11 import * as Schedule from "effect/Schedule";
12 import { getAutoScalingTestSubnetId, getTestAmiId } from "./TestNetwork.ts";
13
14 const { test } = Test.make({ providers: AWS.providers() });
15
16 // Out-of-band proof a scaling policy is deleted: describePolicies by name
17 // returns an empty list once the policy (or its group) is gone.
18 const assertPolicyGone = (policyName: string) =>
19 autoscaling.describePolicies({ PolicyNames: [policyName] }).pipe(
20 Effect.map((r) => (r.ScalingPolicies ?? []).length),
21 Effect.repeat({
22 until: (count) => count === 0,
23 schedule: Schedule.spaced("2 seconds"),
24 times: 8,
25 }),
26 Effect.map((count) => expect(count).toBe(0)),
27 );
28
29 // Out-of-band proof an Auto Scaling Group is deleted after the trailing
30 // stack.destroy(): the name-filtered describe returns an empty list.
31 const assertGroupGone = (name: string) =>
32 autoscaling.describeAutoScalingGroups({ AutoScalingGroupNames: [name] } as any).pipe(
33 Effect.map((r) => (r.AutoScalingGroups ?? []).length),
34 Effect.repeat({
35 until: (count) => count === 0,
36 schedule: Schedule.spaced("3 seconds"),
37 times: 10,
38 }),
39 Effect.map((count) => expect(count).toBe(0)),
40 );
41
42 // `list()` enumerates every scaling policy in the account/region via the
43 // paginated `autoscaling.describePolicies` op (no AutoScalingGroupName filter,
44 // so it spans every group). Deploy a real ASG (sized to zero so no EC2
45 // instances launch) with a target-tracking policy, resolve the provider from
46 // context via the typed `findProvider`, call `list()`, and assert the deployed
47 // policy appears in the exhaustively paginated result.
48 test.provider(
49 "list enumerates the deployed scaling policy",
50 (stack) =>
51 Effect.gen(function* () {
52 yield* stack.destroy();
53
54 // Launch templates do not validate the AMI at creation time; fall back to
55 // a syntactically valid id if the lookup returns nothing.
56 const imageId = amazonLinux2023();
57
58 const policy = yield* stack.deploy(
59 Effect.gen(function* () {
60 const vpc = yield* Vpc("TestVpc", { cidrBlock: "10.0.0.0/16" });
61 const subnet = yield* Subnet("TestSubnet", {
62 vpcId: vpc.vpcId,
63 cidrBlock: "10.0.1.0/24",
64 });
65 const template = yield* LaunchTemplate("ListPolicyTemplate", {
66 launchTemplateName: "alchemy-test-policy-lt-list",
67 imageId,
68 instanceType: "t3.micro",
69 });
70 const group = yield* AutoScalingGroup("ListPolicyGroup", {
71 autoScalingGroupName: "alchemy-test-policy-asg-list",
72 launchTemplate: template,
73 subnetIds: [subnet.subnetId],
74 minSize: 0,
75 maxSize: 0,
76 desiredCapacity: 0,
77 });
78 return yield* ScalingPolicy("ListScalingPolicy", {
79 policyName: "alchemy-test-scaling-policy-list",
80 autoScalingGroup: group,
81 predefinedMetricType: "ASGAverageCPUUtilization",
82 targetValue: 50,
83 });
84 }),
85 );
86
87 const provider = yield* Provider.findProvider(ScalingPolicy);
88 const all = yield* provider.list();
89
90 expect(all.some((p) => p.policyName === policy.policyName)).toBe(true);
91
92 yield* stack.destroy();
93 yield* assertPolicyGone(policy.policyName);
94 yield* assertGroupGone("alchemy-test-policy-asg-list");
95 }),
96 {
97 tags: ["provider:aws", "provider:aws:autoscaling", "provider:aws:ec2", "live"],
98 timeout: 240_000,
99 },
100 );
101
102 // Regression test for https://github.com/alchemy-run/alchemy/issues/736.
103 //
104 // An interrupted first deploy persists the scaling policy as
105 // `status: "creating"` with no attributes — and the Output-valued
106 // `autoScalingGroup` prop (a whole AutoScalingGroup resource object) does not
107 // survive the state round-trip: it deserializes as `undefined`. Plan's
108 // recovery branches then hand those junk props back to the provider as
109 // `olds`:
110 //
111 // - `read` must tolerate `olds.autoScalingGroup === undefined` and fall back
112 // to an account-wide `describePolicies` lookup by (unique physical) policy
113 // name, so a half-created policy that DOES exist is recovered in place
114 // (same policyArn, no duplicate).
115 // - `diff` must NOT treat "old ASG name unknown vs new ASG name known" as an
116 // ASG change: pre-fix it forced `action: "replace"`, which mints a new
117 // instanceId and therefore a NEW generated policy name instead of resuming
118 // the same create.
119 //
120 // The launch template is created out-of-band via distilled `ec2` (not the
121 // `AWS.AutoScaling.LaunchTemplate` resource) to isolate this test from that
122 // provider's unrelated untyped-NotFound read bug. The fleet is placed into a
123 // subnet of the account's default VPC (resolved out-of-band) rather than a
124 // throwaway `Vpc` resource: a failed run of this test loses its in-memory
125 // scratch state, and orphaned VPCs quickly exhaust the 5-per-region quota.
126 const recoveryLtName = "alchemy-test-scaling-policy-recovery-lt";
127 const recoveryAsgName = "alchemy-test-scaling-policy-recovery-asg";
128 const cleanupRecoveryLt = ec2
129 .deleteLaunchTemplate({ LaunchTemplateName: recoveryLtName } as any)
130 .pipe(Effect.catch(() => Effect.void));
131 // Leftover-cleanup for interrupted/failed prior runs (the ASG name is
132 // deterministic and account-unique; deleting it also deletes its policies).
133 const cleanupRecoveryAsg = autoscaling
134 .deleteAutoScalingGroup({
135 AutoScalingGroupName: recoveryAsgName,
136 ForceDelete: true,
137 } as any)
138 .pipe(Effect.catch(() => Effect.void));
139
140 test.provider(
141 "recovers a half-created scaling policy whose creating-state lost the Output-valued autoScalingGroup (#736)",
142 (stack) =>
143 Effect.gen(function* () {
144 yield* cleanupRecoveryAsg;
145 yield* cleanupRecoveryLt;
146 yield* stack.destroy();
147
148 // The launch template is created out-of-band with the raw SDK, so the
149 // AMI id must be a plain string — `amazonLinux2023()` returns an
150 // Output, which only resolves inside `stack.deploy`.
151 const imageId = yield* getTestAmiId;
152 yield* ec2.createLaunchTemplate({
153 LaunchTemplateName: recoveryLtName,
154 LaunchTemplateData: { ImageId: imageId, InstanceType: "t3.micro" },
155 } as any);
156
157 const subnetId = yield* getAutoScalingTestSubnetId;
158
159 const deployPolicy = () =>
160 stack.deploy(
161 Effect.gen(function* () {
162 const group = yield* AutoScalingGroup("RecoveryGroup", {
163 autoScalingGroupName: recoveryAsgName,
164 launchTemplate: { launchTemplateName: recoveryLtName },
165 subnetIds: [subnetId],
166 minSize: 0,
167 maxSize: 0,
168 desiredCapacity: 0,
169 });
170 return yield* ScalingPolicy("RecoveryScalingPolicy", {
171 // Whole-resource spelling — the #736 shape (an unresolved
172 // Output persisted at `creating` does not survive the state
173 // round-trip) AND coverage for the resolved-attributes
174 // narrowing: the engine resolves `group` to its bare
175 // Attributes record (no resource `Type` marker), which the
176 // provider must narrow by shape (`autoScalingGroupName`
177 // string field) to extract the group name.
178 // policyName intentionally omitted: the engine-generated
179 // physical name embeds the instanceId, so a wrongful
180 // `replace` (pre-fix diff) is observable as a changed name.
181 autoScalingGroup: group,
182 predefinedMetricType: "ASGAverageCPUUtilization",
183 targetValue: 50,
184 // Duration.Input prop — whole seconds on the wire.
185 estimatedInstanceWarmup: "90 seconds",
186 });
187 }),
188 );
189
190 const created = yield* deployPolicy();
191
192 // Duration.Input round-trips to the wire as whole seconds.
193 const liveCreated = yield* autoscaling.describePolicies({
194 PolicyNames: [created.policyName],
195 });
196 expect(liveCreated.ScalingPolicies?.[0]?.EstimatedInstanceWarmup).toEqual(90);
197
198 // Rewrite the policy's persisted row into the wedged shape an
199 // interrupted deploy leaves behind: `creating`, no attributes, and the
200 // Output-valued `autoScalingGroup` lost in the round-trip.
201 const wedgeRow = Effect.gen(function* () {
202 const state = yield* yield* State;
203 const stage = stack.stage;
204 const fqns = yield* state.list({ stack: stack.name, stage });
205 const rows = yield* Effect.forEach(fqns, (fqn) =>
206 state.get({ stack: stack.name, stage, fqn }).pipe(Effect.map((row) => ({ fqn, row }))),
207 );
208 const wedged = rows.find(
209 (r): r is { fqn: string; row: ResourceState } =>
210 isResourceState(r.row) && r.row.resourceType === "AWS.AutoScaling.ScalingPolicy",
211 );
212 if (!wedged) {
213 return yield* Effect.die(
214 new Error("no AWS.AutoScaling.ScalingPolicy state row found after deploy"),
215 );
216 }
217 yield* state.set({
218 stack: stack.name,
219 stage,
220 fqn: wedged.fqn,
221 value: {
222 ...wedged.row,
223 status: "creating",
224 attr: undefined,
225 props: {
226 ...wedged.row.props,
227 autoScalingGroup: undefined,
228 },
229 },
230 });
231 });
232
233 // Variant A — the half-created policy still exists in the cloud.
234 // `read` gets junk olds (no ASG name) and must find the policy via the
235 // account-wide name-only lookup: SAME policyArn, no duplicate.
236 yield* wedgeRow;
237 const recoveredInPlace = yield* deployPolicy();
238 expect(recoveredInPlace.policyArn).toEqual(created.policyArn);
239 expect(recoveredInPlace.policyName).toEqual(created.policyName);
240 expect(recoveredInPlace.autoScalingGroupName).toEqual(created.autoScalingGroupName);
241
242 // Variant B — wedge again AND delete the policy out-of-band so the
243 // recovery `read` misses and `diff` runs with the junk olds. Pre-fix,
244 // diff saw `undefined !== <asg name>` and forced a replacement (new
245 // instanceId => new generated policy name). Post-fix it falls through
246 // to update, resumes the same create, and recreates under the SAME
247 // name.
248 yield* wedgeRow;
249 yield* autoscaling.deletePolicy({
250 AutoScalingGroupName: created.autoScalingGroupName,
251 PolicyName: created.policyName,
252 } as any);
253 const remaining = yield* autoscaling
254 .describePolicies({ PolicyNames: [created.policyName] })
255 .pipe(
256 Effect.map((result) => (result.ScalingPolicies ?? []).length),
257 Effect.repeat({
258 until: (count) => count === 0,
259 schedule: Schedule.spaced("2 seconds"),
260 times: 8,
261 }),
262 );
263 expect(remaining).toBe(0);
264
265 const recreated = yield* deployPolicy();
266 expect(recreated.policyName).toEqual(created.policyName);
267 expect(recreated.autoScalingGroupName).toEqual(created.autoScalingGroupName);
268
269 // Out-of-band proof the policy is live again.
270 const after = yield* autoscaling.describePolicies({
271 PolicyNames: [created.policyName],
272 });
273 expect((after.ScalingPolicies ?? []).some((p) => p.PolicyName === created.policyName)).toBe(
274 true,
275 );
276
277 yield* stack.destroy();
278 yield* assertPolicyGone(created.policyName);
279 yield* assertGroupGone(recoveryAsgName);
280 yield* cleanupRecoveryLt;
281 }).pipe(Effect.ensuring(cleanupRecoveryLt)),
282 {
283 tags: ["provider:aws", "provider:aws:autoscaling", "provider:aws:ec2", "live"],
284 timeout: 240_000,
285 },
286 );