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

main
ts 242 lines 8.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 dsql from "@distilled.cloud/aws/dsql";
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 { Db } from "./fixtures/db";
13 import DsqlDirectFunctionLive, { DsqlDirectFunction } from "./fixtures/direct-handler";
14 import DsqlDrizzleFunctionLive, { DsqlDrizzleFunction } from "./fixtures/drizzle-handler";
15
16 // DSQL clusters are serverless and pay-per-use: provisioning reaches ACTIVE
17 // in seconds, so the FULL fixture (cluster + IAM roles + two Lambdas bundling
18 // pg/drizzle + live token-auth round-trips + destroy) measures ~30-40s wall —
19 // well inside the speed-doctrine budget, hence un-gated.
20 const testOptions = { providers: AWS.providers() };
21 const { test, beforeAll, afterAll } = Test.make(testOptions);
22 const sharedStack = Core.scratchStack(testOptions, "DSQLConnect");
23
24 let drizzleUrl: string;
25 let directUrl: string;
26 let clusterId: string | undefined;
27
28 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
29 readonly status: number;
30 readonly body: string;
31 }> {
32 override get message() {
33 return `fixture answered ${this.status}: ${this.body.slice(0, 500)}`;
34 }
35 }
36
37 class FixtureReadinessFailed extends Data.TaggedError("FixtureReadinessFailed")<{
38 readonly status: number;
39 readonly body: string;
40 }> {
41 override get message() {
42 return `fixture answered ${this.status}: ${this.body.slice(0, 500)}`;
43 }
44 }
45
46 class ClusterStillPresent extends Data.TaggedError("ClusterStillPresent")<{
47 readonly clusterId: string;
48 }> {}
49
50 // The fixtures surface every failure as a 500 (handler-level `Effect.orDie`).
51 // A 5xx here is a cold init or a first-connect transient — retry bounded;
52 // 4xx/assertion failures surface immediately.
53 const send = (request: () => HttpClientRequest.HttpClientRequest) =>
54 Effect.suspend(() => HttpClient.execute(request())).pipe(
55 Effect.flatMap((response) =>
56 response.status >= 500
57 ? response.text.pipe(
58 Effect.flatMap((body) =>
59 Effect.fail(new TransientUpstream({ status: response.status, body })),
60 ),
61 )
62 : Effect.succeed(response),
63 ),
64 Effect.retry({
65 while: (e) => e._tag === "TransientUpstream",
66 schedule: Schedule.spaced("5 seconds"),
67 times: 8,
68 }),
69 );
70
71 const postJson = (url: string, body: unknown) =>
72 send(() => HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(url), body)).pipe(
73 Effect.flatMap((r) => r.json),
74 );
75
76 const waitForFixture = (url: string) =>
77 Effect.suspend(() => HttpClient.get(url)).pipe(
78 Effect.flatMap((response) =>
79 response.status === 200
80 ? Effect.void
81 : response.text.pipe(
82 Effect.flatMap((body) => {
83 const error: TransientUpstream | FixtureReadinessFailed =
84 response.status >= 500
85 ? new TransientUpstream({ status: response.status, body })
86 : new FixtureReadinessFailed({ status: response.status, body });
87 return Effect.fail(error);
88 }),
89 ),
90 ),
91 Effect.retry({
92 while: (error) => error._tag === "TransientUpstream",
93 schedule: Schedule.spaced("5 seconds"),
94 times: 18,
95 }),
96 );
97
98 describe(
99 "DSQL.Connect",
100 { tags: ["provider:aws", "provider:aws:dsql", "provider:aws:lambda", "live"] },
101 () => {
102 beforeAll(
103 Effect.gen(function* () {
104 yield* Effect.logInfo("DSQL.Connect setup: destroying previous resources");
105 yield* sharedStack.destroy();
106
107 yield* Effect.logInfo("DSQL.Connect setup: deploying DSQL cluster + 2 Lambda fixtures");
108 const outputs = yield* sharedStack.deploy(
109 Effect.gen(function* () {
110 const cluster = yield* Db;
111 const drizzleFn = yield* DsqlDrizzleFunction;
112 const directFn = yield* DsqlDirectFunction;
113 return {
114 clusterId: cluster.clusterId,
115 drizzleUrl: drizzleFn.functionUrl,
116 directUrl: directFn.functionUrl,
117 };
118 }).pipe(Effect.provide(Layer.mergeAll(DsqlDrizzleFunctionLive, DsqlDirectFunctionLive))),
119 );
120
121 expect(outputs.drizzleUrl).toBeTruthy();
122 expect(outputs.directUrl).toBeTruthy();
123 drizzleUrl = outputs.drizzleUrl!.replace(/\/+$/, "");
124 directUrl = outputs.directUrl!.replace(/\/+$/, "");
125 clusterId = outputs.clusterId;
126
127 // Function URL propagation + cold start + first token-auth connect.
128 // Bounded: retry transient 5xx responses for at most 90 seconds. Each
129 // attempt creates a fresh request; non-transient statuses fail directly.
130 yield* waitForFixture(`${drizzleUrl}/health`);
131 yield* Effect.logInfo(`DSQL.Connect setup: fixtures ready (cluster ${clusterId})`);
132 }),
133 { timeout: 900_000 },
134 );
135
136 afterAll(
137 Effect.gen(function* () {
138 yield* sharedStack.destroy();
139
140 // Out-of-band deletion check via distilled — a deleted DSQL
141 // cluster is gone or reports DELETING/DELETED.
142 if (clusterId) {
143 yield* Core.withProviders(
144 dsql.getCluster({ identifier: clusterId }).pipe(
145 Effect.flatMap((cluster) =>
146 cluster.status === "DELETING" || cluster.status === "DELETED"
147 ? Effect.void
148 : Effect.fail(new ClusterStillPresent({ clusterId: clusterId! })),
149 ),
150 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
151 Effect.retry({
152 while: (e) => e._tag === "ClusterStillPresent",
153 schedule: Schedule.max([Schedule.spaced("5 seconds"), Schedule.recurs(12)]),
154 }),
155 ),
156 testOptions,
157 sharedStack.name,
158 );
159 }
160 }),
161 { timeout: 900_000 },
162 );
163
164 test.provider(
165 "Drizzle over DSQL.Connect round-trips CREATE TABLE / INSERT / SELECT",
166 (_stack) =>
167 Effect.gen(function* () {
168 const setup = (yield* postJson(`${drizzleUrl}/setup`, {})) as { success: boolean };
169 expect(setup.success).toBe(true);
170
171 const insert = (yield* postJson(`${drizzleUrl}/insert`, { id: 1, title: "first" })) as {
172 success: boolean;
173 };
174 expect(insert.success).toBe(true);
175
176 const select = (yield* send(() =>
177 HttpClientRequest.get(`${drizzleUrl}/select?id=1`),
178 ).pipe(Effect.flatMap((r) => r.json))) as { rows: { id: number; title: string }[] };
179 expect(select.rows).toHaveLength(1);
180 expect(select.rows[0]).toEqual({ id: 1, title: "first" });
181 }),
182 { timeout: 180_000 },
183 );
184
185 test.provider(
186 "resolves connection info with a fresh IAM auth token",
187 (_stack) =>
188 Effect.gen(function* () {
189 const info = (yield* send(() => HttpClientRequest.get(`${directUrl}/info`)).pipe(
190 Effect.flatMap((r) => r.json),
191 )) as {
192 host: string;
193 port: number;
194 database?: string;
195 username?: string;
196 hasPassword: boolean;
197 ssl: boolean;
198 urlScheme: string;
199 };
200 expect(info.host).toMatch(/^[a-z0-9]+\.dsql\.[a-z0-9-]+\.on\.aws$/);
201 expect(info.port).toBe(5432);
202 expect(info.database).toBe("postgres");
203 expect(info.username).toBe("admin");
204 expect(info.hasPassword).toBe(true);
205 expect(info.ssl).toBe(true);
206 expect(info.urlScheme).toBe("postgresql");
207 }),
208 { timeout: 180_000 },
209 );
210
211 test.provider(
212 "GetVpcEndpointServiceName binding resolves the PrivateLink service name",
213 (_stack) =>
214 Effect.gen(function* () {
215 const response = (yield* send(() =>
216 HttpClientRequest.get(`${directUrl}/vpc-endpoint-service`),
217 ).pipe(Effect.flatMap((r) => r.json))) as {
218 serviceName: string;
219 clusterVpcEndpoint: string | null;
220 };
221 expect(response.serviceName).toMatch(/^com\.amazonaws\./);
222 expect(response.serviceName).toContain("dsql");
223 }),
224 { timeout: 180_000 },
225 );
226
227 test.provider(
228 "connects DIRECTLY to the public endpoint (raw @effect/sql-pg, no Drizzle, no VPC)",
229 (_stack) =>
230 Effect.gen(function* () {
231 const roundtrip = (yield* postJson(`${directUrl}/roundtrip`, {})) as {
232 rows: { id: number; title: string }[];
233 host: string;
234 };
235 expect(roundtrip.host).toMatch(/\.dsql\./);
236 expect(roundtrip.rows).toHaveLength(1);
237 expect(roundtrip.rows[0]).toEqual({ id: 1, title: "direct" });
238 }),
239 { timeout: 180_000 },
240 );
241 },
242 );