The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { Retry } from "@distilled.cloud/prisma"; |
| 2 | import { |
| 3 | type GetConnectionsResponse, |
| 4 | deleteConnection, |
| 5 | getConnections, |
| 6 | getConnection, |
| 7 | getDatabaseConnections, |
| 8 | createConnection, |
| 9 | createConnectionRotate, |
| 10 | } from "@distilled.cloud/prisma/management"; |
| 11 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 12 | import { isResolved } from "alchemy/Diff"; |
| 13 | import * as ProviderLayer from "alchemy/Local/ProviderLayer"; |
| 14 | import * as Provider from "alchemy/Provider"; |
| 15 | import { Resource } from "alchemy/Resource"; |
| 16 | import * as Data from "effect/Data"; |
| 17 | import * as Effect from "effect/Effect"; |
| 18 | import * as Redacted from "effect/Redacted"; |
| 19 | import * as Schedule from "effect/Schedule"; |
| 20 | import { extractConnectionSecrets } from "./Client.ts"; |
| 21 | import type { Database } from "./Database.ts"; |
| 22 | import { |
| 23 | deriveConnectionAttrs, |
| 24 | hasCanonicalConnectionSecrets, |
| 25 | } from "./internal/DatabaseSecrets.ts"; |
| 26 | import { |
| 27 | DEV_TIMESTAMP, |
| 28 | attrOrNullableString, |
| 29 | attrOrRedactedString, |
| 30 | attrOrString, |
| 31 | devId, |
| 32 | devProvider, |
| 33 | } from "./internal/DevStub.ts"; |
| 34 | import { physicalInstanceName } from "./internal/EnvName.ts"; |
| 35 | import type { ObservedConnectionRecord } from "./internal/Observed.ts"; |
| 36 | import { PrismaPaginationError } from "./internal/Pagination.ts"; |
| 37 | import { |
| 38 | concreteIdOf, |
| 39 | concreteIdsChanged, |
| 40 | isInputObject, |
| 41 | isPrismaDevId, |
| 42 | resolveDatabaseId, |
| 43 | unresolvedDatabaseIdOf, |
| 44 | } from "./internal/Refs.ts"; |
| 45 | import type { PostgresOrigin } from "./PostgresOrigin.ts"; |
| 46 | import type { Providers } from "./Providers.ts"; |
| 47 | import type { PrismaSecretConnection } from "./Types.ts"; |
| 48 | |
| 49 | export class ConnectionConflict extends Data.TaggedError("ConnectionConflict")<{ |
| 50 | readonly message: string; |
| 51 | readonly cause?: unknown; |
| 52 | }> {} |
| 53 | |
| 54 | export class ConnectionUnexpectedResponse extends Data.TaggedError("ConnectionUnexpectedResponse")<{ |
| 55 | readonly message: string; |
| 56 | readonly cause?: unknown; |
| 57 | }> {} |
| 58 | |
| 59 | export interface ConnectionProps { |
| 60 | /** |
| 61 | * Database ID or `database.databaseId` output this connection belongs to. |
| 62 | */ |
| 63 | database: string | Database; |
| 64 | /** |
| 65 | * Human-readable connection name prefix. Alchemy appends the resource |
| 66 | * instance identity because Prisma permits duplicate connection names and |
| 67 | * exposes no ownership tags. |
| 68 | * |
| 69 | * @default the resource's logical ID |
| 70 | */ |
| 71 | name?: string; |
| 72 | /** |
| 73 | * Rotate credentials when this value changes from `false` to `true` while |
| 74 | * keeping the connection ID. Prisma revokes the previous credentials on a |
| 75 | * best-effort basis. Deploy `false` before changing back to `true` for a |
| 76 | * later rotation. |
| 77 | * |
| 78 | * @default false |
| 79 | */ |
| 80 | rotate?: boolean; |
| 81 | } |
| 82 | |
| 83 | export interface Connection extends Resource< |
| 84 | "Prisma.Connection", |
| 85 | ConnectionProps, |
| 86 | { |
| 87 | /** |
| 88 | * Prisma connection/API key ID. |
| 89 | */ |
| 90 | connectionId: string; |
| 91 | /** |
| 92 | * Connection display name. |
| 93 | */ |
| 94 | connectionName: string; |
| 95 | /** |
| 96 | * Database ID this connection belongs to. |
| 97 | */ |
| 98 | databaseId: string; |
| 99 | /** |
| 100 | * Connection kind returned by Prisma. |
| 101 | */ |
| 102 | kind: "postgres" | "accelerate"; |
| 103 | /** |
| 104 | * ISO timestamp when the connection was created. |
| 105 | */ |
| 106 | createdAt: string; |
| 107 | /** |
| 108 | * Direct Postgres connection string, redacted in state. |
| 109 | */ |
| 110 | directConnectionString: Redacted.Redacted<string> | undefined; |
| 111 | /** |
| 112 | * Pooled Postgres connection string, redacted in state. |
| 113 | */ |
| 114 | pooledConnectionString: Redacted.Redacted<string> | undefined; |
| 115 | /** |
| 116 | * Accelerate connection string, redacted in state. |
| 117 | */ |
| 118 | accelerateConnectionString: Redacted.Redacted<string> | undefined; |
| 119 | /** |
| 120 | * Direct database host, when returned by Prisma. |
| 121 | */ |
| 122 | host: string | null | undefined; |
| 123 | /** |
| 124 | * Direct database username, when returned by Prisma. |
| 125 | */ |
| 126 | user: string | null | undefined; |
| 127 | /** |
| 128 | * Direct database password, redacted in state. |
| 129 | */ |
| 130 | password: Redacted.Redacted<string> | undefined; |
| 131 | /** |
| 132 | * Conventional application database URL, redacted in state. |
| 133 | * |
| 134 | * Resolves to the pooled Postgres URL first, then direct Postgres, then |
| 135 | * Accelerate — the serverless-safe default for application traffic. |
| 136 | */ |
| 137 | databaseUrl: Redacted.Redacted<string> | undefined; |
| 138 | /** |
| 139 | * Parsed direct connection components ready to feed into a Postgres |
| 140 | * origin — e.g. `Cloudflare.Hyperdrive`'s `origin` prop. Points at the |
| 141 | * direct (non-pooled) endpoint, which is the recommended target when |
| 142 | * fronting Prisma Postgres with another pooler like Hyperdrive. |
| 143 | */ |
| 144 | origin: PostgresOrigin | undefined; |
| 145 | /** |
| 146 | * Parsed pooled connection components. Useful as a Hyperdrive `dev` |
| 147 | * origin when local workers bypass Hyperdrive and connect directly. |
| 148 | */ |
| 149 | pooledOrigin: PostgresOrigin | undefined; |
| 150 | }, |
| 151 | never, |
| 152 | Providers |
| 153 | > {} |
| 154 | |
| 155 | /** |
| 156 | * A Prisma database connection/API key. |
| 157 | * |
| 158 | * Prisma returns connection credentials only when it creates or rotates a |
| 159 | * connection. Alchemy stores those outputs as `Redacted` values. Changing the |
| 160 | * database or name replaces the connection; changing `rotate` from `false` to |
| 161 | * `true` keeps the connection ID and requests fresh credentials. |
| 162 | * |
| 163 | * ### Creating a Connection |
| 164 | * **Example:** Application connection |
| 165 | * ```typescript |
| 166 | * const connection = yield* Prisma.Connection("api", { |
| 167 | * database: database.databaseId, |
| 168 | * }); |
| 169 | * ``` |
| 170 | * |
| 171 | * ### Binding to Platforms |
| 172 | * **Example:** Pass database URLs to Compute env |
| 173 | * ```typescript |
| 174 | * const connection = yield* Prisma.Connection("api", { |
| 175 | * database, |
| 176 | * }); |
| 177 | * |
| 178 | * const app = yield* Prisma.Compute("api", { |
| 179 | * project, |
| 180 | * path: "./apps/api", |
| 181 | * env: { |
| 182 | * DATABASE_URL: connection.databaseUrl, |
| 183 | * DIRECT_URL: connection.directConnectionString, |
| 184 | * }, |
| 185 | * }); |
| 186 | * ``` |
| 187 | * |
| 188 | * **Example:** Use a connection inside an Effect-native Compute app |
| 189 | * ```typescript |
| 190 | * export default Prisma.Compute( |
| 191 | * "api", |
| 192 | * { project, appName: "api", main: import.meta.filename }, |
| 193 | * Effect.gen(function* () { |
| 194 | * const db = yield* Prisma.Connect(connection); |
| 195 | * const sql = yield* SQL.Postgres({ url: db.databaseUrl }); |
| 196 | * return { |
| 197 | * fetch: Effect.gen(function* () { |
| 198 | * const users = yield* sql`SELECT * FROM users`; |
| 199 | * return yield* HttpServerResponse.json(users); |
| 200 | * }), |
| 201 | * }; |
| 202 | * }).pipe(Effect.provide(Prisma.ConnectBinding)), |
| 203 | * ); |
| 204 | * ``` |
| 205 | * |
| 206 | * **Example:** Use a connection inside an Effect-native Lambda function |
| 207 | * ```typescript |
| 208 | * export default AWS.Lambda.Function( |
| 209 | * "api", |
| 210 | * { main: import.meta.filename, functionUrl: true }, |
| 211 | * Effect.gen(function* () { |
| 212 | * const db = yield* Prisma.Connect(connection); |
| 213 | * const sql = yield* SQL.Postgres({ url: db.databaseUrl }); |
| 214 | * return { |
| 215 | * fetch: Effect.gen(function* () { |
| 216 | * const users = yield* sql`SELECT * FROM users`; |
| 217 | * return yield* HttpServerResponse.json(users); |
| 218 | * }), |
| 219 | * }; |
| 220 | * }).pipe(Effect.provide(Prisma.ConnectBinding)), |
| 221 | * ); |
| 222 | * ``` |
| 223 | * |
| 224 | * **Example:** Use a connection inside an Effect-native Cloudflare Worker |
| 225 | * ```typescript |
| 226 | * export default Cloudflare.Worker( |
| 227 | * "api", |
| 228 | * { main: import.meta.filename, compatibility: { flags: ["nodejs_compat"] } }, |
| 229 | * Effect.gen(function* () { |
| 230 | * const db = yield* Prisma.Connect(connection); |
| 231 | * const sql = yield* SQL.Postgres({ url: db.databaseUrl }); |
| 232 | * return { |
| 233 | * fetch: Effect.gen(function* () { |
| 234 | * const result = yield* sql`SELECT 1 AS ok`; |
| 235 | * return yield* HttpServerResponse.json(result); |
| 236 | * }), |
| 237 | * }; |
| 238 | * }).pipe(Effect.provide(Prisma.ConnectBinding)), |
| 239 | * ); |
| 240 | * ``` |
| 241 | * |
| 242 | * ### Rotating Credentials |
| 243 | * **Example:** Request one rotation |
| 244 | * ```typescript |
| 245 | * const connection = yield* Prisma.Connection("api", { |
| 246 | * database, |
| 247 | * rotate: true, |
| 248 | * }); |
| 249 | * ``` |
| 250 | * |
| 251 | * ### Connecting over Hyperdrive |
| 252 | * **Example:** Front Prisma Postgres with Cloudflare Hyperdrive |
| 253 | * ```typescript |
| 254 | * const hyperdrive = yield* Cloudflare.Hyperdrive.Connection("api-hd", { |
| 255 | * origin: connection.origin.as<Prisma.PostgresOrigin>(), |
| 256 | * }); |
| 257 | * |
| 258 | * export default Cloudflare.Worker( |
| 259 | * "api", |
| 260 | * { main: import.meta.filename, compatibility: { flags: ["nodejs_compat"] } }, |
| 261 | * Effect.gen(function* () { |
| 262 | * const hd = yield* Cloudflare.Hyperdrive.Connect(hyperdrive); |
| 263 | * const sql = yield* SQL.Postgres({ url: hd.connectionString }); |
| 264 | * return { |
| 265 | * fetch: Effect.gen(function* () { |
| 266 | * const users = yield* sql`SELECT * FROM users`; |
| 267 | * return yield* HttpServerResponse.json(users); |
| 268 | * }), |
| 269 | * }; |
| 270 | * }).pipe(Effect.provide(Cloudflare.Hyperdrive.ConnectBinding)), |
| 271 | * ); |
| 272 | * ``` |
| 273 | * |
| 274 | * @resource |
| 275 | * @product Postgres |
| 276 | */ |
| 277 | export const Connection = Resource<Connection>("Prisma.Connection"); |
| 278 | |
| 279 | // Distilled emits the cursor-paginated list operations as plain ops, so |
| 280 | // callers walk `pagination` themselves (see `src/Neon/Project.ts`). |
| 281 | const listDatabaseConnections = (databaseId: string) => |
| 282 | Effect.gen(function* () { |
| 283 | const connections: GetConnectionsResponse["data"][number][] = []; |
| 284 | let cursor: string | undefined; |
| 285 | while (true) { |
| 286 | const page = yield* getDatabaseConnections( |
| 287 | cursor === undefined ? { databaseId, limit: 100 } : { databaseId, limit: 100, cursor }, |
| 288 | ); |
| 289 | connections.push(...page.data); |
| 290 | const nextCursor = page.pagination.nextCursor; |
| 291 | if (!page.pagination.hasMore) break; |
| 292 | if (nextCursor === null) { |
| 293 | return yield* new PrismaPaginationError({ |
| 294 | message: |
| 295 | "Invalid Prisma Management API pagination response from getDatabaseConnections: hasMore was true without a non-empty nextCursor", |
| 296 | }); |
| 297 | } |
| 298 | cursor = nextCursor; |
| 299 | } |
| 300 | return connections; |
| 301 | }); |
| 302 | |
| 303 | const listAllConnections = () => |
| 304 | Effect.gen(function* () { |
| 305 | const connections: GetConnectionsResponse["data"][number][] = []; |
| 306 | let cursor: string | undefined; |
| 307 | while (true) { |
| 308 | const page = yield* getConnections(cursor === undefined ? {} : { cursor }); |
| 309 | connections.push(...page.data); |
| 310 | const nextCursor = page.pagination.nextCursor; |
| 311 | if (!page.pagination.hasMore) break; |
| 312 | if (nextCursor === null) { |
| 313 | return yield* new PrismaPaginationError({ |
| 314 | message: |
| 315 | "Invalid Prisma Management API pagination response from getConnections: hasMore was true without a non-empty nextCursor", |
| 316 | }); |
| 317 | } |
| 318 | cursor = nextCursor; |
| 319 | } |
| 320 | return connections; |
| 321 | }); |
| 322 | |
| 323 | const findConnection = ( |
| 324 | databaseId: string, |
| 325 | predicate: (connection: ObservedConnectionRecord) => boolean, |
| 326 | ) => |
| 327 | listDatabaseConnections(databaseId).pipe( |
| 328 | Effect.map((connections) => connections.filter(predicate)), |
| 329 | ); |
| 330 | |
| 331 | class AmbiguousPrismaConnectionError extends Data.TaggedError("AmbiguousPrismaConnectionError")<{ |
| 332 | readonly databaseId: string; |
| 333 | readonly connectionName: string; |
| 334 | readonly count: number; |
| 335 | }> { |
| 336 | override get message() { |
| 337 | return `Prisma database '${this.databaseId}' has ${this.count} connections named '${this.connectionName}'; use a unique connection name before importing it into Alchemy`; |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | class InvalidPrismaConnectionNameError extends Data.TaggedError( |
| 342 | "InvalidPrismaConnectionNameError", |
| 343 | ) { |
| 344 | override get message() { |
| 345 | return "Prisma connection name must contain at least one non-space character"; |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | const validateConnectionName = (name: string) => { |
| 350 | const trimmed = name.trim(); |
| 351 | return trimmed.length === 0 |
| 352 | ? Effect.fail(new InvalidPrismaConnectionNameError()) |
| 353 | : Effect.succeed(trimmed); |
| 354 | }; |
| 355 | |
| 356 | const uniqueConnection = ( |
| 357 | databaseId: string, |
| 358 | description: string, |
| 359 | predicate: (connection: ObservedConnectionRecord) => boolean, |
| 360 | ) => |
| 361 | findConnection(databaseId, predicate).pipe( |
| 362 | Effect.flatMap((connections) => |
| 363 | connections.length <= 1 |
| 364 | ? Effect.succeed(connections[0]) |
| 365 | : Effect.fail( |
| 366 | new AmbiguousPrismaConnectionError({ |
| 367 | databaseId, |
| 368 | connectionName: description, |
| 369 | count: connections.length, |
| 370 | }), |
| 371 | ), |
| 372 | ), |
| 373 | ); |
| 374 | |
| 375 | class GeneratedConnectionNotVisible extends Data.TaggedError("GeneratedConnectionNotVisible")<{ |
| 376 | readonly message: string; |
| 377 | }> {} |
| 378 | |
| 379 | const generatedConnectionRecoverySchedule = Schedule.max([ |
| 380 | Schedule.exponential("250 millis"), |
| 381 | Schedule.recurs(6), |
| 382 | ]); |
| 383 | |
| 384 | const recoverGeneratedConnectionAfterConflict = (databaseId: string, expectedName: string) => |
| 385 | uniqueConnection(databaseId, expectedName, (candidate) => candidate.name === expectedName).pipe( |
| 386 | Effect.flatMap((connection) => |
| 387 | connection |
| 388 | ? Effect.succeed(connection) |
| 389 | : Effect.fail( |
| 390 | new GeneratedConnectionNotVisible({ |
| 391 | message: `Generated Prisma connection '${expectedName}' is not visible yet.`, |
| 392 | }), |
| 393 | ), |
| 394 | ), |
| 395 | Effect.retry({ |
| 396 | while: (error) => error instanceof GeneratedConnectionNotVisible, |
| 397 | schedule: generatedConnectionRecoverySchedule, |
| 398 | }), |
| 399 | ); |
| 400 | |
| 401 | const physicalConnectionPrefix = (name: string) => `${name.trim().slice(0, 52)}-`; |
| 402 | |
| 403 | const isGeneratedPhysicalConnectionName = (physicalName: string, logicalName: string) => { |
| 404 | const prefix = physicalConnectionPrefix(logicalName); |
| 405 | return ( |
| 406 | physicalName.startsWith(prefix) && /^[0-9a-f]{12}$/i.test(physicalName.slice(prefix.length)) |
| 407 | ); |
| 408 | }; |
| 409 | |
| 410 | const isAdoptablePhysicalConnectionName = (physicalName: string, logicalName: string) => |
| 411 | physicalName === logicalName.trim() || |
| 412 | isGeneratedPhysicalConnectionName(physicalName, logicalName); |
| 413 | |
| 414 | const attrsFrom = ( |
| 415 | connection: ObservedConnectionRecord, |
| 416 | secrets: PrismaSecretConnection, |
| 417 | ): Connection["Attributes"] => ({ |
| 418 | connectionId: connection.id, |
| 419 | connectionName: connection.name, |
| 420 | databaseId: connection.database.id, |
| 421 | kind: connection.kind, |
| 422 | createdAt: connection.createdAt, |
| 423 | directConnectionString: secrets.directConnectionString, |
| 424 | pooledConnectionString: secrets.pooledConnectionString, |
| 425 | accelerateConnectionString: secrets.accelerateConnectionString, |
| 426 | host: secrets.host, |
| 427 | user: secrets.user, |
| 428 | password: secrets.password, |
| 429 | ...deriveConnectionAttrs(secrets), |
| 430 | }); |
| 431 | |
| 432 | const ProviderLive = () => |
| 433 | Provider.effect( |
| 434 | Connection, |
| 435 | Effect.gen(function* () { |
| 436 | return { |
| 437 | stables: ["connectionId"], |
| 438 | list: () => |
| 439 | listAllConnections().pipe( |
| 440 | Effect.map((connections) => connections.map((c) => attrsFrom(c, {}))), |
| 441 | ), |
| 442 | diff: Effect.fn(function* ({ id, olds, news, output }) { |
| 443 | if (!isInputObject(news)) return undefined; |
| 444 | if (isPrismaDevId(output?.connectionId)) { |
| 445 | return { action: "update" } as const; |
| 446 | } |
| 447 | const oldDatabaseId = output?.databaseId ?? unresolvedDatabaseIdOf(olds.database); |
| 448 | const newDatabaseId = isResolved(news.database) |
| 449 | ? unresolvedDatabaseIdOf(news.database) |
| 450 | : undefined; |
| 451 | const resolvedName = isResolved(news.name) |
| 452 | ? yield* validateConnectionName(news.name ?? id) |
| 453 | : undefined; |
| 454 | const nameChanged = |
| 455 | resolvedName !== undefined && resolvedName !== (olds.name ?? id).trim(); |
| 456 | if (concreteIdsChanged(oldDatabaseId, newDatabaseId) || nameChanged) { |
| 457 | return { action: "replace" } as const; |
| 458 | } |
| 459 | if (!isResolved(news.rotate)) return undefined; |
| 460 | if ((news.rotate ?? false) !== (olds.rotate ?? false)) { |
| 461 | return { action: "update" } as const; |
| 462 | } |
| 463 | return undefined; |
| 464 | }), |
| 465 | read: Effect.fn(function* ({ id, instanceId, output, olds }) { |
| 466 | const connectionId = isPrismaDevId(output?.connectionId) |
| 467 | ? undefined |
| 468 | : output?.connectionId; |
| 469 | if (connectionId && output) { |
| 470 | const connection = yield* getConnection({ |
| 471 | id: connectionId, |
| 472 | }).pipe( |
| 473 | Effect.map((response) => response.data), |
| 474 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 475 | ); |
| 476 | if (!connection) return undefined; |
| 477 | if ( |
| 478 | connection.database.id !== output.databaseId || |
| 479 | connection.name !== output.connectionName |
| 480 | ) { |
| 481 | return yield* new ConnectionConflict({ |
| 482 | message: `Prisma connection '${connection.id}' no longer matches persisted database '${output.databaseId}' and name '${output.connectionName}'. Refusing to refresh a mismatched connection.`, |
| 483 | }); |
| 484 | } |
| 485 | const observed = extractConnectionSecrets(connection); |
| 486 | return attrsFrom(connection, { |
| 487 | directConnectionString: output?.directConnectionString, |
| 488 | pooledConnectionString: output?.pooledConnectionString, |
| 489 | accelerateConnectionString: output?.accelerateConnectionString, |
| 490 | host: observed.host, |
| 491 | user: output?.user, |
| 492 | password: output?.password, |
| 493 | }); |
| 494 | } |
| 495 | |
| 496 | const databaseId = unresolvedDatabaseIdOf(olds.database); |
| 497 | if (!databaseId) return undefined; |
| 498 | const name = yield* validateConnectionName(olds.name ?? id); |
| 499 | const expectedName = physicalInstanceName(name, instanceId); |
| 500 | const owned = yield* uniqueConnection( |
| 501 | databaseId, |
| 502 | expectedName, |
| 503 | (connection) => connection.name === expectedName, |
| 504 | ); |
| 505 | if (owned) return attrsFrom(owned, {}); |
| 506 | |
| 507 | const prefix = physicalConnectionPrefix(name); |
| 508 | const generated = yield* uniqueConnection( |
| 509 | databaseId, |
| 510 | `${prefix}<instance-id>`, |
| 511 | (connection) => |
| 512 | connection.name !== expectedName && |
| 513 | isGeneratedPhysicalConnectionName(connection.name, name), |
| 514 | ); |
| 515 | const connection = |
| 516 | generated ?? |
| 517 | (yield* uniqueConnection(databaseId, name, (connection) => connection.name === name)); |
| 518 | if (!connection) return undefined; |
| 519 | return Unowned(attrsFrom(connection, {})); |
| 520 | }), |
| 521 | reconcile: Effect.fn(function* ({ id, instanceId, news, olds, output }) { |
| 522 | const databaseId = yield* resolveDatabaseId(news.database); |
| 523 | const name = yield* validateConnectionName(news.name ?? id); |
| 524 | const connectionId = concreteIdOf(output?.connectionId); |
| 525 | let connection: ObservedConnectionRecord | undefined = connectionId |
| 526 | ? yield* getConnection({ id: connectionId }).pipe( |
| 527 | Effect.map((response) => response.data), |
| 528 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 529 | ) |
| 530 | : undefined; |
| 531 | |
| 532 | const expectedName = physicalInstanceName(name, instanceId); |
| 533 | const physicalName = connectionId && output ? output.connectionName : expectedName; |
| 534 | if (connectionId && !isAdoptablePhysicalConnectionName(physicalName, name)) { |
| 535 | return yield* new ConnectionConflict({ |
| 536 | message: `Persisted Prisma connection '${connectionId}' has physical name '${physicalName}', which does not match requested logical name '${name}'. Refusing to adopt or persist a mismatched connection.`, |
| 537 | }); |
| 538 | } |
| 539 | if ( |
| 540 | connection && |
| 541 | (connection.database.id !== databaseId || connection.name !== physicalName) |
| 542 | ) { |
| 543 | return yield* new ConnectionConflict({ |
| 544 | message: `Prisma connection '${connection.id}' resolves to database '${connection.database.id}' with name '${connection.name}', not requested database '${databaseId}' and physical name '${physicalName}'. Refusing to rotate or persist mismatched identity; replace the connection instead.`, |
| 545 | }); |
| 546 | } |
| 547 | |
| 548 | if (!connection && !connectionId) { |
| 549 | connection = yield* uniqueConnection( |
| 550 | databaseId, |
| 551 | expectedName, |
| 552 | (candidate) => candidate.name === expectedName, |
| 553 | ); |
| 554 | } |
| 555 | |
| 556 | let secrets: PrismaSecretConnection = connection |
| 557 | ? extractConnectionSecrets(connection) |
| 558 | : {}; |
| 559 | if (!connection) { |
| 560 | const create = createConnection({ |
| 561 | databaseId, |
| 562 | name: physicalName, |
| 563 | }).pipe( |
| 564 | // A replayed create would mint a second connection; the retry |
| 565 | // policy cannot see the request, so opt out explicitly. |
| 566 | Retry.none, |
| 567 | Effect.map((response) => response.data), |
| 568 | ); |
| 569 | connection = yield* physicalName === expectedName |
| 570 | ? create.pipe( |
| 571 | Effect.catchTag("Conflict", () => |
| 572 | recoverGeneratedConnectionAfterConflict(databaseId, expectedName), |
| 573 | ), |
| 574 | ) |
| 575 | : create; |
| 576 | secrets = extractConnectionSecrets(connection); |
| 577 | } |
| 578 | const missingCanonicalSecrets = |
| 579 | secrets.directConnectionString === undefined && |
| 580 | secrets.pooledConnectionString === undefined && |
| 581 | secrets.accelerateConnectionString === undefined && |
| 582 | output?.directConnectionString === undefined && |
| 583 | output?.pooledConnectionString === undefined && |
| 584 | output?.accelerateConnectionString === undefined; |
| 585 | const recoveringOwnedGeneratedSecrets = |
| 586 | physicalName === expectedName && missingCanonicalSecrets; |
| 587 | if (recoveringOwnedGeneratedSecrets || (news.rotate === true && olds?.rotate !== true)) { |
| 588 | const rotated = yield* createConnectionRotate({ |
| 589 | id: connection.id, |
| 590 | }).pipe( |
| 591 | // Rotation mints new credentials; a replay would revoke the |
| 592 | // ones we just persisted, so opt out of the retry policy. |
| 593 | Retry.none, |
| 594 | Effect.map((response) => response.data), |
| 595 | ); |
| 596 | if ( |
| 597 | rotated.id !== connection.id || |
| 598 | rotated.database.id !== databaseId || |
| 599 | rotated.name !== physicalName |
| 600 | ) { |
| 601 | return yield* new ConnectionUnexpectedResponse({ |
| 602 | message: `Prisma rotated connection '${rotated.id}' for database '${rotated.database.id}' with name '${rotated.name}', but connection '${connection.id}' for database '${databaseId}' with name '${physicalName}' was requested. Refusing to persist mismatched credentials.`, |
| 603 | }); |
| 604 | } |
| 605 | connection = rotated; |
| 606 | secrets = extractConnectionSecrets(rotated); |
| 607 | if (!hasCanonicalConnectionSecrets(secrets)) { |
| 608 | return yield* new ConnectionUnexpectedResponse({ |
| 609 | message: `Prisma rotated connection '${connection.id}' for database '${databaseId}' without returning a canonical connection URL. Refusing to persist missing or stale credentials.`, |
| 610 | }); |
| 611 | } |
| 612 | } |
| 613 | |
| 614 | return attrsFrom(connection, { |
| 615 | directConnectionString: |
| 616 | secrets.directConnectionString ?? output?.directConnectionString, |
| 617 | pooledConnectionString: |
| 618 | secrets.pooledConnectionString ?? output?.pooledConnectionString, |
| 619 | accelerateConnectionString: |
| 620 | secrets.accelerateConnectionString ?? output?.accelerateConnectionString, |
| 621 | host: secrets.host ?? output?.host, |
| 622 | user: secrets.user ?? output?.user, |
| 623 | password: secrets.password ?? output?.password, |
| 624 | }); |
| 625 | }), |
| 626 | delete: Effect.fn(function* ({ output }) { |
| 627 | if (isPrismaDevId(output.connectionId)) return; |
| 628 | const connection = yield* getConnection({ |
| 629 | id: output.connectionId, |
| 630 | }).pipe( |
| 631 | Effect.map((response) => response.data), |
| 632 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 633 | ); |
| 634 | if (!connection) return; |
| 635 | if ( |
| 636 | connection.database.id !== output.databaseId || |
| 637 | connection.name !== output.connectionName |
| 638 | ) { |
| 639 | return yield* new ConnectionConflict({ |
| 640 | message: `Prisma connection '${connection.id}' no longer matches persisted database '${output.databaseId}' and name '${output.connectionName}'. Refusing to delete a mismatched connection.`, |
| 641 | }); |
| 642 | } |
| 643 | yield* deleteConnection({ id: connection.id }).pipe( |
| 644 | Effect.catchTag("NotFound", () => Effect.void), |
| 645 | ); |
| 646 | }), |
| 647 | }; |
| 648 | }), |
| 649 | ); |
| 650 | |
| 651 | const ProviderLocal = () => |
| 652 | devProvider(Connection, ["connectionId"], ({ id, news }) => { |
| 653 | const secrets = { |
| 654 | directConnectionString: attrOrRedactedString(news.database, "directConnectionString"), |
| 655 | pooledConnectionString: attrOrRedactedString(news.database, "pooledConnectionString"), |
| 656 | accelerateConnectionString: attrOrRedactedString(news.database, "accelerateConnectionString"), |
| 657 | }; |
| 658 | return { |
| 659 | connectionId: devId("connection", id), |
| 660 | connectionName: news.name ?? id, |
| 661 | databaseId: attrOrString(news.database, "databaseId"), |
| 662 | kind: "postgres", |
| 663 | createdAt: DEV_TIMESTAMP, |
| 664 | ...secrets, |
| 665 | host: attrOrNullableString(news.database, "host"), |
| 666 | user: attrOrNullableString(news.database, "user"), |
| 667 | password: attrOrRedactedString(news.database, "password"), |
| 668 | ...deriveConnectionAttrs(secrets), |
| 669 | }; |
| 670 | }); |
| 671 | |
| 672 | export const ConnectionProvider = () => |
| 673 | ProviderLayer.dual(Connection, { |
| 674 | local: () => ProviderLocal(), |
| 675 | live: () => ProviderLive(), |
| 676 | }); |