The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Binding from "alchemy/Binding"; |
| 2 | import * as Output from "alchemy/Output"; |
| 3 | import { CurrentRuntimeContext, RuntimeContext } from "alchemy/RuntimeContext"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import { identity } from "effect/Function"; |
| 6 | import * as Layer from "effect/Layer"; |
| 7 | import * as Redacted from "effect/Redacted"; |
| 8 | import type { Connection } from "./Connection.ts"; |
| 9 | import { envName } from "./internal/EnvName.ts"; |
| 10 | |
| 11 | /** |
| 12 | * The typed runtime client returned by {@link Connect}. |
| 13 | */ |
| 14 | export interface ConnectClient { |
| 15 | /** |
| 16 | * Conventional application database URL, redacted. |
| 17 | * |
| 18 | * Resolves to the pooled Postgres URL first, then direct Postgres, then |
| 19 | * Accelerate — the serverless-safe default for application traffic. Dies |
| 20 | * with a descriptive defect when the connection carries no URL at all. |
| 21 | * |
| 22 | * Feed it straight into `SQL.Postgres` / `Drizzle.Postgres`: |
| 23 | * |
| 24 | * ```typescript |
| 25 | * const db = yield* Prisma.Connect(connection); |
| 26 | * const sql = yield* SQL.Postgres({ url: db.databaseUrl }); |
| 27 | * ``` |
| 28 | */ |
| 29 | databaseUrl: Effect.Effect<Redacted.Redacted<string>, never, RuntimeContext>; |
| 30 | /** |
| 31 | * Prisma connection/API key ID. |
| 32 | */ |
| 33 | connectionId: Effect.Effect<string, never, RuntimeContext>; |
| 34 | /** |
| 35 | * Database ID this connection belongs to. |
| 36 | */ |
| 37 | databaseId: Effect.Effect<string, never, RuntimeContext>; |
| 38 | /** |
| 39 | * Direct Postgres connection string, when available. |
| 40 | */ |
| 41 | directConnectionString: Effect.Effect< |
| 42 | Redacted.Redacted<string> | undefined, |
| 43 | never, |
| 44 | RuntimeContext |
| 45 | >; |
| 46 | /** |
| 47 | * Pooled Prisma Postgres connection string, when available. |
| 48 | */ |
| 49 | pooledConnectionString: Effect.Effect< |
| 50 | Redacted.Redacted<string> | undefined, |
| 51 | never, |
| 52 | RuntimeContext |
| 53 | >; |
| 54 | /** |
| 55 | * Accelerate connection string, when available. |
| 56 | */ |
| 57 | accelerateConnectionString: Effect.Effect< |
| 58 | Redacted.Redacted<string> | undefined, |
| 59 | never, |
| 60 | RuntimeContext |
| 61 | >; |
| 62 | /** |
| 63 | * Direct database host, when available. |
| 64 | */ |
| 65 | host: Effect.Effect<string | null | undefined, never, RuntimeContext>; |
| 66 | /** |
| 67 | * Direct database user, when available. |
| 68 | */ |
| 69 | user: Effect.Effect<string | null | undefined, never, RuntimeContext>; |
| 70 | /** |
| 71 | * Direct database password, when available. |
| 72 | */ |
| 73 | password: Effect.Effect<Redacted.Redacted<string> | undefined, never, RuntimeContext>; |
| 74 | } |
| 75 | |
| 76 | /** |
| 77 | * Bind a {@link Connection} to any Function or Worker host (a Prisma |
| 78 | * Compute app, AWS Lambda Function, Cloudflare Worker or Container, …) and |
| 79 | * obtain the typed runtime client. |
| 80 | * |
| 81 | * `Connect` is a single identifier that is simultaneously the binding's |
| 82 | * Context tag, its type, and the callable — |
| 83 | * `yield* Prisma.Connect(connection)`. |
| 84 | * |
| 85 | * Provide `Prisma.ConnectBinding` on the host implementation so Alchemy can |
| 86 | * register the deploy-time binding and resolve the client at runtime. |
| 87 | * |
| 88 | * ### Binding a Connection |
| 89 | * **Example:** Use a connection inside Prisma Compute |
| 90 | * ```typescript |
| 91 | * export default Prisma.Compute( |
| 92 | * "api", |
| 93 | * { project, main: import.meta.filename }, |
| 94 | * Effect.gen(function* () { |
| 95 | * const db = yield* Prisma.Connect(connection); |
| 96 | * const sql = yield* SQL.Postgres({ url: db.databaseUrl }); |
| 97 | * |
| 98 | * return { |
| 99 | * fetch: Effect.gen(function* () { |
| 100 | * const users = yield* sql`SELECT * FROM users`; |
| 101 | * return yield* HttpServerResponse.json(users); |
| 102 | * }), |
| 103 | * }; |
| 104 | * }).pipe(Effect.provide(Prisma.ConnectBinding)), |
| 105 | * ); |
| 106 | * ``` |
| 107 | * |
| 108 | * **Example:** Use a connection inside a Cloudflare Container |
| 109 | * ```typescript |
| 110 | * export default Api.make( |
| 111 | * { main: import.meta.url }, |
| 112 | * Effect.gen(function* () { |
| 113 | * const db = yield* Prisma.Connect(connection); |
| 114 | * const sql = yield* SQL.Postgres({ url: db.databaseUrl }); |
| 115 | * |
| 116 | * return Api.of({ |
| 117 | * fetch: Effect.gen(function* () { |
| 118 | * const users = yield* sql`SELECT * FROM users`; |
| 119 | * return yield* HttpServerResponse.json(users); |
| 120 | * }), |
| 121 | * }); |
| 122 | * }).pipe(Effect.provide(Prisma.ConnectBinding)), |
| 123 | * ); |
| 124 | * ``` |
| 125 | * |
| 126 | * A container is a real process with no workerd bindings, so the connection |
| 127 | * travels as plain environment variables — the same channel Prisma Compute |
| 128 | * and Lambda use. Start the container with |
| 129 | * `api.start({ enableInternet: true })` so it can reach the database. (Hyperdrive, by contrast, is a workerd binding and is |
| 130 | * unavailable inside a container.) |
| 131 | * |
| 132 | * @binding |
| 133 | * @product Postgres |
| 134 | */ |
| 135 | export interface Connect extends Binding.Service< |
| 136 | Connect, |
| 137 | "Prisma.Connect", |
| 138 | (connection: Connection) => Effect.Effect<ConnectClient> |
| 139 | > {} |
| 140 | |
| 141 | export const Connect = Binding.Service<Connect>("Prisma.Connect"); |
| 142 | |
| 143 | export interface ConnectEnvKeys { |
| 144 | connectionId: string; |
| 145 | databaseId: string; |
| 146 | directConnectionString: string; |
| 147 | pooledConnectionString: string; |
| 148 | accelerateConnectionString: string; |
| 149 | host: string; |
| 150 | user: string; |
| 151 | password: string; |
| 152 | } |
| 153 | |
| 154 | /** |
| 155 | * Derive the env var names {@link Connect} uses to carry a Connection's |
| 156 | * outputs into the host runtime. |
| 157 | */ |
| 158 | export const connectEnvKeys = ( |
| 159 | connection: Pick<Connection, "FQN" | "LogicalId">, |
| 160 | ): ConnectEnvKeys => { |
| 161 | const name = connection.FQN === connection.LogicalId ? connection.LogicalId : connection.FQN; |
| 162 | const prefix = `PRISMA_${envName(name)}`; |
| 163 | return { |
| 164 | connectionId: `${prefix}_CONNECTION_ID`, |
| 165 | databaseId: `${prefix}_DATABASE_ID`, |
| 166 | directConnectionString: `${prefix}_DIRECT_CONNECTION_STRING`, |
| 167 | pooledConnectionString: `${prefix}_POOLED_CONNECTION_STRING`, |
| 168 | accelerateConnectionString: `${prefix}_ACCELERATE_CONNECTION_STRING`, |
| 169 | host: `${prefix}_HOST`, |
| 170 | user: `${prefix}_USER`, |
| 171 | password: `${prefix}_PASSWORD`, |
| 172 | }; |
| 173 | }; |
| 174 | |
| 175 | // Compute env sync omits undefined and treats null as deletion. Connection |
| 176 | // bindings need both values to round-trip into the typed runtime client. |
| 177 | const ENCODED_CONNECTION_PREFIX = "__ALCHEMY_PRISMA_CONNECTION_VALUE__:"; |
| 178 | |
| 179 | type EncodedConnectionValue = |
| 180 | | { readonly kind: "undefined" } |
| 181 | | { readonly kind: "null" } |
| 182 | | { readonly kind: "value"; readonly value: string }; |
| 183 | |
| 184 | const encodeConnectionValue = (value: EncodedConnectionValue) => |
| 185 | `${ENCODED_CONNECTION_PREFIX}${JSON.stringify(value)}`; |
| 186 | |
| 187 | const escapePrefixedValue = <A extends string | Redacted.Redacted<string>>( |
| 188 | value: A, |
| 189 | ): A | string | Redacted.Redacted<string> => { |
| 190 | const raw = typeof value === "string" ? value : String(Redacted.value(value)); |
| 191 | if (!raw.startsWith(ENCODED_CONNECTION_PREFIX)) return value; |
| 192 | const encoded = encodeConnectionValue({ kind: "value", value: raw }); |
| 193 | return Redacted.isRedacted(value) ? Redacted.make(encoded) : encoded; |
| 194 | }; |
| 195 | |
| 196 | const encodeOptionalValue = <A extends string | Redacted.Redacted<string>>( |
| 197 | output: Output.Output<A | null | undefined>, |
| 198 | ): Output.Output<A | string | Redacted.Redacted<string>> => |
| 199 | output.pipe( |
| 200 | Output.map((value) => |
| 201 | value === undefined |
| 202 | ? encodeConnectionValue({ kind: "undefined" }) |
| 203 | : value === null |
| 204 | ? encodeConnectionValue({ kind: "null" }) |
| 205 | : escapePrefixedValue(value), |
| 206 | ), |
| 207 | ) as Output.Output<A | string | Redacted.Redacted<string>>; |
| 208 | |
| 209 | const encodedConnectEnv = (connection: Connection) => ({ |
| 210 | connectionId: connection.connectionId, |
| 211 | databaseId: connection.databaseId, |
| 212 | directConnectionString: encodeOptionalValue(connection.directConnectionString), |
| 213 | pooledConnectionString: encodeOptionalValue(connection.pooledConnectionString), |
| 214 | accelerateConnectionString: encodeOptionalValue(connection.accelerateConnectionString), |
| 215 | host: encodeOptionalValue(connection.host), |
| 216 | user: encodeOptionalValue(connection.user), |
| 217 | password: encodeOptionalValue(connection.password), |
| 218 | }); |
| 219 | |
| 220 | const redactedToString = ( |
| 221 | value: Redacted.Redacted<string> | string | undefined, |
| 222 | ): string | undefined => (Redacted.isRedacted(value) ? Redacted.value(value) : value); |
| 223 | |
| 224 | const decodeConnectionValue = ( |
| 225 | value: Redacted.Redacted<string> | string, |
| 226 | ): string | null | undefined => { |
| 227 | const raw = redactedToString(value); |
| 228 | if (raw === undefined || !raw.startsWith(ENCODED_CONNECTION_PREFIX)) { |
| 229 | return raw; |
| 230 | } |
| 231 | try { |
| 232 | const parsed = JSON.parse(raw.slice(ENCODED_CONNECTION_PREFIX.length)); |
| 233 | if (typeof parsed !== "object" || parsed === null || !("kind" in parsed)) { |
| 234 | return raw; |
| 235 | } |
| 236 | if (parsed.kind === "undefined") return undefined; |
| 237 | if (parsed.kind === "null") return null; |
| 238 | if (parsed.kind === "value" && typeof parsed.value === "string") { |
| 239 | return parsed.value; |
| 240 | } |
| 241 | return raw; |
| 242 | } catch { |
| 243 | return raw; |
| 244 | } |
| 245 | }; |
| 246 | |
| 247 | const optionalString = (value: Redacted.Redacted<string> | string): string | undefined => |
| 248 | decodeConnectionValue(value) ?? undefined; |
| 249 | |
| 250 | const optionalRedacted = ( |
| 251 | value: Redacted.Redacted<string> | string, |
| 252 | ): Redacted.Redacted<string> | undefined => { |
| 253 | const decoded = optionalString(value); |
| 254 | return decoded === undefined ? undefined : Redacted.make(decoded); |
| 255 | }; |
| 256 | |
| 257 | const nullableString = (value: Redacted.Redacted<string> | string): string | null | undefined => |
| 258 | decodeConnectionValue(value); |
| 259 | |
| 260 | /** |
| 261 | * Implementation layer for {@link Connect}. Provide it on the host |
| 262 | * Function/Worker Effect: |
| 263 | * |
| 264 | * ```typescript |
| 265 | * Effect.gen(function* () { |
| 266 | * const db = yield* Prisma.Connect(connection); |
| 267 | * // ... |
| 268 | * }).pipe(Effect.provide(Prisma.ConnectBinding)) |
| 269 | * ``` |
| 270 | */ |
| 271 | export const ConnectBinding = Layer.effect( |
| 272 | Connect, |
| 273 | Effect.gen(function* () { |
| 274 | return Effect.fn(function* (connection: Connection) { |
| 275 | // Carried through the host's RuntimeContext: env vars on Prisma |
| 276 | // Compute, Lambda and Containers, text bindings on Workers. Any |
| 277 | // Platform host works. |
| 278 | const runtime = yield* CurrentRuntimeContext; |
| 279 | if (!runtime) { |
| 280 | return yield* Effect.die( |
| 281 | new Error("Prisma.Connect must be bound while initializing a Function or Worker"), |
| 282 | ); |
| 283 | } |
| 284 | // Records the output on the host at deploy; the returned Effect reads |
| 285 | // and decodes it at runtime. |
| 286 | const bind = <A, B>(key: string, output: Output.Output<A>, decode: (value: A) => B) => |
| 287 | output |
| 288 | .bind(key) |
| 289 | .pipe(Effect.provideService(RuntimeContext, runtime), Effect.map(Effect.map(decode))); |
| 290 | const keys = connectEnvKeys(connection); |
| 291 | const env = encodedConnectEnv(connection); |
| 292 | const directConnectionString = yield* bind( |
| 293 | keys.directConnectionString, |
| 294 | env.directConnectionString, |
| 295 | optionalRedacted, |
| 296 | ); |
| 297 | const pooledConnectionString = yield* bind( |
| 298 | keys.pooledConnectionString, |
| 299 | env.pooledConnectionString, |
| 300 | optionalRedacted, |
| 301 | ); |
| 302 | const accelerateConnectionString = yield* bind( |
| 303 | keys.accelerateConnectionString, |
| 304 | env.accelerateConnectionString, |
| 305 | optionalRedacted, |
| 306 | ); |
| 307 | const databaseUrl = Effect.all([ |
| 308 | pooledConnectionString, |
| 309 | directConnectionString, |
| 310 | accelerateConnectionString, |
| 311 | ]).pipe( |
| 312 | Effect.flatMap(([pooled, direct, accelerate]) => { |
| 313 | const url = pooled ?? direct ?? accelerate; |
| 314 | return url === undefined |
| 315 | ? Effect.die( |
| 316 | new Error( |
| 317 | "Prisma connection carries no connection URL (no pooled, direct, or Accelerate endpoint was bound)", |
| 318 | ), |
| 319 | ) |
| 320 | : Effect.succeed(url); |
| 321 | }), |
| 322 | ); |
| 323 | return { |
| 324 | databaseUrl, |
| 325 | connectionId: yield* bind(keys.connectionId, env.connectionId, identity), |
| 326 | databaseId: yield* bind(keys.databaseId, env.databaseId, identity), |
| 327 | directConnectionString, |
| 328 | pooledConnectionString, |
| 329 | accelerateConnectionString, |
| 330 | host: yield* bind(keys.host, env.host, nullableString), |
| 331 | user: yield* bind(keys.user, env.user, nullableString), |
| 332 | password: yield* bind(keys.password, env.password, optionalRedacted), |
| 333 | } satisfies ConnectClient; |
| 334 | }); |
| 335 | }), |
| 336 | ); |