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

main
ts 398 lines 15.9 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 rds from "@distilled.cloud/aws/rds";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as HttpClient from "effect/http/HttpClient";
9 import * as HttpClientRequest from "effect/http/HttpClientRequest";
10 import * as Layer from "effect/Layer";
11 import * as Schedule from "effect/Schedule";
12 import RDSDrizzleIamFunctionLive, { RDSDrizzleIamFunction } from "./drizzle-iam-handler";
13 import RDSDataTestFunctionLive, { RDSDataTestFunction } from "./handler";
14 import { reapRDSDataOrphans } from "./reap";
15
16 // Aurora Serverless v2 cluster + writer-instance provisioning takes 5-15
17 // minutes — far beyond the speed doctrine's budget — so the ENTIRE live suite
18 // (deploy hook, every test, destroy hook) skipped under `--fast`.
19 // A run without the env var is skip-clean: no AWS calls, no side effects.
20 const SLOW = !process.env.FAST;
21
22 const testOptions = { providers: AWS.providers() };
23 const { test, beforeAll, afterAll } = Test.make(testOptions);
24 const sharedStack = Core.scratchStack(testOptions, "RDSDataBindings");
25
26 let baseUrl: string;
27 let drizzleUrl: string;
28 let clusterIdentifier: string | undefined;
29
30 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
31 readonly status: number;
32 readonly body: string;
33 }> {}
34
35 class ClusterStillPresent extends Data.TaggedError("ClusterStillPresent")<{
36 readonly clusterIdentifier: string;
37 }> {}
38
39 // The fixture surfaces every failure as a 500 (handler-level `Effect.orDie`).
40 // A 5xx from this Lambda is either a cold re-init or an rds-data transient
41 // (DatabaseResumingException / DatabaseUnavailableException while the
42 // serverless cluster scales from idle) — retry those on a generous bounded
43 // schedule; a 4xx/assertion failure is surfaced immediately.
44 const send = (request: HttpClientRequest.HttpClientRequest) =>
45 HttpClient.execute(request).pipe(
46 Effect.flatMap((response) =>
47 response.status >= 500
48 ? response.text.pipe(
49 Effect.flatMap((body) =>
50 Effect.fail(new TransientUpstream({ status: response.status, body })),
51 ),
52 )
53 : Effect.succeed(response),
54 ),
55 Effect.retry({
56 while: (e) => e._tag === "TransientUpstream",
57 schedule: Schedule.max([Schedule.spaced("5 seconds"), Schedule.recurs(8)]),
58 }),
59 );
60
61 const postJson = (url: string, body: unknown) =>
62 send(HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(url), body)).pipe(
63 Effect.flatMap((r) => r.json),
64 );
65
66 // The scratch stack's state store is IN MEMORY, so `sharedStack.destroy()`
67 // can only see resources deployed by THIS process. A previous run killed
68 // mid-deploy/mid-destroy (Aurora provisioning + teardown run 10+ minutes)
69 // leaves the whole VPC/RDS fixture orphaned with no state to destroy from.
70 // The reaper deletes fixture leftovers out-of-band by deterministic
71 // name-prefix / ownership tag; it runs as a pre-clean before deploy and as
72 // an `ensuring` finalizer after destroy.
73 const reapOrphans = Core.withProviders(reapRDSDataOrphans, testOptions, sharedStack.name);
74
75 describe(
76 "RDSData Bindings",
77 {
78 tags: [
79 "provider:aws",
80 "provider:aws:batch",
81 "provider:aws:ec2",
82 "provider:aws:iam",
83 "provider:aws:lambda",
84 "provider:aws:rds",
85 "provider:aws:rdsdata",
86 "provider:aws:secretsmanager",
87 "live",
88 ],
89 },
90 () => {
91 beforeAll(
92 SLOW
93 ? Effect.gen(function* () {
94 yield* Effect.logInfo("RDSData test setup: destroying previous resources");
95 yield* sharedStack.destroy();
96
97 yield* Effect.logInfo(
98 "RDSData test setup: reaping orphans from prior interrupted runs",
99 );
100 yield* reapOrphans;
101
102 yield* Effect.logInfo(
103 "RDSData test setup: deploying Aurora SV2 + Lambda fixture (5-15 min)",
104 );
105 const { dataApiUrl, drizzleIamUrl } = yield* sharedStack.deploy(
106 Effect.gen(function* () {
107 const dataApi = yield* RDSDataTestFunction;
108 const drizzleIam = yield* RDSDrizzleIamFunction;
109 return { dataApiUrl: dataApi.functionUrl, drizzleIamUrl: drizzleIam.functionUrl };
110 }).pipe(
111 Effect.provide(Layer.mergeAll(RDSDataTestFunctionLive, RDSDrizzleIamFunctionLive)),
112 ),
113 );
114
115 expect(dataApiUrl).toBeTruthy();
116 expect(drizzleIamUrl).toBeTruthy();
117 baseUrl = dataApiUrl!.replace(/\/+$/, "");
118 drizzleUrl = drizzleIamUrl!.replace(/\/+$/, "");
119
120 // Bounded readiness poll (gated-suite only): the cluster is already
121 // `available` when deploy returns (the DBCluster/DBInstance
122 // reconcilers wait for it), so this covers Lambda URL cold start
123 // plus first Data API connection setup. Generous spaced schedule:
124 // 10s x 42 ≈ 7 min ceiling.
125 yield* HttpClient.get(`${baseUrl}/health`).pipe(
126 Effect.flatMap((response) =>
127 response.status === 200
128 ? Effect.succeed(response)
129 : Effect.fail(new Error(`Fixture not ready: ${response.status}`)),
130 ),
131 Effect.tapError((error) =>
132 Effect.logWarning(`RDSData test setup: fixture not ready yet (${String(error)})`),
133 ),
134 Effect.retry({
135 schedule: Schedule.max([Schedule.spaced("10 seconds"), Schedule.recurs(42)]),
136 }),
137 );
138
139 // Capture the cluster identifier so afterAll can verify deletion
140 // out-of-band after destroy.
141 const meta = (yield* HttpClient.get(`${baseUrl}/meta`).pipe(
142 Effect.flatMap((r) => r.json),
143 )) as { clusterIdentifier: string };
144 clusterIdentifier = meta.clusterIdentifier;
145 yield* Effect.logInfo(
146 `RDSData test setup: fixture ready (cluster ${clusterIdentifier})`,
147 );
148
149 // Create the shared table once for all binding tests.
150 yield* postJson(`${baseUrl}/setup`, {});
151
152 // Bootstrap the IAM-auth DB user (rds_iam + table grants) via the
153 // Data API — the VPC-attached Drizzle fixture can't reach the Data
154 // API itself.
155 yield* postJson(`${baseUrl}/setup-iam-user`, {});
156 })
157 : Effect.void,
158 { timeout: 1_500_000 },
159 );
160
161 afterAll(
162 SLOW
163 ? Effect.gen(function* () {
164 yield* sharedStack.destroy();
165
166 // Out-of-band deletion check via distilled: the DBCluster provider
167 // already waits until the cluster is gone, so this is a bounded
168 // confirmation, not a long poll.
169 if (clusterIdentifier) {
170 yield* Core.withProviders(
171 rds.describeDBClusters({ DBClusterIdentifier: clusterIdentifier }).pipe(
172 Effect.flatMap((response) =>
173 (response.DBClusters ?? []).length === 0
174 ? Effect.void
175 : Effect.fail(
176 new ClusterStillPresent({ clusterIdentifier: clusterIdentifier! }),
177 ),
178 ),
179 Effect.catchTag("DBClusterNotFoundFault", () => Effect.void),
180 Effect.retry({
181 schedule: Schedule.max([Schedule.spaced("15 seconds"), Schedule.recurs(8)]),
182 }),
183 ),
184 testOptions,
185 sharedStack.name,
186 );
187 }
188 }).pipe(
189 // Always sweep out-of-band leftovers — even when destroy itself
190 // fails partway (e.g. a lingering Lambda ENI blocking SG deletion).
191 // Once this process exits, the in-memory state is gone and nothing
192 // else can ever find these resources again.
193 Effect.ensuring(reapOrphans.pipe(Effect.orDie)),
194 )
195 : Effect.void,
196 { timeout: 1_500_000 },
197 );
198
199 describe("ExecuteStatement", () => {
200 test.provider.skipIf(!SLOW)(
201 "inserts and selects a row with typed parameters",
202 (_stack) =>
203 Effect.gen(function* () {
204 const insert = (yield* postJson(`${baseUrl}/insert`, { id: 1, title: "first" })) as {
205 success: boolean;
206 numberOfRecordsUpdated: number;
207 };
208 expect(insert.success).toBe(true);
209 expect(insert.numberOfRecordsUpdated).toBe(1);
210
211 const select = (yield* send(HttpClientRequest.get(`${baseUrl}/select?id=1`)).pipe(
212 Effect.flatMap((r) => r.json),
213 )) as { records: { longValue?: number; stringValue?: string }[][] };
214 expect(select.records).toHaveLength(1);
215 expect(select.records[0]![0]!.longValue).toBe(1);
216 expect(select.records[0]![1]!.stringValue).toBe("first");
217 }),
218 { timeout: 120_000 },
219 );
220
221 test.provider.skipIf(!SLOW)(
222 "returns no records for a missing row",
223 (_stack) =>
224 Effect.gen(function* () {
225 const select = (yield* send(HttpClientRequest.get(`${baseUrl}/select?id=999999`)).pipe(
226 Effect.flatMap((r) => r.json),
227 )) as { records: unknown[] };
228 expect(select.records).toHaveLength(0);
229 }),
230 { timeout: 120_000 },
231 );
232 });
233
234 describe("BatchExecuteStatement", () => {
235 test.provider.skipIf(!SLOW)(
236 "inserts multiple rows via parameterSets",
237 (_stack) =>
238 Effect.gen(function* () {
239 const batch = (yield* postJson(`${baseUrl}/batch-insert`, {
240 rows: [
241 { id: 10, title: "batch-a" },
242 { id: 11, title: "batch-b" },
243 ],
244 })) as { updateResults: unknown[] };
245 expect(batch.updateResults).toHaveLength(2);
246
247 const select = (yield* send(HttpClientRequest.get(`${baseUrl}/select?id=11`)).pipe(
248 Effect.flatMap((r) => r.json),
249 )) as { records: { longValue?: number; stringValue?: string }[][] };
250 expect(select.records[0]![1]!.stringValue).toBe("batch-b");
251 }),
252 { timeout: 120_000 },
253 );
254 });
255
256 describe("BeginTransaction", () => {
257 test.provider.skipIf(!SLOW)(
258 "returns a transaction id",
259 (_stack) =>
260 Effect.gen(function* () {
261 const result = (yield* postJson(`${baseUrl}/tx-commit`, {
262 id: 20,
263 title: "begin",
264 })) as { transactionId: string };
265 expect(result.transactionId).toBeTruthy();
266 }),
267 { timeout: 120_000 },
268 );
269 });
270
271 describe("CommitTransaction", () => {
272 test.provider.skipIf(!SLOW)(
273 "commits an insert so it is visible afterwards",
274 (_stack) =>
275 Effect.gen(function* () {
276 const result = (yield* postJson(`${baseUrl}/tx-commit`, {
277 id: 30,
278 title: "committed",
279 })) as { transactionId: string; transactionStatus: string };
280 expect(result.transactionId).toBeTruthy();
281
282 const select = (yield* send(HttpClientRequest.get(`${baseUrl}/select?id=30`)).pipe(
283 Effect.flatMap((r) => r.json),
284 )) as { records: { longValue?: number; stringValue?: string }[][] };
285 expect(select.records).toHaveLength(1);
286 expect(select.records[0]![1]!.stringValue).toBe("committed");
287 }),
288 { timeout: 120_000 },
289 );
290 });
291
292 describe("RollbackTransaction", () => {
293 test.provider.skipIf(!SLOW)(
294 "rolls back an insert so it never becomes visible",
295 (_stack) =>
296 Effect.gen(function* () {
297 const result = (yield* postJson(`${baseUrl}/tx-rollback`, {
298 id: 40,
299 title: "rolled-back",
300 })) as { transactionId: string; transactionStatus: string };
301 expect(result.transactionId).toBeTruthy();
302
303 const select = (yield* send(HttpClientRequest.get(`${baseUrl}/select?id=40`)).pipe(
304 Effect.flatMap((r) => r.json),
305 )) as { records: unknown[] };
306 expect(select.records).toHaveLength(0);
307 }),
308 { timeout: 120_000 },
309 );
310 });
311
312 // RDS.Connect is not a Data API binding, but it targets the same cluster
313 // and only resolves connection settings (endpoint + secret credentials), so
314 // it shares this fixture instead of provisioning a second Aurora cluster.
315 describe("RDS.Connect", () => {
316 test.provider.skipIf(!SLOW)(
317 "resolves host, port, database and credentials from the secret",
318 (_stack) =>
319 Effect.gen(function* () {
320 const info = (yield* send(HttpClientRequest.get(`${baseUrl}/connect-info`)).pipe(
321 Effect.flatMap((r) => r.json),
322 )) as {
323 host: string;
324 port: number;
325 database?: string;
326 username?: string;
327 hasPassword: boolean;
328 ssl: boolean;
329 };
330 expect(info.host).toMatch(/\.rds\.amazonaws\.com$/);
331 expect(info.port).toBe(5432);
332 expect(info.database).toBe("app");
333 expect(info.username).toBe("app");
334 expect(info.hasPassword).toBe(true);
335 expect(info.ssl).toBe(true);
336 }),
337 { timeout: 120_000 },
338 );
339 });
340
341 // IAM database authentication (db-drivers §3 "RDS/Aurora"): the deploy
342 // half binds `rds-db:connect` on `dbuser:{resourceId}/app_iam` and attaches
343 // the Lambda to the fixture VPC through the binding contract's `vpc`
344 // channel (DECISION #5); the runtime half presigns a 15-minute token as the
345 // password and `Drizzle.Postgres` consumes `ConnectionInfo.url` directly.
346 describe("RDS.Connect (IAM auth)", () => {
347 test.provider.skipIf(!SLOW)(
348 "mints an IAM auth token as the password and can re-mint via refreshPassword",
349 (_stack) =>
350 Effect.gen(function* () {
351 const info = (yield* send(HttpClientRequest.get(`${drizzleUrl}/connect-info`)).pipe(
352 Effect.flatMap((r) => r.json),
353 )) as {
354 host: string;
355 port: number;
356 database?: string;
357 username?: string;
358 hasToken: boolean;
359 ssl: boolean;
360 canRefresh: boolean;
361 };
362 expect(info.host).toMatch(/\.rds\.amazonaws\.com$/);
363 expect(info.port).toBe(5432);
364 expect(info.database).toBe("app");
365 expect(info.username).toBe("app_iam");
366 expect(info.hasToken).toBe(true);
367 expect(info.ssl).toBe(true);
368 expect(info.canRefresh).toBe(true);
369 }),
370 { timeout: 120_000 },
371 );
372
373 test.provider.skipIf(!SLOW)(
374 "Drizzle round-trips over the IAM-auth connection URL",
375 (_stack) =>
376 Effect.gen(function* () {
377 // Socket sanity check first — TLS + token auth + in-VPC route.
378 const health = (yield* send(HttpClientRequest.get(`${drizzleUrl}/drizzle-health`)).pipe(
379 Effect.flatMap((r) => r.json),
380 )) as { rows: { one: number }[] };
381 expect(health.rows[0]?.one).toBe(1);
382
383 // Cross-path consistency: write via the Data API Lambda, read over
384 // the wire protocol from the VPC-attached Lambda.
385 yield* postJson(`${baseUrl}/insert`, { id: 60, title: "written-via-data-api" });
386 const todos = (yield* send(HttpClientRequest.get(`${drizzleUrl}/drizzle-todos`)).pipe(
387 Effect.flatMap((r) => r.json),
388 )) as { rows: { count: number }[] };
389 expect(todos.rows[0]!.count).toBeGreaterThanOrEqual(1);
390 }),
391 { timeout: 180_000 },
392 );
393 });
394
395 // `ExecuteSql` is deprecated (Aurora Serverless v1 era API) — implemented
396 // for completeness but intentionally not exercised against live AWS.
397 },
398 );