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

main
ts 276 lines 10.1 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { describe, expect } from "@alchemy.run/test";
3 import * as Test from "@alchemy.run/test/Alchemy";
4 import * as Core from "@alchemy.run/test/Core";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as HttpClient from "effect/http/HttpClient";
8 import * as HttpClientRequest from "effect/http/HttpClientRequest";
9 import * as Schedule from "effect/Schedule";
10 import CfnTestFunctionLive, { CfnTestFunction, FIXTURE_EXPORT_NAME } from "./handler";
11
12 const testOptions = { providers: AWS.providers() };
13 const { test, beforeAll, afterAll } = Test.make(testOptions);
14 const sharedStack = Core.scratchStack(testOptions, "CloudFormationBindings");
15
16 // Lambda function URL cold-start (DNS, IAM propagation, init) can take well
17 // over 60s on a fresh deploy under parallel-suite load.
18 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(120)]);
19
20 let baseUrl: string;
21
22 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
23 readonly status: number;
24 readonly body: string;
25 }> {}
26
27 // Retry transient 5xx from the shared Lambda fixture (cold re-init, IAM
28 // propagation on the freshly attached cloudformation policy surfaced as a
29 // 500 by the handler's `Effect.orDie`). Genuine 4xx/assertion failures
30 // return immediately.
31 const send = (request: HttpClientRequest.HttpClientRequest) =>
32 HttpClient.execute(request).pipe(
33 Effect.flatMap((response) =>
34 response.status >= 500
35 ? response.text.pipe(
36 Effect.flatMap((body) =>
37 Effect.fail(new TransientUpstream({ status: response.status, body })),
38 ),
39 )
40 : Effect.succeed(response),
41 ),
42 Effect.retry({
43 while: (e) => e._tag === "TransientUpstream",
44 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
45 }),
46 );
47
48 const getJson = (url: string) =>
49 send(HttpClientRequest.get(url)).pipe(Effect.flatMap((r) => r.json));
50
51 describe.sequential(
52 "CloudFormation Bindings",
53 { tags: ["provider:aws", "provider:aws:cloudformation", "provider:aws:lambda", "live"] },
54 () => {
55 beforeAll(
56 Effect.gen(function* () {
57 yield* Effect.logInfo("CFN test setup: destroying previous resources");
58 yield* sharedStack.destroy();
59
60 yield* Effect.logInfo("CFN test setup: deploying fixture");
61 const { functionUrl } = yield* sharedStack.deploy(
62 Effect.gen(function* () {
63 return yield* CfnTestFunction;
64 }).pipe(Effect.provide(CfnTestFunctionLive)),
65 );
66
67 expect(functionUrl).toBeTruthy();
68 baseUrl = functionUrl!.replace(/\/+$/, "");
69 const readinessUrl = `${baseUrl}/describe`;
70
71 yield* Effect.logInfo(`CFN test setup: probing readiness at ${readinessUrl}`);
72 yield* HttpClient.get(readinessUrl).pipe(
73 Effect.flatMap((response) =>
74 response.status === 200
75 ? Effect.succeed(response)
76 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
77 ),
78 Effect.retry({ schedule: readinessPolicy }),
79 );
80 }),
81 { timeout: 420_000 },
82 );
83
84 afterAll.skipIf(!!process.env.NO_DESTROY)(sharedStack.destroy(), { timeout: 240_000 });
85
86 describe("DescribeStacks", () => {
87 test.provider("reads the bound stack's status and outputs", (_stack) =>
88 Effect.gen(function* () {
89 const body = (yield* getJson(`${baseUrl}/describe`)) as any;
90
91 expect(body.stackId).toContain("arn:aws:cloudformation:");
92 expect(["CREATE_COMPLETE", "UPDATE_COMPLETE"]).toContain(body.status);
93 expect(body.outputs.ParamName).toBeDefined();
94 }),
95 );
96 });
97
98 describe("DescribeStackEvents", () => {
99 test.provider("reads the stack's event history", (_stack) =>
100 Effect.gen(function* () {
101 const body = (yield* getJson(`${baseUrl}/events`)) as any;
102
103 expect(body.count).toBeGreaterThan(0);
104 expect(Array.isArray(body.statuses)).toBe(true);
105 }),
106 );
107 });
108
109 describe("DescribeStackResources", () => {
110 test.provider("resolves a resource's physical id", (_stack) =>
111 Effect.gen(function* () {
112 const body = (yield* getJson(`${baseUrl}/resources`)) as any;
113
114 expect(body.logicalId).toBe("Param");
115 expect(body.type).toBe("AWS::SSM::Parameter");
116 expect(body.physicalId).toBeTruthy();
117 }),
118 );
119 });
120
121 describe("ListStackResources", () => {
122 test.provider("enumerates the stack's resources", (_stack) =>
123 Effect.gen(function* () {
124 const body = (yield* getJson(`${baseUrl}/list-resources`)) as any;
125
126 expect(body.types).toContain("AWS::SSM::Parameter");
127 }),
128 );
129 });
130
131 describe("GetTemplate", () => {
132 test.provider("reads the deployed template body", (_stack) =>
133 Effect.gen(function* () {
134 const body = (yield* getJson(`${baseUrl}/template`)) as any;
135
136 expect(body.template).toContain("AWS::SSM::Parameter");
137 }),
138 );
139 });
140
141 describe("DetectStackDrift + DescribeStackDriftDetectionStatus", () => {
142 test.provider(
143 "starts drift detection and polls it to a terminal status",
144 (_stack) =>
145 Effect.gen(function* () {
146 const started = (yield* send(HttpClientRequest.post(`${baseUrl}/drift`)).pipe(
147 Effect.flatMap((r) => r.json),
148 )) as any;
149
150 expect(started.detectionId).toBeTruthy();
151
152 // Detection runs asynchronously; poll until it leaves
153 // DETECTION_IN_PROGRESS. DETECTION_FAILED is acceptable — the
154 // fixture role has no ssm read access, and either terminal status
155 // proves the cloudformation:* IAM + binding wiring.
156 const status = yield* getJson(`${baseUrl}/drift-status?id=${started.detectionId}`).pipe(
157 Effect.flatMap((body: any) =>
158 body.detectionStatus === "DETECTION_IN_PROGRESS"
159 ? Effect.fail(new DriftInProgress())
160 : Effect.succeed(body),
161 ),
162 Effect.retry({
163 while: (e) => e._tag === "DriftInProgress",
164 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(20)]),
165 }),
166 );
167
168 expect(["DETECTION_COMPLETE", "DETECTION_FAILED"]).toContain(
169 (status as any).detectionStatus,
170 );
171 }),
172 { timeout: 120_000 },
173 );
174 });
175
176 describe("DescribeStackResourceDrifts", () => {
177 test.provider("reads per-resource drift results", (_stack) =>
178 Effect.gen(function* () {
179 const body = (yield* getJson(`${baseUrl}/resource-drifts`)) as any;
180
181 // Results only exist for resources CloudFormation managed to check;
182 // the call succeeding proves the binding + IAM wiring either way.
183 expect(Array.isArray(body.drifts)).toBe(true);
184 }),
185 );
186 });
187
188 describe("ListExports", () => {
189 test.provider("lists the fixture stack's export", (_stack) =>
190 Effect.gen(function* () {
191 // Exports are eventually consistent for fresh stacks.
192 const body = yield* fetchUntil(
193 getJson(`${baseUrl}/exports`),
194 (b) => Array.isArray(b?.names) && b.names.includes(FIXTURE_EXPORT_NAME),
195 );
196
197 expect((body as any).names).toContain(FIXTURE_EXPORT_NAME);
198 }),
199 );
200 });
201
202 describe("ListImports", () => {
203 test.provider("fails with a typed error for an un-imported export", (_stack) =>
204 Effect.gen(function* () {
205 const body = (yield* getJson(`${baseUrl}/imports?name=${FIXTURE_EXPORT_NAME}`)) as any;
206
207 // Nothing imports the fixture export — CloudFormation must reject
208 // with a TYPED tag (an untyped catch-all would crash into a 500).
209 expect(typeof body.errorTag).toBe("string");
210 expect(body.errorTag.length).toBeGreaterThan(0);
211 }),
212 );
213 });
214
215 describe("ValidateTemplate", () => {
216 test.provider("validates the fixture template", (_stack) =>
217 Effect.gen(function* () {
218 const body = (yield* send(
219 HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(`${baseUrl}/validate`), {}),
220 ).pipe(Effect.flatMap((r) => r.json))) as any;
221
222 expect(Array.isArray(body.parameters)).toBe(true);
223 expect(body.errorTag).toBeUndefined();
224 }),
225 );
226
227 test.provider("rejects an invalid template with a typed error", (_stack) =>
228 Effect.gen(function* () {
229 const body = (yield* send(
230 HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(`${baseUrl}/validate`), {
231 template: '{"Resources": {}}',
232 }),
233 ).pipe(Effect.flatMap((r) => r.json))) as any;
234
235 expect(typeof body.errorTag).toBe("string");
236 expect(body.errorTag.length).toBeGreaterThan(0);
237 }),
238 );
239 });
240
241 describe("SignalResource", () => {
242 test.provider("delivers a signal for a stack resource", (_stack) =>
243 Effect.gen(function* () {
244 const body = (yield* send(HttpClientRequest.post(`${baseUrl}/signal`)).pipe(
245 Effect.flatMap((r) => r.json),
246 )) as any;
247
248 // CloudFormation accepts (and ignores) signals for resources that
249 // are not waiting on a CreationPolicy — a 200 proves the
250 // cloudformation:SignalResource IAM + binding wiring.
251 expect(body.ok).toBe(true);
252 }),
253 );
254 });
255 },
256 );
257
258 class DriftInProgress extends Data.TaggedError("DriftInProgress") {}
259
260 // A request observed not-yet-consistent control-plane state (ListExports
261 // lags fresh stacks by a few seconds). Retry, bounded.
262 class BindingNotConsistent extends Data.TaggedError("BindingNotConsistent") {}
263
264 const fetchUntil = <A>(
265 fetch: Effect.Effect<unknown, any, HttpClient.HttpClient>,
266 ready: (body: any) => boolean,
267 ) =>
268 fetch.pipe(
269 Effect.flatMap((body) =>
270 ready(body) ? Effect.succeed(body as A) : Effect.fail(new BindingNotConsistent()),
271 ),
272 Effect.retry({
273 while: (e) => e._tag === "BindingNotConsistent",
274 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(20)]),
275 }),
276 );