1import * as DSQL from "@/AWS/DSQL";
2import * as Lambda from "@/AWS/Lambda";
3import * as PgClient from "@effect/sql-pg/PgClient";
4import * as Context from "effect/Context";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as Layer from "effect/Layer";
8import * as Redacted from "effect/Redacted";
9import { HttpServerRequest } from "effect/http/HttpServerRequest";
10import * as HttpServerResponse from "effect/http/HttpServerResponse";
11import path from "pathe";
12import { Db } from "./db.ts";
13
14const main = path.resolve(import.meta.dirname, "direct-handler.ts");
15
16export class DsqlDirectFunction extends Lambda.Function<Lambda.Function>()(
17 "DsqlDirectFunction",
18) {}
19
20/**
21 * Lambda fixture proving the DIRECT public-endpoint path: a raw Postgres
22 * client (`@effect/sql-pg`, no Drizzle, no Hyperdrive, no VPC) connects to
23 * `<clusterId>.dsql.<region>.on.aws:5432` over TLS with the IAM auth token
24 * that `DSQL.Connect` mints as the password.
25 */
26export default DsqlDirectFunction.make(
27 {
28 main,
29 functionUrl: true,
30 timeout: Duration.seconds(30),
31 // Preserve `pg` as CommonJS in node_modules; bundling it rewrites the
32 // Client constructor into a namespace object and crashes Lambda init.
33 build: { install: ["pg"] },
34 },
35 Effect.gen(function* () {
36 const cluster = yield* Db;
37 const conn = yield* DSQL.Connect(cluster, { admin: true });
38 const getVpcEndpointServiceName =
39 yield* DSQL.GetVpcEndpointServiceName(cluster);
40
41 return {
42 fetch: Effect.gen(function* () {
43 const request = yield* HttpServerRequest;
44 const url = new URL(request.originalUrl);
45 const pathname = url.pathname;
46
47 // PrivateLink service-name lookup via the management binding.
48 if (request.method === "GET" && pathname === "/vpc-endpoint-service") {
49 const { serviceName, clusterVpcEndpoint } =
50 yield* getVpcEndpointServiceName();
51 return yield* HttpServerResponse.json({
52 serviceName,
53 clusterVpcEndpoint: clusterVpcEndpoint ?? null,
54 });
55 }
56
57 // Connection descriptor shape — no socket opened. The password
58 // (auth token) is never echoed, only its presence.
59 if (request.method === "GET" && pathname === "/info") {
60 const info = yield* conn;
61 return yield* HttpServerResponse.json({
62 host: info.host,
63 port: info.port,
64 database: info.database,
65 username: info.username,
66 hasPassword:
67 info.password !== undefined &&
68 Redacted.value(info.password).length > 0,
69 ssl: info.ssl,
70 urlScheme: Redacted.value(info.url).split("://")[0],
71 });
72 }
73
74 // Full round-trip over the public endpoint: mint token, open a TLS
75 // socket, CREATE TABLE / INSERT / SELECT. The pool is built on the
76 // per-event scope (`Layer.build` + ambient request Scope), so it is
77 // closed when the invocation settles.
78 if (request.method === "POST" && pathname === "/roundtrip") {
79 const info = yield* conn;
80 // Plain `PgClient` over the DSQL URL (`sslmode=require`): DSQL
81 // routes on TLS SNI, which `@effect/sql-pg` ≥ rc.115 sends for
82 // DNS hosts by default (Effect-TS/effect#8174).
83 const ctx = yield* Layer.build(PgClient.layer({ url: info.url }));
84 const sqlClient = Context.get(ctx, PgClient.PgClient);
85 // DSQL runs DDL as its own autocommit statement (no DDL+DML
86 // transactions) — each call below is a separate statement.
87 yield* sqlClient`CREATE TABLE IF NOT EXISTS dsql_direct_widgets (id integer PRIMARY KEY, title text NOT NULL)`;
88 yield* sqlClient`DELETE FROM dsql_direct_widgets WHERE id = 1`;
89 yield* sqlClient`INSERT INTO dsql_direct_widgets (id, title) VALUES (1, 'direct')`;
90 const rows =
91 yield* sqlClient`SELECT id, title FROM dsql_direct_widgets WHERE id = 1`;
92 return yield* HttpServerResponse.json({ rows, host: info.host });
93 }
94
95 return yield* HttpServerResponse.json(
96 { error: "Not found", method: request.method, pathname },
97 { status: 404 },
98 );
99 }).pipe(Effect.orDie),
100 };
101 }).pipe(
102 Effect.provide(
103 Layer.mergeAll(DSQL.ConnectHttp, DSQL.GetVpcEndpointServiceNameHttp),
104 ),
105 ),
106);