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

main
ts 236 lines 8.64 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { LifecyclePolicy, type LifecyclePolicyDetails } from "@alchemy.run/aws/DLM";
3 import * as IAM from "@alchemy.run/aws/IAM";
4 import { expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as dlm from "@distilled.cloud/aws/dlm";
7 import * as iam from "@distilled.cloud/aws/iam";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11
12 const { test } = Test.make({ providers: AWS.providers() });
13
14 class PolicyStillExists extends Data.TaggedError("PolicyStillExists")<{
15 readonly policyId: string;
16 }> {}
17
18 const assertPolicyDeleted = (policyId: string) =>
19 dlm.getLifecyclePolicy({ PolicyId: policyId }).pipe(
20 Effect.flatMap(() => Effect.fail(new PolicyStillExists({ policyId }))),
21 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
22 Effect.retry({
23 while: (e) => e._tag === "PolicyStillExists",
24 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(10)]),
25 }),
26 );
27
28 class RoleStillExists extends Data.TaggedError("RoleStillExists")<{
29 readonly roleName: string;
30 }> {}
31
32 const assertRoleDeleted = (roleName: string) =>
33 iam.getRole({ RoleName: roleName }).pipe(
34 Effect.flatMap(() => Effect.fail(new RoleStillExists({ roleName }))),
35 Effect.catchTag("NoSuchEntityException", () => Effect.void),
36 Effect.retry({
37 while: (e) => e._tag === "RoleStillExists",
38 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(10)]),
39 }),
40 );
41
42 const tagRecord = (
43 tags: { [key: string]: string | undefined } | undefined,
44 ): Record<string, string | undefined> => tags ?? {};
45
46 const snapshotDetails = (retainCount: number) =>
47 ({
48 resourceTypes: ["VOLUME"],
49 targetTags: { AlchemyDlmTest: "true" },
50 schedules: [
51 {
52 name: "Daily",
53 copyTags: false,
54 createRule: {
55 interval: 24,
56 intervalUnit: "HOURS",
57 times: ["03:00"],
58 },
59 retainRule: { count: retainCount },
60 },
61 ],
62 }) satisfies LifecyclePolicyDetails;
63
64 test.provider(
65 "create, update, no-op, tag removal, destroy with managed role",
66 (stack) =>
67 Effect.gen(function* () {
68 const policy = yield* stack.deploy(
69 Effect.gen(function* () {
70 return yield* LifecyclePolicy("Snapshots", {
71 policyDetails: snapshotDetails(7),
72 tags: { Environment: "test" },
73 });
74 }),
75 );
76
77 expect(policy.policyId).toMatch(/^policy-/);
78 expect(policy.policyArn).toContain(":policy/");
79 expect(policy.state).toBe("ENABLED");
80 expect(policy.executionRoleArn).toContain(":role/");
81 expect(policy.roleName).toBeDefined();
82
83 // out-of-band verification via distilled
84 const created = yield* dlm
85 .getLifecyclePolicy({ PolicyId: policy.policyId })
86 .pipe(Effect.map((r) => r.Policy!));
87 expect(created.State).toBe("ENABLED");
88 expect(created.ExecutionRoleArn).toBe(policy.executionRoleArn);
89 expect(created.PolicyDetails?.PolicyType).toBe("EBS_SNAPSHOT_MANAGEMENT");
90 expect(created.PolicyDetails?.ResourceTypes).toEqual(["VOLUME"]);
91 expect(created.PolicyDetails?.TargetTags).toEqual([{ Key: "AlchemyDlmTest", Value: "true" }]);
92 expect(created.PolicyDetails?.Schedules?.[0]?.RetainRule?.Count).toBe(7);
93 const createdTags = tagRecord(created.Tags);
94 expect(createdTags.Environment).toBe("test");
95 expect(createdTags["alchemy::id"]).toBe("Snapshots");
96
97 // update retention + state + add a tag — same physical policy
98 const updated = yield* stack.deploy(
99 Effect.gen(function* () {
100 return yield* LifecyclePolicy("Snapshots", {
101 state: "DISABLED",
102 policyDetails: snapshotDetails(14),
103 tags: { Environment: "test", Extra: "1" },
104 });
105 }),
106 );
107 expect(updated.policyId).toBe(policy.policyId);
108 expect(updated.state).toBe("DISABLED");
109
110 const afterUpdate = yield* dlm
111 .getLifecyclePolicy({ PolicyId: policy.policyId })
112 .pipe(Effect.map((r) => r.Policy!));
113 expect(afterUpdate.State).toBe("DISABLED");
114 expect(afterUpdate.PolicyDetails?.Schedules?.[0]?.RetainRule?.Count).toBe(14);
115 expect(tagRecord(afterUpdate.Tags).Extra).toBe("1");
116 const modifiedAfterUpdate = afterUpdate.DateModified?.toISOString();
117
118 // no-op deploy converges without issuing an update
119 yield* stack.deploy(
120 Effect.gen(function* () {
121 return yield* LifecyclePolicy("Snapshots", {
122 state: "DISABLED",
123 policyDetails: snapshotDetails(14),
124 tags: { Environment: "test", Extra: "1" },
125 });
126 }),
127 );
128 const afterNoop = yield* dlm
129 .getLifecyclePolicy({ PolicyId: policy.policyId })
130 .pipe(Effect.map((r) => r.Policy!));
131 expect(afterNoop.DateModified?.toISOString()).toBe(modifiedAfterUpdate);
132
133 // remove a tag
134 yield* stack.deploy(
135 Effect.gen(function* () {
136 return yield* LifecyclePolicy("Snapshots", {
137 state: "DISABLED",
138 policyDetails: snapshotDetails(14),
139 tags: { Environment: "test" },
140 });
141 }),
142 );
143 const afterTagRemoval = yield* dlm
144 .getLifecyclePolicy({ PolicyId: policy.policyId })
145 .pipe(Effect.map((r) => tagRecord(r.Policy?.Tags)));
146 expect(afterTagRemoval.Extra).toBeUndefined();
147 expect(afterTagRemoval.Environment).toBe("test");
148 expect(afterTagRemoval["alchemy::id"]).toBe("Snapshots");
149
150 yield* stack.destroy();
151 yield* assertPolicyDeleted(policy.policyId);
152 yield* assertRoleDeleted(policy.roleName!);
153 }),
154 {
155 tags: ["provider:aws", "provider:aws:dlm", "provider:aws:iam", "live"],
156 timeout: 120_000,
157 },
158 );
159
160 test.provider(
161 "explicit execution role; policy type change triggers replacement",
162 (stack) =>
163 Effect.gen(function* () {
164 const deployWith = (policyDetails: LifecyclePolicyDetails) =>
165 stack.deploy(
166 Effect.gen(function* () {
167 const role = yield* IAM.Role("DlmRole", {
168 assumeRolePolicyDocument: {
169 Version: "2012-10-17",
170 Statement: [
171 {
172 Effect: "Allow",
173 Principal: { Service: "dlm.amazonaws.com" },
174 Action: ["sts:AssumeRole"],
175 },
176 ],
177 },
178 managedPolicyArns: [
179 "arn:aws:iam::aws:policy/service-role/AWSDataLifecycleManagerServiceRole",
180 "arn:aws:iam::aws:policy/service-role/AWSDataLifecycleManagerServiceRoleForAMIManagement",
181 ],
182 });
183 const policy = yield* LifecyclePolicy("Policy", {
184 description: "alchemy dlm explicit role test",
185 state: "DISABLED",
186 executionRoleArn: role.roleArn,
187 policyDetails,
188 });
189 return { role, policy };
190 }),
191 );
192
193 const first = yield* deployWith(snapshotDetails(2));
194 expect(first.policy.state).toBe("DISABLED");
195 expect(first.policy.roleName).toBeUndefined();
196 expect(first.policy.executionRoleArn).toBe(first.role.roleArn);
197
198 const observed = yield* dlm
199 .getLifecyclePolicy({ PolicyId: first.policy.policyId })
200 .pipe(Effect.map((r) => r.Policy!));
201 expect(observed.State).toBe("DISABLED");
202 expect(observed.Description).toBe("alchemy dlm explicit role test");
203 expect(observed.ExecutionRoleArn).toBe(first.role.roleArn);
204
205 // changing the policy type replaces the policy (new PolicyId). The
206 // role stays deployed across the replacement step.
207 const second = yield* deployWith({
208 policyType: "IMAGE_MANAGEMENT",
209 resourceTypes: ["INSTANCE"],
210 targetTags: { AlchemyDlmTest: "ami" },
211 parameters: { noReboot: true },
212 schedules: [
213 {
214 name: "Nightly",
215 createRule: { interval: 24, intervalUnit: "HOURS" },
216 retainRule: { count: 2 },
217 },
218 ],
219 });
220 expect(second.policy.policyId).not.toBe(first.policy.policyId);
221
222 const observedAmi = yield* dlm
223 .getLifecyclePolicy({ PolicyId: second.policy.policyId })
224 .pipe(Effect.map((r) => r.Policy!));
225 expect(observedAmi.PolicyDetails?.PolicyType).toBe("IMAGE_MANAGEMENT");
226 expect(observedAmi.PolicyDetails?.Parameters?.NoReboot).toBe(true);
227 yield* assertPolicyDeleted(first.policy.policyId);
228
229 yield* stack.destroy();
230 yield* assertPolicyDeleted(second.policy.policyId);
231 }),
232 {
233 tags: ["provider:aws", "provider:aws:dlm", "provider:aws:iam", "live"],
234 timeout: 180_000,
235 },
236 );