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

main
ts 229 lines 8.71 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 eventbridge from "@distilled.cloud/aws/eventbridge";
6 import * as ssm from "@distilled.cloud/aws/ssm";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as HttpClient from "effect/http/HttpClient";
10 import * as HttpClientRequest from "effect/http/HttpClientRequest";
11 import * as Schedule from "effect/Schedule";
12 import SSMTestFunctionLive, { SSMTestFunction } from "./handler";
13
14 const testOptions = { providers: AWS.providers() };
15 const { test, beforeAll, afterAll } = Test.make(testOptions);
16 const sharedStack = Core.scratchStack(testOptions, "SSMBindings");
17
18 // Lambda function URL cold-start (DNS, IAM propagation, init) can take well
19 // over 60s on a fresh deploy under parallel-suite load. Budget ~150s of
20 // readiness polling.
21 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]);
22
23 let baseUrl: string;
24 let functionArn: string;
25
26 class ParameterStillExists extends Data.TaggedError("ParameterStillExists")<{
27 readonly name: string;
28 }> {}
29
30 const assertParameterDeleted = (name: string) =>
31 ssm.getParameter({ Name: name }).pipe(
32 Effect.flatMap(() => Effect.fail(new ParameterStillExists({ name }))),
33 Effect.catchTag("ParameterNotFound", () => Effect.void),
34 Effect.retry({
35 while: (e) => e._tag === "ParameterStillExists",
36 schedule: Schedule.max([Schedule.exponential(500), Schedule.recurs(8)]),
37 }),
38 );
39
40 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
41 readonly status: number;
42 readonly body: string;
43 }> {}
44
45 // The shared Lambda fixture occasionally answers a transient 5xx under
46 // parallel load (cold re-init, IAM propagation). Retry 5xx only; a genuine
47 // 4xx/assertion failure surfaces immediately.
48 const send = (request: HttpClientRequest.HttpClientRequest) =>
49 HttpClient.execute(request).pipe(
50 Effect.flatMap((response) =>
51 response.status >= 500
52 ? response.text.pipe(
53 Effect.flatMap((body) =>
54 Effect.fail(new TransientUpstream({ status: response.status, body })),
55 ),
56 )
57 : Effect.succeed(response),
58 ),
59 Effect.retry({
60 while: (e) => e._tag === "TransientUpstream",
61 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
62 }),
63 );
64
65 const getJson = (path: string) =>
66 send(HttpClientRequest.get(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
67
68 const postJson = (path: string) =>
69 send(HttpClientRequest.post(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
70
71 describe.sequential(
72 "SSM Bindings",
73 { tags: ["provider:aws", "provider:aws:lambda", "provider:aws:ssm", "live"] },
74 () => {
75 beforeAll(
76 Effect.gen(function* () {
77 yield* Effect.logInfo("SSM test setup: destroying previous resources");
78 yield* sharedStack.destroy();
79
80 yield* Effect.logInfo("SSM test setup: deploying fixture");
81 const attrs = yield* sharedStack.deploy(
82 Effect.gen(function* () {
83 return yield* SSMTestFunction;
84 }).pipe(Effect.provide(SSMTestFunctionLive)),
85 );
86
87 expect(attrs.functionUrl).toBeTruthy();
88 baseUrl = attrs.functionUrl!.replace(/\/+$/, "");
89 functionArn = attrs.functionArn;
90 const readinessUrl = `${baseUrl}/get-string`;
91
92 yield* Effect.logInfo(`SSM test setup: probing readiness at ${readinessUrl}`);
93 yield* HttpClient.get(readinessUrl).pipe(
94 Effect.flatMap((response) =>
95 response.status === 200
96 ? Effect.succeed(response)
97 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
98 ),
99 Effect.tapError((error) =>
100 Effect.logWarning(`SSM test setup: fixture not ready yet (${String(error)})`),
101 ),
102 Effect.retry({ schedule: readinessPolicy }),
103 );
104 }),
105 { timeout: 240_000 },
106 );
107
108 // Idempotent backstop — the "destroy leaves nothing behind" test below is
109 // the primary teardown; this reclaims resources if that test never ran.
110 afterAll(sharedStack.destroy(), { timeout: 120_000 });
111
112 describe("GetParameter", () => {
113 test.provider("reads a String parameter through the binding", (_stack) =>
114 Effect.gen(function* () {
115 const response = yield* getJson("/get-string");
116
117 expect((response as any).type).toBe("String");
118 expect((response as any).value).toBe("plain-config-value");
119 }),
120 );
121
122 test.provider("decrypts a SecureString parameter through the binding", (_stack) =>
123 Effect.gen(function* () {
124 const response = yield* getJson("/get-secure");
125
126 expect((response as any).type).toBe("SecureString");
127 expect((response as any).value).toBe("bound-secret-value");
128 }),
129 );
130 });
131
132 describe("GetParameters", () => {
133 test.provider("reads String and SecureString parameters in one call", (_stack) =>
134 Effect.gen(function* () {
135 const response = yield* getJson("/get-many");
136
137 const parameters = (response as any).parameters as Array<{
138 name: string;
139 type: string;
140 value: string;
141 }>;
142 expect((response as any).invalidParameters).toEqual([]);
143 expect(parameters).toHaveLength(2);
144 const values = parameters.map((p) => p.value).sort();
145 expect(values).toEqual(["bound-secret-value", "plain-config-value"].sort());
146 }),
147 );
148 });
149
150 describe("GetParameterHistory", () => {
151 test.provider("reads the deployed version from the parameter's history", (_stack) =>
152 Effect.gen(function* () {
153 const response = (yield* getJson("/history")) as { count: number; values: string[] };
154 expect(response.count).toBeGreaterThanOrEqual(1);
155 expect(response.values).toContain("v1");
156 }),
157 );
158 });
159
160 describe("PutParameter", () => {
161 test.provider("writes a new version of the bound parameter at runtime", (_stack) =>
162 Effect.gen(function* () {
163 const response = (yield* postJson("/put")) as { version: number; latest: string };
164 expect(response.version).toBeGreaterThanOrEqual(2);
165 expect(response.latest).toBe("v2-runtime");
166 }),
167 );
168 });
169
170 describe("Label/UnlabelParameterVersion", () => {
171 test.provider("labels the latest version and removes the label again", (_stack) =>
172 Effect.gen(function* () {
173 const response = (yield* postJson("/label-cycle")) as {
174 labeledVersion: number;
175 invalidLabels: string[];
176 removedLabels: string[];
177 };
178 expect(response.labeledVersion).toBeGreaterThanOrEqual(1);
179 expect(response.invalidLabels).toEqual([]);
180 expect(response.removedLabels).toContain("current");
181 }),
182 );
183 });
184
185 describe("GetParametersByPath", () => {
186 test.provider("reads the subtree under the bound path-root parameter", (_stack) =>
187 Effect.gen(function* () {
188 const response = (yield* getJson("/by-path")) as {
189 parameters: Array<{ name: string; value: string }>;
190 };
191 const child = response.parameters.find(
192 (parameter) => parameter.name === "/alchemy-test/ssm-bindings/root/child",
193 );
194 expect(child?.value).toBe("child-value");
195 }),
196 );
197 });
198
199 describe("consumeParameterEvents", { tags: ["provider:aws:eventbridge"] }, () => {
200 test.provider("the deploy created an EventBridge rule targeting the function", (_stack) =>
201 Effect.gen(function* () {
202 // Out-of-band via distilled: the fixture's consumeParameterEvents
203 // must have materialized as a rule on the default bus with the
204 // Lambda as target.
205 const { RuleNames } = yield* eventbridge.listRuleNamesByTarget({
206 TargetArn: functionArn,
207 });
208 expect((RuleNames ?? []).length).toBeGreaterThanOrEqual(1);
209 }),
210 );
211 });
212
213 // Runs last (describe.sequential): tear the shared stack down and prove
214 // out-of-band that the destroy left nothing behind. The afterAll destroy
215 // stays registered as an idempotent backstop for crashes before this test.
216 describe("teardown", () => {
217 test.provider(
218 "destroy leaves no parameters behind",
219 (_stack) =>
220 Effect.gen(function* () {
221 yield* sharedStack.destroy();
222 yield* assertParameterDeleted("/alchemy-test/ssm-bindings/root");
223 yield* assertParameterDeleted("/alchemy-test/ssm-bindings/root/child");
224 }),
225 { timeout: 120_000 },
226 );
227 });
228 },
229 );