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

main
ts 251 lines 9.84 KB
Raw
1 import * as Lambda from "@alchemy.run/aws/Lambda";
2 import * as RDS from "@alchemy.run/aws/RDS";
3 import * as RDSData from "@alchemy.run/aws/RDSData";
4 import * as Duration from "effect/Duration";
5 import * as Effect from "effect/Effect";
6 import { HttpServerRequest } from "effect/http/HttpServerRequest";
7 import * as HttpServerResponse from "effect/http/HttpServerResponse";
8 import * as Layer from "effect/Layer";
9 import path from "pathe";
10 import { RDSDataInfra } from "./infra.ts";
11
12 const main = path.resolve(import.meta.dirname, "handler.ts");
13
14 export class RDSDataTestFunction extends Lambda.Function<Lambda.Function>()(
15 "RDSDataTestFunction",
16 ) {}
17
18 /**
19 * Lambda fixture for the RDS Data API bindings.
20 *
21 * Provisions an isolated network (Aurora requires a DB subnet group spanning
22 * two AZs), an ingress-free security group (the Data API is HTTP — the Lambda
23 * never opens a socket to the cluster), and an Aurora Serverless v2 postgres
24 * cluster with the Data API enabled plus a generated admin secret.
25 *
26 * One HTTP route per binding behavior; `Effect.orDie` once at the outer
27 * handler. NOTE: `ExecuteSql` is deprecated (Aurora Serverless v1 era) and is
28 * intentionally NOT exercised here.
29 */
30 export default RDSDataTestFunction.make(
31 {
32 main,
33 functionUrl: true,
34 // Data API statements can take tens of seconds while the serverless
35 // cluster scales from idle — keep the Lambda alive through that.
36 timeout: Duration.seconds(60),
37 },
38 Effect.gen(function* () {
39 // Shared Aurora fixture infra (VPC, subnets, SGs, secret, cluster,
40 // writer) — also yielded by the Drizzle IAM fixture; declarations
41 // dedupe by logical ID.
42 const { secret, cluster } = yield* RDSDataInfra;
43
44 const options = { secret, database: "app" };
45
46 const executeStatement = yield* RDSData.ExecuteStatement(cluster, options);
47 const batchExecuteStatement = yield* RDSData.BatchExecuteStatement(cluster, options);
48 const beginTransaction = yield* RDSData.BeginTransaction(cluster, options);
49 const commitTransaction = yield* RDSData.CommitTransaction(cluster, {
50 secret,
51 });
52 const rollbackTransaction = yield* RDSData.RollbackTransaction(cluster, {
53 secret,
54 });
55 // RDS.Connect resolves connection settings (endpoint + secret credentials)
56 // — no socket is opened, so it is exercisable from this ingress-free
57 // fixture alongside the Data API bindings.
58 const connect = yield* RDS.Connect(cluster, { secret, database: "app" });
59
60 const ClusterIdentifier = yield* cluster.dbClusterIdentifier;
61 const ClusterArn = yield* cluster.dbClusterArn;
62
63 return {
64 fetch: Effect.gen(function* () {
65 const request = yield* HttpServerRequest;
66 const url = new URL(request.originalUrl);
67 const pathname = url.pathname;
68
69 // Deployment metadata so the test can verify cluster deletion
70 // out-of-band after destroy.
71 if (request.method === "GET" && pathname === "/meta") {
72 const clusterIdentifier = yield* ClusterIdentifier;
73 const clusterArn = yield* ClusterArn;
74 return yield* HttpServerResponse.json({
75 clusterIdentifier,
76 clusterArn,
77 });
78 }
79
80 // RDS.Connect binding: resolves host/port from the cluster endpoint
81 // and credentials from the Secrets Manager secret. The password is
82 // never echoed back — only its presence.
83 if (request.method === "GET" && pathname === "/connect-info") {
84 const info = yield* connect;
85 return yield* HttpServerResponse.json({
86 host: info.host,
87 port: info.port,
88 database: info.database,
89 username: info.username,
90 hasPassword: typeof info.password === "string" && info.password.length > 0,
91 ssl: info.ssl,
92 });
93 }
94
95 // Cheap readiness probe (also proves ExecuteStatement end-to-end).
96 if (request.method === "GET" && pathname === "/health") {
97 const result = yield* executeStatement({ sql: "SELECT 1" });
98 return yield* HttpServerResponse.json({
99 records: result.records ?? [],
100 });
101 }
102
103 if (request.method === "POST" && pathname === "/setup") {
104 const result = yield* executeStatement({
105 sql: "CREATE TABLE IF NOT EXISTS todos (id INT PRIMARY KEY, title TEXT NOT NULL)",
106 });
107 return yield* HttpServerResponse.json({
108 success: true,
109 numberOfRecordsUpdated: result.numberOfRecordsUpdated ?? 0,
110 });
111 }
112
113 // Bootstrap the IAM-auth database user for the Drizzle fixture:
114 // `rds_iam` switches the user to token authentication, and the
115 // grants let it read the shared `todos` table. Idempotent so the
116 // suite can re-run against a standing deployment.
117 if (request.method === "POST" && pathname === "/setup-iam-user") {
118 yield* executeStatement({
119 sql: "DO $$ BEGIN CREATE USER app_iam WITH LOGIN; EXCEPTION WHEN duplicate_object THEN NULL; END $$",
120 });
121 yield* executeStatement({ sql: "GRANT rds_iam TO app_iam" });
122 yield* executeStatement({
123 sql: "GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_iam",
124 });
125 return yield* HttpServerResponse.json({ success: true });
126 }
127
128 if (request.method === "POST" && pathname === "/insert") {
129 const body = (yield* request.json) as unknown as {
130 id: number;
131 title: string;
132 };
133 const result = yield* executeStatement({
134 sql: "INSERT INTO todos (id, title) VALUES (:id, :title) ON CONFLICT (id) DO UPDATE SET title = :title",
135 parameters: [
136 { name: "id", value: { longValue: body.id } },
137 { name: "title", value: { stringValue: body.title } },
138 ],
139 });
140 return yield* HttpServerResponse.json({
141 success: true,
142 numberOfRecordsUpdated: result.numberOfRecordsUpdated ?? 0,
143 });
144 }
145
146 if (request.method === "GET" && pathname === "/select") {
147 const id = url.searchParams.get("id");
148 if (!id) {
149 return HttpServerResponse.text("Missing id", { status: 400 });
150 }
151 const result = yield* executeStatement({
152 sql: "SELECT id, title FROM todos WHERE id = :id",
153 parameters: [{ name: "id", value: { longValue: Number(id) } }],
154 });
155 return yield* HttpServerResponse.json({
156 records: result.records ?? [],
157 });
158 }
159
160 if (request.method === "GET" && pathname === "/count") {
161 const result = yield* executeStatement({
162 sql: "SELECT count(*)::int FROM todos",
163 });
164 return yield* HttpServerResponse.json({
165 records: result.records ?? [],
166 });
167 }
168
169 if (request.method === "POST" && pathname === "/batch-insert") {
170 const body = (yield* request.json) as unknown as {
171 rows: { id: number; title: string }[];
172 };
173 const result = yield* batchExecuteStatement({
174 sql: "INSERT INTO todos (id, title) VALUES (:id, :title) ON CONFLICT (id) DO UPDATE SET title = :title",
175 parameterSets: body.rows.map((row) => [
176 { name: "id", value: { longValue: row.id } },
177 { name: "title", value: { stringValue: row.title } },
178 ]),
179 });
180 return yield* HttpServerResponse.json({
181 updateResults: result.updateResults ?? [],
182 });
183 }
184
185 // Begin → insert inside the transaction → commit.
186 if (request.method === "POST" && pathname === "/tx-commit") {
187 const body = (yield* request.json) as unknown as {
188 id: number;
189 title: string;
190 };
191 const tx = yield* beginTransaction();
192 yield* executeStatement({
193 sql: "INSERT INTO todos (id, title) VALUES (:id, :title)",
194 parameters: [
195 { name: "id", value: { longValue: body.id } },
196 { name: "title", value: { stringValue: body.title } },
197 ],
198 transactionId: tx.transactionId,
199 });
200 const commit = yield* commitTransaction({
201 transactionId: tx.transactionId!,
202 });
203 return yield* HttpServerResponse.json({
204 transactionId: tx.transactionId,
205 transactionStatus: commit.transactionStatus,
206 });
207 }
208
209 // Begin → insert inside the transaction → rollback (row must vanish).
210 if (request.method === "POST" && pathname === "/tx-rollback") {
211 const body = (yield* request.json) as unknown as {
212 id: number;
213 title: string;
214 };
215 const tx = yield* beginTransaction();
216 yield* executeStatement({
217 sql: "INSERT INTO todos (id, title) VALUES (:id, :title)",
218 parameters: [
219 { name: "id", value: { longValue: body.id } },
220 { name: "title", value: { stringValue: body.title } },
221 ],
222 transactionId: tx.transactionId,
223 });
224 const rollback = yield* rollbackTransaction({
225 transactionId: tx.transactionId!,
226 });
227 return yield* HttpServerResponse.json({
228 transactionId: tx.transactionId,
229 transactionStatus: rollback.transactionStatus,
230 });
231 }
232
233 return yield* HttpServerResponse.json(
234 { error: "Not found", method: request.method, pathname },
235 { status: 404 },
236 );
237 }).pipe(Effect.orDie),
238 };
239 }).pipe(
240 Effect.provide(
241 Layer.mergeAll(
242 RDSData.ExecuteStatementHttp,
243 RDSData.BatchExecuteStatementHttp,
244 RDSData.BeginTransactionHttp,
245 RDSData.CommitTransactionHttp,
246 RDSData.RollbackTransactionHttp,
247 RDS.ConnectHttp,
248 ),
249 ),
250 ),
251 );