| 1 | import { Connect, ConnectHttp, connectEnvKeys } from "@/Neon/Connect"; |
| 2 | import { CurrentRuntimeContext } from "@/RuntimeContext"; |
| 3 | import { Postgres } from "@/SQL/Postgres"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as Cause from "effect/Cause"; |
| 6 | import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 7 | import { ConnectBranch, ConnectProject } from "./connect-database.ts"; |
| 8 | |
| 9 | export const connectHandler = Effect.gen(function* () { |
| 10 | const context = yield* CurrentRuntimeContext; |
| 11 | if (!context) |
| 12 | return yield* Effect.die(new Error("Connect fixture requires a host")); |
| 13 | const branchResource = yield* ConnectBranch; |
| 14 | const keys = connectEnvKeys(branchResource); |
| 15 | const branch = yield* Connect(branchResource); |
| 16 | const projectResource = yield* ConnectProject; |
| 17 | const projectKeys = connectEnvKeys(projectResource); |
| 18 | const project = yield* Connect(projectResource); |
| 19 | const pooled = yield* Postgres({ url: branch.connectionString }); |
| 20 | const direct = yield* Postgres({ url: branch.directConnectionString }); |
| 21 | const parent = yield* Postgres({ url: project.pooledConnectionString }); |
| 22 | return { |
| 23 | fetch: Effect.gen(function* () { |
| 24 | const rows = |
| 25 | yield* pooled`SELECT current_database() AS database, value FROM alchemy_connect_marker`; |
| 26 | const directRows = |
| 27 | yield* direct`SELECT current_database() AS database, value FROM alchemy_connect_marker`; |
| 28 | const parentRows = |
| 29 | yield* parent`SELECT current_database() AS database, value FROM alchemy_connect_marker`; |
| 30 | const accountKey = yield* context.get<string>("NEON_API_KEY"); |
| 31 | return yield* HttpServerResponse.json({ |
| 32 | database: rows[0]?.database, |
| 33 | directDatabase: directRows[0]?.database, |
| 34 | parentDatabase: parentRows[0]?.database, |
| 35 | branchMarker: rows[0]?.value, |
| 36 | directMarker: directRows[0]?.value, |
| 37 | parentMarker: parentRows[0]?.value, |
| 38 | hasAccountKey: accountKey !== undefined, |
| 39 | injected: yield* context.get<boolean>(keys.injected), |
| 40 | parentInjected: yield* context.get<boolean>(projectKeys.injected), |
| 41 | }); |
| 42 | }).pipe( |
| 43 | Effect.catchCause((cause) => |
| 44 | HttpServerResponse.json({ |
| 45 | error: Cause.pretty(cause).replace( |
| 46 | /postgres(?:ql)?:\/\/[^\s"']+/g, |
| 47 | "<redacted-database-url>", |
| 48 | ), |
| 49 | }), |
| 50 | ), |
| 51 | Effect.orDie, |
| 52 | ), |
| 53 | }; |
| 54 | }).pipe(Effect.provide(ConnectHttp)); |