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

main
ts 384 lines 14.3 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import type * as rdsdata from "@distilled.cloud/aws/rds-data";
3 import type { RuntimeContext } from "alchemy";
4 import * as Effect from "effect/Effect";
5 import * as Layer from "effect/Layer";
6 import * as Schedule from "effect/Schedule";
7 import type * as Scope from "effect/Scope";
8 import { Database, type DatabaseService, type DirectDatabase } from "./Database.ts";
9 import { BetterAuthMigrationError } from "./Errors.ts";
10
11 /**
12 * Minimal shape of the RDS Data API surface the Kysely dialect drives —
13 * promise-based so the same dialect serves the runtime (backed by the
14 * `AWS.RDSData.*` bindings) and deploy-time migrations (backed by
15 * distilled with ambient credentials).
16 *
17 * @internal
18 */
19 export interface DataApiExecutor {
20 readonly execute: (request: {
21 sql: string;
22 parameters?: rdsdata.SqlParameter[];
23 includeResultMetadata?: boolean;
24 transactionId?: string;
25 }) => Promise<DataApiResponse>;
26 readonly begin: () => Promise<{ transactionId?: string }>;
27 readonly commit: (transactionId: string) => Promise<unknown>;
28 readonly rollback: (transactionId: string) => Promise<unknown>;
29 }
30
31 interface DataApiResponse {
32 records?: rdsdata.Field[][];
33 columnMetadata?: rdsdata.ColumnMetadata[];
34 numberOfRecordsUpdated?: number;
35 }
36
37 /**
38 * Build a Kysely dialect over the RDS Data API.
39 *
40 * Postgres-flavoured, with `$n` placeholders rewritten to the Data API's
41 * named `:n` parameters. Streaming is unsupported (the Data API is
42 * request/response).
43 *
44 * @internal
45 */
46 export const makeDataApiDialect = (
47 executor: DataApiExecutor,
48 ): Effect.Effect<import("kysely").Dialect> =>
49 Effect.promise(async () => {
50 const {
51 CastNode,
52 DataTypeNode,
53 OperationNodeTransformer,
54 PostgresAdapter,
55 PostgresIntrospector,
56 PostgresQueryCompiler,
57 ReferenceNode,
58 } = await import("kysely");
59
60 class DataApiIntrospectionTransformer extends OperationNodeTransformer {
61 protected override transformAlias(node: import("kysely").AliasNode) {
62 const alias = super.transformAlias(node);
63 const reference = alias.node;
64 if (
65 ReferenceNode.is(reference) &&
66 reference.column.kind === "ColumnNode" &&
67 reference.column.column.name === "relkind"
68 ) {
69 // The Data API cannot return PostgreSQL's internal "char" type.
70 return {
71 ...alias,
72 node: CastNode.create(reference, DataTypeNode.create("text")),
73 };
74 }
75 return alias;
76 }
77 }
78
79 const introspectionTransformer = new DataApiIntrospectionTransformer();
80 const introspectionPlugin: import("kysely").KyselyPlugin = {
81 transformQuery: ({ node }) => introspectionTransformer.transformNode(node),
82 transformResult: async ({ result }) => result,
83 };
84
85 class DataApiQueryCompiler extends PostgresQueryCompiler {
86 protected override getCurrentParameterPlaceholder(): string {
87 return `:${this.numParameters}`;
88 }
89 }
90
91 class DataApiConnection {
92 transactionId: string | undefined;
93
94 async executeQuery(compiledQuery: { sql: string; parameters: ReadonlyArray<unknown> }) {
95 const response = await executor.execute({
96 sql: compiledQuery.sql,
97 parameters: compiledQuery.parameters.map((value, index) =>
98 AWS.RDSData.toSqlParameter(`${index + 1}`, value),
99 ),
100 includeResultMetadata: true,
101 ...(this.transactionId === undefined ? {} : { transactionId: this.transactionId }),
102 });
103 return {
104 rows: AWS.RDSData.toRows(response) as never[],
105 numAffectedRows: BigInt(response.numberOfRecordsUpdated ?? 0),
106 };
107 }
108
109 async *streamQuery(): AsyncIterableIterator<never> {
110 throw new Error("RDS Data API does not support streaming queries");
111 }
112 }
113
114 class DataApiDriver {
115 async init() {}
116 async acquireConnection() {
117 return new DataApiConnection();
118 }
119 async beginTransaction(connection: DataApiConnection) {
120 const { transactionId } = await executor.begin();
121 connection.transactionId = transactionId;
122 }
123 async commitTransaction(connection: DataApiConnection) {
124 if (connection.transactionId !== undefined) {
125 await executor.commit(connection.transactionId);
126 connection.transactionId = undefined;
127 }
128 }
129 async rollbackTransaction(connection: DataApiConnection) {
130 if (connection.transactionId !== undefined) {
131 await executor.rollback(connection.transactionId);
132 connection.transactionId = undefined;
133 }
134 }
135 async releaseConnection() {}
136 async destroy() {}
137 }
138
139 return {
140 createAdapter: () => new PostgresAdapter(),
141 createDriver: () => new DataApiDriver(),
142 createQueryCompiler: () => new DataApiQueryCompiler(),
143 createIntrospector: (db: import("kysely").Kysely<unknown>) =>
144 new PostgresIntrospector(db.withPlugin(introspectionPlugin)),
145 } as unknown as import("kysely").Dialect;
146 });
147
148 export interface AuroraDataApiOptions {
149 /**
150 * Secrets Manager secret holding the database credentials. Required when
151 * passing a bare `DBCluster`; defaults to the composite's `secret` when
152 * passing an `AWS.RDS.Aurora` result.
153 */
154 readonly secret?: AWS.SecretsManager.Secret;
155 /** Database name inside the cluster. */
156 readonly database?: string;
157 /**
158 * Deploy-time automatic migration (over the Data API with ambient
159 * credentials). `false` disables.
160 * @default enabled
161 */
162 readonly migrate?: false;
163 }
164
165 /** The `AWS.RDS.Aurora` composite pieces this layer consumes. */
166 interface AuroraLike {
167 readonly cluster: AWS.RDS.DBCluster;
168 readonly secret: AWS.SecretsManager.Secret;
169 readonly writer: AWS.RDS.DBInstance;
170 }
171
172 const isAuroraLike = (value: object): value is AuroraLike =>
173 "cluster" in value && "secret" in value && "writer" in value;
174
175 /**
176 * A freshly-created cluster answers `DatabaseNotFoundException` until its
177 * writer instance registers, and a Serverless v2 cluster answers
178 * `DatabaseResumingException` while scaling from zero — both transient.
179 * Bounded per the speed doctrine (~1 minute of backoff).
180 */
181 const transientRetry = <A, E extends { _tag: string }, R>(
182 effect: Effect.Effect<A, E, R>,
183 ): Effect.Effect<A, E, R> =>
184 effect.pipe(
185 Effect.retry({
186 while: (error) =>
187 error._tag === "DatabaseResumingException" || error._tag === "DatabaseNotFoundException",
188 schedule: Schedule.exponential("2 seconds", 1.5),
189 times: 8,
190 }),
191 );
192
193 /**
194 * Aurora (RDS Data API) database layer for Better Auth — the optimal
195 * Lambda → Aurora pairing: SQL over HTTPS with IAM auth, no VPC
196 * attachment, no `pg`, no connection pooling concerns.
197 *
198 * Runtime access flows through the `AWS.RDSData.*` bindings, which grant
199 * the host `rds-data:*` + `secretsmanager:GetSecretValue` IAM and inject
200 * the cluster/secret ARNs. Requires the cluster to have the Data API
201 * enabled (`AWS.RDS.Aurora` enables it by default).
202 *
203 *
204 * ### Lambda with an Aurora-backed BetterAuth
205 * Pass the `AWS.RDS.Aurora` composite directly — the layer wires the
206 * cluster, credentials secret, and the writer-instance dependency (so
207 * deploy-time migrations wait for the cluster to be queryable) from one
208 * value.
209 * **Example:** Function URL serving auth over the Data API
210 * ```typescript
211 * import { BetterAuth } from "@alchemy.run/better-auth";
212 * import { AuroraDataApi } from "@alchemy.run/better-auth/AuroraDataApi";
213 * import * as AWS from "@alchemy.run/aws";
214 *
215 * export const Db = AWS.RDS.Aurora("AuthDb", { subnetIds, securityGroupIds });
216 *
217 * export default AuthFunction.make(
218 * { main, url: true, memorySize: 512 },
219 * Effect.gen(function* () {
220 * const auth = yield* BetterAuth({ emailAndPassword: { enabled: true } });
221 * return { fetch: ... };
222 * }).pipe(Effect.provide(AuroraDataApi(Db, { database: "postgres" }))),
223 * );
224 * ```
225 *
226 * ### Serverless v2 scale-from-zero
227 * A paused cluster answers `DatabaseResumingException` while waking; the
228 * layer retries the transient window with bounded backoff at both deploy
229 * and runtime.
230 * **Example:** Bare cluster + explicit secret
231 * ```typescript
232 * AuroraDataApi(cluster, { secret, database: "auth" })
233 * ```
234 *
235 * @layer
236 * @provides BetterAuth.Database
237 * @peer kysely
238 * @peer @distilled.cloud/aws
239 * @product Aurora
240 */
241 export const AuroraDataApi = (
242 cluster:
243 | AWS.RDS.DBCluster
244 | AuroraLike
245 | Effect.Effect<AWS.RDS.DBCluster | AuroraLike, never, any>,
246 options?: AuroraDataApiOptions,
247 ) =>
248 Layer.effect(
249 Database,
250 Effect.gen(function* () {
251 const source = Effect.isEffect(cluster)
252 ? yield* cluster as Effect.Effect<AWS.RDS.DBCluster | AuroraLike>
253 : cluster;
254 const composite = isAuroraLike(source) ? source : undefined;
255 const db = composite?.cluster ?? (source as AWS.RDS.DBCluster);
256 const secret = options?.secret ?? composite?.secret;
257 if (secret === undefined) {
258 return yield* Effect.die(
259 new Error(
260 "AuroraDataApi: pass the AWS.RDS.Aurora composite, or a DBCluster together with `options.secret`.",
261 ),
262 );
263 }
264 const bindingOptions = {
265 secret,
266 ...(options?.database === undefined ? {} : { database: options.database }),
267 };
268 const executeStatement = yield* AWS.RDSData.ExecuteStatement(db, bindingOptions);
269 const beginTransaction = yield* AWS.RDSData.BeginTransaction(db, bindingOptions);
270 const commitTransaction = yield* AWS.RDSData.CommitTransaction(db, bindingOptions);
271 const rollbackTransaction = yield* AWS.RDSData.RollbackTransaction(db, bindingOptions);
272
273 const runtime = Effect.gen(function* () {
274 const context = yield* Effect.context<RuntimeContext>();
275 const run = <A, E>(effect: Effect.Effect<A, E, RuntimeContext>): Promise<A> =>
276 Effect.runPromiseWith(context)(effect);
277 const dialect = yield* makeDataApiDialect({
278 execute: (request) =>
279 executeStatement(request as AWS.RDSData.ExecuteStatementRequest).pipe(
280 transientRetry,
281 run,
282 ),
283 begin: () => beginTransaction().pipe(transientRetry, run),
284 commit: (transactionId) => run(commitTransaction({ transactionId })),
285 rollback: (transactionId) => run(rollbackTransaction({ transactionId })),
286 });
287 return { dialect, type: "postgres" as const };
288 });
289
290 const service: DatabaseService = {
291 provider: "postgres",
292 runtime: runtime as DatabaseService["runtime"],
293 };
294
295 // Deploy-time migrations call the Data API through distilled with the
296 // ambient stack credentials (mirroring D1's deploy-time HTTP client).
297 // DCE'd from runtime bundles.
298 if (!globalThis.__ALCHEMY_RUNTIME__ && options?.migrate !== false) {
299 return {
300 ...service,
301 migrate: {
302 identity: {
303 clusterArn: db.dbClusterArn,
304 // depend on the WRITER instance too: a cluster with no
305 // registered instance answers DatabaseNotFoundException
306 ...(composite === undefined ? {} : { writerArn: composite.writer.dbInstanceArn }),
307 } as Record<string, unknown>,
308 connect: Effect.gen(function* () {
309 // Init half — capture the ARNs as Action dependencies.
310 const clusterArn = yield* db.dbClusterArn;
311 const secretArn = yield* secret.secretArn;
312 if (composite !== undefined) {
313 // capture-only: the migration must wait for the writer
314 yield* composite.writer.dbInstanceArn.asEffect().pipe(Effect.asVoid);
315 }
316 const ambient = yield* Effect.context<never>();
317 // Apply half — Data API dialect over distilled.
318 return Effect.gen(function* () {
319 const resourceArn = yield* clusterArn;
320 const resolvedSecretArn = yield* secretArn;
321 const rdsdata = yield* Effect.promise(
322 () => import("@distilled.cloud/aws/rds-data"),
323 );
324 const base = {
325 resourceArn,
326 secretArn: resolvedSecretArn,
327 ...(options?.database === undefined ? {} : { database: options.database }),
328 };
329 const run = <A>(effect: Effect.Effect<A, any, any>) =>
330 Effect.runPromiseWith(ambient)(effect as Effect.Effect<A, any, never>);
331 const dialect = yield* makeDataApiDialect({
332 execute: (request) =>
333 rdsdata
334 .executeStatement({
335 ...base,
336 ...request,
337 } as never)
338 .pipe(transientRetry, run),
339 begin: () => rdsdata.beginTransaction(base).pipe(transientRetry, run),
340 commit: (transactionId) =>
341 run(
342 rdsdata.commitTransaction({
343 resourceArn,
344 secretArn: resolvedSecretArn,
345 transactionId,
346 }),
347 ),
348 rollback: (transactionId) =>
349 run(
350 rdsdata.rollbackTransaction({
351 resourceArn,
352 secretArn: resolvedSecretArn,
353 transactionId,
354 }),
355 ),
356 });
357 return { dialect, type: "postgres" } as DirectDatabase;
358 }).pipe(
359 Effect.catchDefect((cause: unknown) =>
360 Effect.fail(
361 new BetterAuthMigrationError({
362 message:
363 "Failed to reach the Aurora Data API for Better Auth schema migrations",
364 cause,
365 }),
366 ),
367 ),
368 );
369 }) as Effect.Effect<
370 Effect.Effect<DirectDatabase, BetterAuthMigrationError, Scope.Scope>,
371 never,
372 RuntimeContext
373 >,
374 },
375 } satisfies DatabaseService;
376 }
377 return service;
378 }),
379 ).pipe(
380 Layer.provide(AWS.RDSData.ExecuteStatementHttp),
381 Layer.provide(AWS.RDSData.BeginTransactionHttp),
382 Layer.provide(AWS.RDSData.CommitTransactionHttp),
383 Layer.provide(AWS.RDSData.RollbackTransactionHttp),
384 );