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

main
ts 239 lines 9.51 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 AppConfigTestFunctionLive, { AppConfigTestFunction } from "./fixtures/handler";
11
12 const testOptions = { providers: AWS.providers() };
13 const { test, beforeAll, afterAll } = Test.make(testOptions);
14 const sharedStack = Core.scratchStack(testOptions, "AppConfigBindings");
15
16 let baseUrl: string;
17
18 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
19 readonly status: number;
20 readonly body: string;
21 }> {}
22
23 // Fresh Lambda role + AppConfig permissions propagate eventually — the first
24 // fetches can 500 with AccessDenied under the handler's `Effect.orDie`. Retry
25 // 5xx only; a genuine 4xx fails immediately.
26 const send = (request: HttpClientRequest.HttpClientRequest) =>
27 HttpClient.execute(request).pipe(
28 Effect.flatMap((response) =>
29 response.status >= 500
30 ? response.text.pipe(
31 Effect.flatMap((body) =>
32 Effect.fail(new TransientUpstream({ status: response.status, body })),
33 ),
34 )
35 : Effect.succeed(response),
36 ),
37 Effect.retry({
38 while: (e) => e._tag === "TransientUpstream",
39 schedule: Schedule.max([Schedule.exponential("1 second"), Schedule.recurs(8)]),
40 }),
41 );
42
43 // Sequential: the tests share one Lambda + one AppConfig environment, and
44 // AppConfig allows only one in-flight deployment per environment. Concurrent
45 // execution races the v2 rollout against the v1 `/config` assertion.
46 describe.sequential(
47 "AppConfig Bindings",
48 { tags: ["provider:aws", "provider:aws:appconfig", "provider:aws:lambda", "live"] },
49 () => {
50 beforeAll(
51 Effect.gen(function* () {
52 yield* Effect.logInfo("AppConfig test setup: destroying previous resources");
53 yield* sharedStack.destroy();
54
55 yield* Effect.logInfo(
56 "AppConfig test setup: deploying app -> env -> profile -> version -> deployment -> Lambda",
57 );
58 const { functionUrl } = yield* sharedStack.deploy(
59 Effect.gen(function* () {
60 return yield* AppConfigTestFunction;
61 }).pipe(Effect.provide(AppConfigTestFunctionLive)),
62 );
63
64 expect(functionUrl).toBeTruthy();
65 baseUrl = functionUrl!.replace(/\/+$/, "");
66
67 // Readiness probe — fresh function URLs take seconds to serve 200s.
68 yield* HttpClient.get(`${baseUrl}/ping`).pipe(
69 Effect.flatMap((response) =>
70 response.status === 200
71 ? Effect.succeed(response)
72 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
73 ),
74 Effect.retry({
75 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]),
76 }),
77 );
78
79 // Authorization gate — control-plane grants on a freshly created role
80 // can take up to a minute to become effective. Wait once here so every
81 // test runs against a fully authorized Lambda.
82 yield* HttpClient.execute(
83 HttpClientRequest.post(`${baseUrl}/validate`).pipe(
84 HttpClientRequest.bodyJsonUnsafe({ version: "1" }),
85 ),
86 ).pipe(
87 Effect.flatMap((response) =>
88 response.status === 200
89 ? Effect.succeed(response)
90 : Effect.fail(
91 new Error(`management bindings not yet authorized: ${response.status}`),
92 ),
93 ),
94 Effect.retry({
95 schedule: Schedule.max([Schedule.spaced("5 seconds"), Schedule.recurs(24)]),
96 }),
97 );
98 }),
99 { timeout: 360_000 },
100 );
101 afterAll(sharedStack.destroy(), { timeout: 300_000 });
102
103 describe("GetConfiguration", () => {
104 test.provider(
105 "the Lambda fetches its deployed configuration through the binding",
106 () =>
107 Effect.gen(function* () {
108 // The data plane may briefly serve an empty body right after the
109 // deployment completes; retry until the content is present.
110 const body = yield* send(HttpClientRequest.get(`${baseUrl}/config`)).pipe(
111 Effect.flatMap((response) => response.json),
112 Effect.map((json) => json as { content?: string; contentType?: string }),
113 Effect.filterOrFail(
114 (json) => typeof json.content === "string" && json.content.length > 0,
115 () => new Error("configuration not yet available"),
116 ),
117 Effect.retry({
118 schedule: Schedule.max([Schedule.spaced("3 seconds"), Schedule.recurs(20)]),
119 }),
120 );
121
122 expect(body.contentType).toContain("application/json");
123 expect(JSON.parse(body.content!)).toEqual({ featureX: true, limit: 42 });
124 }),
125 { timeout: 180_000 },
126 );
127 });
128
129 describe("CreateHostedConfigurationVersion + StartDeployment + GetDeployment", () => {
130 test.provider(
131 "the Lambda writes a new version, rolls it out, and serves it",
132 () =>
133 Effect.gen(function* () {
134 const newContent = JSON.stringify({ featureX: false, limit: 7 });
135
136 // 1. Write a new hosted configuration version through the binding.
137 const version = yield* send(
138 HttpClientRequest.post(`${baseUrl}/version`).pipe(
139 HttpClientRequest.bodyJsonUnsafe({ content: newContent }),
140 ),
141 ).pipe(
142 Effect.flatMap((response) => response.json),
143 Effect.map((json) => json as { versionNumber?: number }),
144 );
145 expect(version.versionNumber).toBeGreaterThan(1);
146
147 // 2. Roll it out with the all-at-once strategy.
148 const started = yield* send(
149 HttpClientRequest.post(`${baseUrl}/deploy`).pipe(
150 HttpClientRequest.bodyJsonUnsafe({ version: String(version.versionNumber) }),
151 ),
152 ).pipe(
153 Effect.flatMap((response) => response.json),
154 Effect.map((json) => json as { deploymentNumber?: number; state?: string }),
155 );
156 expect(started.deploymentNumber).toBeGreaterThan(0);
157
158 // 3. Poll the deployment through the binding until it completes.
159 const settled = yield* send(
160 HttpClientRequest.get(`${baseUrl}/deployment?number=${started.deploymentNumber}`),
161 ).pipe(
162 Effect.flatMap((response) => response.json),
163 Effect.map((json) => json as { state?: string }),
164 Effect.repeat({
165 schedule: Schedule.spaced("3 seconds"),
166 until: (json): boolean => json.state === "COMPLETE",
167 times: 30,
168 }),
169 );
170 expect(settled.state).toBe("COMPLETE");
171
172 // 4. The data plane now serves the new content.
173 const body = yield* send(HttpClientRequest.get(`${baseUrl}/config`)).pipe(
174 Effect.flatMap((response) => response.json),
175 Effect.map((json) => json as { content?: string }),
176 Effect.filterOrFail(
177 (json) => json.content === newContent,
178 () => new Error("new configuration not yet served"),
179 ),
180 Effect.retry({
181 schedule: Schedule.max([Schedule.spaced("3 seconds"), Schedule.recurs(20)]),
182 }),
183 );
184 expect(JSON.parse(body.content!)).toEqual({ featureX: false, limit: 7 });
185 }),
186 { timeout: 300_000 },
187 );
188 });
189
190 describe("ValidateConfiguration", () => {
191 test.provider(
192 "the Lambda validates a hosted version against the profile's validators",
193 () =>
194 Effect.gen(function* () {
195 const body = yield* send(
196 HttpClientRequest.post(`${baseUrl}/validate`).pipe(
197 HttpClientRequest.bodyJsonUnsafe({ version: "1" }),
198 ),
199 ).pipe(
200 Effect.flatMap((response) => response.json),
201 Effect.map((json) => json as { valid?: boolean }),
202 );
203 expect(body.valid).toBe(true);
204 }),
205 { timeout: 120_000 },
206 );
207 });
208
209 describe("StopDeployment", () => {
210 test.provider(
211 "the Lambda stops a slow in-flight rollout",
212 () =>
213 Effect.gen(function* () {
214 // Start a rollout that takes 20 minutes so it is stoppable.
215 const started = yield* send(
216 HttpClientRequest.post(`${baseUrl}/deploy`).pipe(
217 HttpClientRequest.bodyJsonUnsafe({ version: "1", slow: true }),
218 ),
219 ).pipe(
220 Effect.flatMap((response) => response.json),
221 Effect.map((json) => json as { deploymentNumber?: number; state?: string }),
222 );
223 expect(started.deploymentNumber).toBeGreaterThan(0);
224
225 const stopped = yield* send(
226 HttpClientRequest.post(`${baseUrl}/stop`).pipe(
227 HttpClientRequest.bodyJsonUnsafe({ number: started.deploymentNumber }),
228 ),
229 ).pipe(
230 Effect.flatMap((response) => response.json),
231 Effect.map((json) => json as { state?: string }),
232 );
233 expect(stopped.state).toBe("ROLLED_BACK");
234 }),
235 { timeout: 180_000 },
236 );
237 });
238 },
239 );