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 GetProjectDatabasesResponse, |
| 4 | type GetProjectsResponse, |
| 5 | getProjects, |
| 6 | getProject, |
| 7 | getProjectDatabases, |
| 8 | updateProject, |
| 9 | createProject, |
| 10 | createProjectDatabase, |
| 11 | } from "@distilled.cloud/prisma/management"; |
| 12 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 13 | import { isResolved } from "alchemy/Diff"; |
| 14 | import * as ProviderLayer from "alchemy/Local/ProviderLayer"; |
| 15 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 16 | import * as Provider from "alchemy/Provider"; |
| 17 | import { Resource } from "alchemy/Resource"; |
| 18 | import * as Data from "effect/Data"; |
| 19 | import * as Effect from "effect/Effect"; |
| 20 | import * as Redacted from "effect/Redacted"; |
| 21 | import * as Schedule from "effect/Schedule"; |
| 22 | import { extractConnectionSecrets } from "./Client.ts"; |
| 23 | import { destroyProjectApps } from "./ComputeLifecycle.ts"; |
| 24 | import { |
| 25 | hasCanonicalConnectionSecrets, |
| 26 | mergeConnectionSecrets, |
| 27 | recoverDatabaseConnectionSecrets, |
| 28 | } from "./internal/DatabaseSecrets.ts"; |
| 29 | import { DEV_TIMESTAMP, devId, devProvider } from "./internal/DevStub.ts"; |
| 30 | import type { ObservedDatabase, ObservedProject } from "./internal/Observed.ts"; |
| 31 | import { PrismaPaginationError } from "./internal/Pagination.ts"; |
| 32 | import { isInputObject, isPrismaDevId } from "./internal/Refs.ts"; |
| 33 | import type { Providers } from "./Providers.ts"; |
| 34 | import type { PrismaSecretConnection, PrismaRegionId } from "./Types.ts"; |
| 35 | |
| 36 | export class ProjectConflict extends Data.TaggedError("ProjectConflict")<{ |
| 37 | readonly message: string; |
| 38 | readonly cause?: unknown; |
| 39 | }> {} |
| 40 | |
| 41 | export class ProjectInvalidProps extends Data.TaggedError("ProjectInvalidProps")<{ |
| 42 | readonly message: string; |
| 43 | readonly cause?: unknown; |
| 44 | }> {} |
| 45 | |
| 46 | export class ProjectUnexpectedResponse extends Data.TaggedError("ProjectUnexpectedResponse")<{ |
| 47 | readonly message: string; |
| 48 | readonly cause?: unknown; |
| 49 | }> {} |
| 50 | |
| 51 | export interface ProjectProps { |
| 52 | /** |
| 53 | * Project display name. If omitted, Alchemy generates a stable physical name. |
| 54 | */ |
| 55 | name?: string; |
| 56 | /** |
| 57 | * Whether to create a default Prisma Postgres database with the project. |
| 58 | * |
| 59 | * @default true |
| 60 | */ |
| 61 | createDatabase?: boolean; |
| 62 | /** |
| 63 | * Region for the default database created with the project. |
| 64 | * |
| 65 | * When `createDatabase` is false, omitting this leaves the project's default |
| 66 | * region unset. |
| 67 | * |
| 68 | * @default "us-east-1" when a default database is created |
| 69 | */ |
| 70 | region?: PrismaRegionId; |
| 71 | /** |
| 72 | * Opaque project settings passed through to the Management API. |
| 73 | */ |
| 74 | settings?: Record<string, unknown>; |
| 75 | /** |
| 76 | * Rotate the adopted default database connection to recover its one-time |
| 77 | * credentials. Prisma revokes the previous key on a best-effort basis and |
| 78 | * rotation may interrupt existing consumers, so adoption leaves credentials |
| 79 | * unset unless explicitly opted in. |
| 80 | * |
| 81 | * @default false |
| 82 | */ |
| 83 | rotateCredentialsOnAdopt?: boolean; |
| 84 | } |
| 85 | |
| 86 | export interface Project extends Resource< |
| 87 | "Prisma.Project", |
| 88 | ProjectProps, |
| 89 | { |
| 90 | /** |
| 91 | * Prisma project ID. |
| 92 | */ |
| 93 | projectId: string; |
| 94 | /** |
| 95 | * Prisma project display name. |
| 96 | */ |
| 97 | projectName: string; |
| 98 | /** |
| 99 | * Workspace ID that owns the project. |
| 100 | */ |
| 101 | workspaceId: string; |
| 102 | /** |
| 103 | * ISO timestamp when the project was created. |
| 104 | */ |
| 105 | createdAt: string; |
| 106 | /** |
| 107 | * Default Prisma Postgres region for the project, when available. |
| 108 | */ |
| 109 | defaultRegion: string | null; |
| 110 | /** |
| 111 | * Default database ID created with or discovered for the project. |
| 112 | */ |
| 113 | databaseId: string | undefined; |
| 114 | /** |
| 115 | * Default database connection ID, when a database exists. |
| 116 | */ |
| 117 | defaultConnectionId: string | undefined; |
| 118 | /** |
| 119 | * Direct Postgres connection string, redacted in state. |
| 120 | */ |
| 121 | directConnectionString: Redacted.Redacted<string> | undefined; |
| 122 | /** |
| 123 | * Pooled Postgres connection string, redacted in state. |
| 124 | */ |
| 125 | pooledConnectionString: Redacted.Redacted<string> | undefined; |
| 126 | /** |
| 127 | * Accelerate connection string, redacted in state. |
| 128 | */ |
| 129 | accelerateConnectionString: Redacted.Redacted<string> | undefined; |
| 130 | /** |
| 131 | * Direct database host, when returned by Prisma. |
| 132 | */ |
| 133 | host: string | null | undefined; |
| 134 | /** |
| 135 | * Direct database username, when returned by Prisma. |
| 136 | */ |
| 137 | user: string | null | undefined; |
| 138 | /** |
| 139 | * Direct database password, redacted in state. |
| 140 | */ |
| 141 | password: Redacted.Redacted<string> | undefined; |
| 142 | }, |
| 143 | never, |
| 144 | Providers |
| 145 | > {} |
| 146 | |
| 147 | /** |
| 148 | * A Prisma project, optionally with a default Prisma Postgres database. |
| 149 | * |
| 150 | * A Project is the ownership boundary for its databases, branches, apps, and |
| 151 | * repository link. Destroying this resource deletes the project and its |
| 152 | * contained data. Set `createDatabase: false` when you want standalone |
| 153 | * `Prisma.Database` resources with independent lifecycles. |
| 154 | * |
| 155 | * ### Creating a Project |
| 156 | * **Example:** Project with a default database |
| 157 | * ```typescript |
| 158 | * const project = yield* Prisma.Project("app", { |
| 159 | * name: "app", |
| 160 | * region: "us-east-1", |
| 161 | * }); |
| 162 | * ``` |
| 163 | * |
| 164 | * **Example:** Project only |
| 165 | * ```typescript |
| 166 | * const project = yield* Prisma.Project("control-plane", { |
| 167 | * createDatabase: false, |
| 168 | * }); |
| 169 | * ``` |
| 170 | * |
| 171 | * @resource |
| 172 | * @product Project |
| 173 | */ |
| 174 | export const Project = Resource<Project>("Prisma.Project"); |
| 175 | |
| 176 | const createName = (id: string, name: string | undefined) => |
| 177 | name === undefined ? createPhysicalName({ id }) : Effect.succeed(name); |
| 178 | |
| 179 | // Distilled emits the Management API's cursor-paginated list operations as |
| 180 | // plain ops, so callers walk `pagination` themselves — the same shape the Neon |
| 181 | // provider uses (see `src/Neon/Project.ts` findProjectByName). |
| 182 | const listProjects = () => |
| 183 | Effect.gen(function* () { |
| 184 | const projects: GetProjectsResponse["data"][number][] = []; |
| 185 | let cursor: string | undefined; |
| 186 | while (true) { |
| 187 | const page = yield* getProjects(cursor === undefined ? {} : { cursor }); |
| 188 | projects.push(...page.data); |
| 189 | const nextCursor = page.pagination.nextCursor; |
| 190 | if (!page.pagination.hasMore) break; |
| 191 | if (nextCursor === null) { |
| 192 | return yield* new PrismaPaginationError({ |
| 193 | message: |
| 194 | "Invalid Prisma Management API pagination response from getProjects: hasMore was true without a non-empty nextCursor", |
| 195 | }); |
| 196 | } |
| 197 | cursor = nextCursor; |
| 198 | } |
| 199 | return projects; |
| 200 | }); |
| 201 | |
| 202 | const findProjectByName = (name: string) => |
| 203 | listProjects().pipe( |
| 204 | Effect.flatMap((projects) => { |
| 205 | const matches = projects.filter((p) => p.name === name); |
| 206 | return matches.length > 1 |
| 207 | ? Effect.fail( |
| 208 | new ProjectConflict({ |
| 209 | message: `Multiple Prisma projects are named '${name}'; use a unique project name before managing it with Alchemy.`, |
| 210 | }), |
| 211 | ) |
| 212 | : Effect.succeed(matches[0]); |
| 213 | }), |
| 214 | ); |
| 215 | |
| 216 | class GeneratedProjectNotVisible extends Data.TaggedError("GeneratedProjectNotVisible")<{ |
| 217 | readonly message: string; |
| 218 | }> {} |
| 219 | |
| 220 | const generatedProjectRecoverySchedule = Schedule.max([ |
| 221 | Schedule.exponential("250 millis"), |
| 222 | Schedule.recurs(6), |
| 223 | ]); |
| 224 | |
| 225 | const recoverGeneratedProjectAfterConflict = (name: string) => |
| 226 | findProjectByName(name).pipe( |
| 227 | Effect.flatMap((project) => |
| 228 | project |
| 229 | ? Effect.succeed(project) |
| 230 | : Effect.fail( |
| 231 | new GeneratedProjectNotVisible({ |
| 232 | message: `Generated Prisma project '${name}' already exists but is not visible yet.`, |
| 233 | }), |
| 234 | ), |
| 235 | ), |
| 236 | Effect.retry({ |
| 237 | while: (error) => error instanceof GeneratedProjectNotVisible, |
| 238 | schedule: generatedProjectRecoverySchedule, |
| 239 | }), |
| 240 | ); |
| 241 | |
| 242 | const listProjectDatabases = (projectId: string) => |
| 243 | Effect.gen(function* () { |
| 244 | const databases: GetProjectDatabasesResponse["data"][number][] = []; |
| 245 | let cursor: string | undefined; |
| 246 | while (true) { |
| 247 | const page = yield* getProjectDatabases( |
| 248 | cursor === undefined ? { projectId, limit: 100 } : { projectId, limit: 100, cursor }, |
| 249 | ); |
| 250 | databases.push(...page.data); |
| 251 | const nextCursor = page.pagination.nextCursor; |
| 252 | if (!page.pagination.hasMore) break; |
| 253 | if (nextCursor === null) { |
| 254 | return yield* new PrismaPaginationError({ |
| 255 | message: |
| 256 | "Invalid Prisma Management API pagination response from getProjectDatabases: hasMore was true without a non-empty nextCursor", |
| 257 | }); |
| 258 | } |
| 259 | cursor = nextCursor; |
| 260 | } |
| 261 | return databases; |
| 262 | }); |
| 263 | |
| 264 | const defaultDatabase = (projectId: string) => |
| 265 | listProjectDatabases(projectId).pipe( |
| 266 | Effect.flatMap((databases) => { |
| 267 | const matches = databases.filter((db) => db.isDefault); |
| 268 | return matches.length > 1 |
| 269 | ? Effect.fail( |
| 270 | new ProjectConflict({ |
| 271 | message: `Prisma project '${projectId}' has multiple default databases; refusing to select one arbitrarily.`, |
| 272 | }), |
| 273 | ) |
| 274 | : Effect.succeed(matches[0]); |
| 275 | }), |
| 276 | ); |
| 277 | |
| 278 | class DefaultDatabaseConsistencyError extends Data.TaggedError("DefaultDatabaseConsistencyError")<{ |
| 279 | readonly message: string; |
| 280 | }> {} |
| 281 | |
| 282 | const defaultDatabaseConsistencySchedule = Schedule.max([ |
| 283 | Schedule.exponential("250 millis"), |
| 284 | Schedule.recurs(6), |
| 285 | ]); |
| 286 | |
| 287 | const requireDefaultDatabaseInRegion = ( |
| 288 | database: ObservedDatabase | undefined, |
| 289 | projectName: string, |
| 290 | desiredRegion: string, |
| 291 | ) => |
| 292 | database?.region?.id === desiredRegion |
| 293 | ? Effect.succeed(database) |
| 294 | : Effect.fail( |
| 295 | new DefaultDatabaseConsistencyError({ |
| 296 | message: database |
| 297 | ? `Prisma project '${projectName}' still has default database '${database.id}' in region '${database.region?.id ?? "unknown"}', but region '${desiredRegion}' was requested. Retry after any in-progress default database promotion completes.` |
| 298 | : `Prisma project '${projectName}' does not expose the requested default database in region '${desiredRegion}'. Retry after any in-progress default database creation completes.`, |
| 299 | }), |
| 300 | ); |
| 301 | |
| 302 | type ProjectDatabaseAttrs = ObservedDatabase; |
| 303 | |
| 304 | const observeDesiredDefaultDatabase = ( |
| 305 | projectName: string, |
| 306 | projectId: string, |
| 307 | expectedDatabaseId: string, |
| 308 | desiredRegion: string, |
| 309 | ) => |
| 310 | Effect.gen(function* () { |
| 311 | const project = (yield* getProject({ id: projectId }).pipe( |
| 312 | Effect.catchTag("NotFound", () => |
| 313 | Effect.fail( |
| 314 | new DefaultDatabaseConsistencyError({ |
| 315 | message: `Prisma project '${projectName}' (${projectId}) is not visible yet while verifying its new default database.`, |
| 316 | }), |
| 317 | ), |
| 318 | ), |
| 319 | )).data; |
| 320 | const database = yield* requireDefaultDatabaseInRegion( |
| 321 | yield* defaultDatabase(projectId).pipe( |
| 322 | Effect.catchTag("NotFound", () => |
| 323 | Effect.fail( |
| 324 | new DefaultDatabaseConsistencyError({ |
| 325 | message: `Prisma project '${projectName}' default database list is not visible yet.`, |
| 326 | }), |
| 327 | ), |
| 328 | ), |
| 329 | ), |
| 330 | projectName, |
| 331 | desiredRegion, |
| 332 | ); |
| 333 | if (database.id !== expectedDatabaseId) { |
| 334 | return yield* new DefaultDatabaseConsistencyError({ |
| 335 | message: `Prisma project '${projectName}' exposes default database '${database.id}', but newly created database '${expectedDatabaseId}' was expected. Retry after the in-progress default database promotion completes.`, |
| 336 | }); |
| 337 | } |
| 338 | if (project.defaultRegion !== desiredRegion) { |
| 339 | return yield* new DefaultDatabaseConsistencyError({ |
| 340 | message: `Prisma project '${projectName}' still reports default region '${project.defaultRegion ?? "unknown"}', but region '${desiredRegion}' was requested. Retry after the in-progress default database promotion completes.`, |
| 341 | }); |
| 342 | } |
| 343 | return { project, database }; |
| 344 | }).pipe( |
| 345 | Effect.retry({ |
| 346 | while: (error) => error instanceof DefaultDatabaseConsistencyError, |
| 347 | schedule: defaultDatabaseConsistencySchedule, |
| 348 | }), |
| 349 | ); |
| 350 | |
| 351 | const attrsFrom = ( |
| 352 | project: ObservedProject, |
| 353 | database: ObservedDatabase | undefined, |
| 354 | secrets: PrismaSecretConnection, |
| 355 | ): Project["Attributes"] => ({ |
| 356 | projectId: project.id, |
| 357 | projectName: project.name, |
| 358 | workspaceId: project.workspace.id, |
| 359 | createdAt: project.createdAt, |
| 360 | // The default database observation is authoritative. Project.defaultRegion |
| 361 | // may briefly lag after Prisma atomically promotes a replacement database. |
| 362 | defaultRegion: database?.region?.id ?? project.defaultRegion, |
| 363 | databaseId: database?.id, |
| 364 | defaultConnectionId: database?.defaultConnectionId ?? undefined, |
| 365 | directConnectionString: secrets.directConnectionString, |
| 366 | pooledConnectionString: secrets.pooledConnectionString, |
| 367 | accelerateConnectionString: secrets.accelerateConnectionString, |
| 368 | host: secrets.host, |
| 369 | user: secrets.user, |
| 370 | password: secrets.password, |
| 371 | }); |
| 372 | |
| 373 | const ProviderLive = () => |
| 374 | Provider.effect( |
| 375 | Project, |
| 376 | Effect.gen(function* () { |
| 377 | return { |
| 378 | stables: ["projectId"], |
| 379 | list: Effect.fn(function* () { |
| 380 | const projects = yield* listProjects(); |
| 381 | return yield* Effect.forEach( |
| 382 | projects, |
| 383 | Effect.fn(function* (project) { |
| 384 | const database = yield* defaultDatabase(project.id).pipe( |
| 385 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 386 | ); |
| 387 | return attrsFrom(project, database, {}); |
| 388 | }), |
| 389 | { concurrency: 8 }, |
| 390 | ); |
| 391 | }), |
| 392 | diff: Effect.fn(function* ({ id, olds = {}, news = {}, output }) { |
| 393 | if (isPrismaDevId(output?.projectId)) { |
| 394 | return { action: "update" } as const; |
| 395 | } |
| 396 | if (!isInputObject(news)) return undefined; |
| 397 | if ( |
| 398 | isResolved(news.rotateCredentialsOnAdopt) && |
| 399 | news.rotateCredentialsOnAdopt === true && |
| 400 | olds.rotateCredentialsOnAdopt !== true |
| 401 | ) { |
| 402 | return { action: "update" } as const; |
| 403 | } |
| 404 | const desiredCreateDatabase = isResolved(news.createDatabase) |
| 405 | ? (news.createDatabase ?? true) |
| 406 | : undefined; |
| 407 | const desiredRegion = isResolved(news.region) ? (news.region ?? "us-east-1") : undefined; |
| 408 | const hadDatabase = |
| 409 | output?.databaseId !== undefined || (!output && (olds.createDatabase ?? true)); |
| 410 | |
| 411 | // The API cannot remove a project's last/default database. Moving |
| 412 | // from a database-bearing project to `createDatabase: false` |
| 413 | // therefore requires replacing the project itself. |
| 414 | if (desiredCreateDatabase === false && hadDatabase) { |
| 415 | // A replacement may coexist when its generated name changes with |
| 416 | // the instance id, or when this update also changes the explicit |
| 417 | // name. A stable explicit name collides with the old generation |
| 418 | // and must be removed before creating the new project. |
| 419 | const deleteFirst = isResolved(news.name) |
| 420 | ? news.name !== undefined && (!output || news.name === output.projectName) |
| 421 | : true; |
| 422 | return { action: "replace", deleteFirst } as const; |
| 423 | } |
| 424 | |
| 425 | // Adding a missing default database and replacing only that database |
| 426 | // for a region change are both supported in-place. Preserve the |
| 427 | // project (and its apps, repository link, environment, and IDs). |
| 428 | if ( |
| 429 | desiredCreateDatabase === true && |
| 430 | output?.databaseId !== undefined && |
| 431 | desiredRegion !== undefined && |
| 432 | output.defaultRegion !== desiredRegion |
| 433 | ) { |
| 434 | return yield* new ProjectInvalidProps({ |
| 435 | message: `Cannot safely change Prisma project '${output.projectName}' default database region from '${output.defaultRegion ?? "unknown"}' to '${desiredRegion}' in place. The Management API would create an empty default database and leave the data-bearing database to be deleted. Create a replacement project and perform an explicit data migration/cutover instead.`, |
| 436 | }); |
| 437 | } |
| 438 | if ( |
| 439 | desiredCreateDatabase === true && |
| 440 | (output?.databaseId === undefined || (olds.createDatabase ?? true) === false) |
| 441 | ) { |
| 442 | return { action: "update" } as const; |
| 443 | } |
| 444 | const updateProps = { |
| 445 | name: news.name, |
| 446 | settings: news.settings, |
| 447 | }; |
| 448 | if (!isResolved(updateProps)) return undefined; |
| 449 | const resolvedUpdateProps = updateProps as Pick<ProjectProps, "name" | "settings">; |
| 450 | const nextName = yield* createName(id, resolvedUpdateProps.name); |
| 451 | const oldName = output?.projectName ?? (yield* createName(id, olds.name)); |
| 452 | if ( |
| 453 | nextName !== oldName || |
| 454 | // Settings are write-only in the Management API project |
| 455 | // response. Re-apply an explicit desired value every deploy so |
| 456 | // out-of-band changes converge, and write `{}` once when a |
| 457 | // previously managed settings prop is removed. |
| 458 | resolvedUpdateProps.settings !== undefined || |
| 459 | (olds.settings !== undefined && resolvedUpdateProps.settings === undefined) |
| 460 | ) { |
| 461 | return { action: "update" } as const; |
| 462 | } |
| 463 | return undefined; |
| 464 | }), |
| 465 | read: Effect.fn(function* ({ id, output, olds = {}, previous }) { |
| 466 | const projectId = isPrismaDevId(output?.projectId) ? undefined : output?.projectId; |
| 467 | const project = projectId |
| 468 | ? yield* getProject({ id: projectId }).pipe( |
| 469 | Effect.map((response) => response.data), |
| 470 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 471 | ) |
| 472 | : yield* findProjectByName(yield* createName(id, olds.name)); |
| 473 | if (!project) return undefined; |
| 474 | const database = yield* defaultDatabase(project.id).pipe( |
| 475 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 476 | ); |
| 477 | const cachedSecrets = output?.databaseId === database?.id ? output : undefined; |
| 478 | const attrs = attrsFrom(project, database, { |
| 479 | directConnectionString: cachedSecrets?.directConnectionString, |
| 480 | pooledConnectionString: cachedSecrets?.pooledConnectionString, |
| 481 | accelerateConnectionString: cachedSecrets?.accelerateConnectionString, |
| 482 | host: cachedSecrets?.host, |
| 483 | user: cachedSecrets?.user, |
| 484 | password: cachedSecrets?.password, |
| 485 | }); |
| 486 | // An omitted name is derived from this exact PlanScope instance ID. |
| 487 | // Finding it proves this is create-recovery, not a foreign natural- |
| 488 | // key match. User-supplied names still require explicit adoption, |
| 489 | // except for the generation a replacement is replacing. |
| 490 | return projectId === undefined && |
| 491 | olds.name !== undefined && |
| 492 | project.id !== previous?.projectId |
| 493 | ? Unowned(attrs) |
| 494 | : attrs; |
| 495 | }), |
| 496 | reconcile: Effect.fn(function* ({ id, news = {}, olds, output }) { |
| 497 | const name = yield* createName(id, news.name); |
| 498 | const outputProjectId = isPrismaDevId(output?.projectId) ? undefined : output?.projectId; |
| 499 | let project: ObservedProject | undefined = outputProjectId |
| 500 | ? yield* getProject({ id: outputProjectId }).pipe( |
| 501 | Effect.map((response) => response.data), |
| 502 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 503 | ) |
| 504 | : news.name === undefined |
| 505 | ? yield* findProjectByName(name) |
| 506 | : undefined; |
| 507 | |
| 508 | let createdDatabase: ProjectDatabaseAttrs | undefined; |
| 509 | let secrets: PrismaSecretConnection = {}; |
| 510 | let createdProject = false; |
| 511 | let recoverCreateSecrets = false; |
| 512 | if (!project) { |
| 513 | const result = yield* createProject({ |
| 514 | name, |
| 515 | createDatabase: news.createDatabase ?? true, |
| 516 | region: news.region, |
| 517 | }).pipe( |
| 518 | // A replayed create would make a second project; the retry |
| 519 | // policy cannot see the request, so opt out explicitly. |
| 520 | Retry.none, |
| 521 | Effect.map((response) => { |
| 522 | const project: ObservedProject = response.data; |
| 523 | return { |
| 524 | project, |
| 525 | database: response.data.database ?? undefined, |
| 526 | secrets: extractConnectionSecrets(response.data.database?.connections[0]), |
| 527 | created: true, |
| 528 | recoverSecrets: true, |
| 529 | }; |
| 530 | }), |
| 531 | Effect.catchTag("Conflict", () => |
| 532 | news.name === undefined |
| 533 | ? recoverGeneratedProjectAfterConflict(name).pipe( |
| 534 | Effect.map((project) => ({ |
| 535 | project, |
| 536 | database: undefined, |
| 537 | secrets: {}, |
| 538 | // The generated physical name is owned by this |
| 539 | // resource instance. Treat a conflict followed by an |
| 540 | // exact read as lost-response recovery so write-only |
| 541 | // default credentials are restored. |
| 542 | created: false, |
| 543 | recoverSecrets: true, |
| 544 | })), |
| 545 | ) |
| 546 | : Effect.fail( |
| 547 | new ProjectConflict({ |
| 548 | message: `Prisma project '${name}' appeared after the adoption check. Refusing to take it over; rerun with adoption enabled if it is the intended project.`, |
| 549 | }), |
| 550 | ), |
| 551 | ), |
| 552 | ); |
| 553 | project = result.project; |
| 554 | createdDatabase = result.database; |
| 555 | secrets = result.secrets; |
| 556 | createdProject = result.created; |
| 557 | recoverCreateSecrets = result.recoverSecrets; |
| 558 | } |
| 559 | if (!project) { |
| 560 | return yield* new ProjectUnexpectedResponse({ |
| 561 | message: `Prisma project '${name}' could not be observed after create recovery.`, |
| 562 | }); |
| 563 | } |
| 564 | const ownedGeneratedIdentity = news.name === undefined && project.name === name; |
| 565 | |
| 566 | if (news.createDatabase === false && createdDatabase) { |
| 567 | return yield* new ProjectUnexpectedResponse({ |
| 568 | message: `Prisma created unexpected default database '${createdDatabase.name}' (${createdDatabase.id}) for project '${project.name}' even though createDatabase was false. Refusing to persist a state the Management API cannot remove in place.`, |
| 569 | }); |
| 570 | } |
| 571 | |
| 572 | if (news.createDatabase === false && !createdProject) { |
| 573 | const existingDefault = yield* defaultDatabase(project.id).pipe( |
| 574 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 575 | ); |
| 576 | if (existingDefault) { |
| 577 | return yield* new ProjectConflict({ |
| 578 | message: `Prisma project '${project.name}' already owns default database '${existingDefault.name}' (${existingDefault.id}), which cannot be removed in place. Refusing to adopt or reconcile it as createDatabase: false; replace the Prisma.Project instead.`, |
| 579 | }); |
| 580 | } |
| 581 | } |
| 582 | |
| 583 | // Project reads do not expose settings. Whenever settings are |
| 584 | // explicitly managed, write them during reconcile (including the |
| 585 | // forced reconcile after adoption) instead of trusting `olds` as an |
| 586 | // observation of cloud state. When the prop is removed after being |
| 587 | // managed, an empty object clears the previously managed settings. |
| 588 | const settingsChanged = news.settings !== undefined || olds?.settings !== undefined; |
| 589 | if (project.name !== name || settingsChanged) { |
| 590 | project = (yield* updateProject({ |
| 591 | id: project.id, |
| 592 | name, |
| 593 | ...(settingsChanged ? { settings: news.settings ?? {} } : {}), |
| 594 | })).data; |
| 595 | } |
| 596 | const projectId = project.id; |
| 597 | |
| 598 | let database = createdDatabase; |
| 599 | let defaultDatabaseChanged = false; |
| 600 | if (news.createDatabase !== false && !database) { |
| 601 | database = yield* defaultDatabase(projectId).pipe( |
| 602 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 603 | ); |
| 604 | } |
| 605 | |
| 606 | if (news.createDatabase !== false) { |
| 607 | const desiredRegion = news.region ?? "us-east-1"; |
| 608 | if (database && database.region?.id !== desiredRegion) { |
| 609 | return yield* new ProjectInvalidProps({ |
| 610 | message: `Cannot safely change Prisma project '${name}' default database region from '${database.region?.id ?? "unknown"}' to '${desiredRegion}' in place. The Management API would create an empty default database and risk deleting the existing data-bearing database. Create a replacement project and perform an explicit data migration/cutover instead.`, |
| 611 | }); |
| 612 | } |
| 613 | if (!database) { |
| 614 | defaultDatabaseChanged = true; |
| 615 | const created: ObservedDatabase = yield* createProjectDatabase({ |
| 616 | projectId, |
| 617 | region: desiredRegion, |
| 618 | isDefault: true, |
| 619 | }).pipe( |
| 620 | Retry.none, |
| 621 | Effect.map((response) => response.data), |
| 622 | Effect.catchTag("Conflict", () => |
| 623 | defaultDatabase(projectId).pipe( |
| 624 | Effect.flatMap((database) => |
| 625 | requireDefaultDatabaseInRegion(database, name, desiredRegion), |
| 626 | ), |
| 627 | ), |
| 628 | ), |
| 629 | ); |
| 630 | database = yield* requireDefaultDatabaseInRegion(created, name, desiredRegion); |
| 631 | secrets = extractConnectionSecrets(created.connections[0]); |
| 632 | } |
| 633 | } |
| 634 | |
| 635 | // Project.defaultRegion is derived from the current default database; |
| 636 | // re-read both resources after an in-place database replacement and |
| 637 | // verify the Management API actually exposes the desired region. |
| 638 | if (defaultDatabaseChanged) { |
| 639 | const changedDatabaseId = database?.id; |
| 640 | if (changedDatabaseId === undefined) { |
| 641 | return yield* new DefaultDatabaseConsistencyError({ |
| 642 | message: `Prisma project '${name}' did not return an identifier for its new default database.`, |
| 643 | }); |
| 644 | } |
| 645 | const observed = yield* observeDesiredDefaultDatabase( |
| 646 | name, |
| 647 | project.id, |
| 648 | changedDatabaseId, |
| 649 | news.region ?? "us-east-1", |
| 650 | ); |
| 651 | project = observed.project; |
| 652 | database = observed.database; |
| 653 | } |
| 654 | |
| 655 | const persistedSecrets = |
| 656 | output && database !== undefined && output.databaseId === database.id |
| 657 | ? { |
| 658 | directConnectionString: output.directConnectionString, |
| 659 | pooledConnectionString: output.pooledConnectionString, |
| 660 | accelerateConnectionString: output.accelerateConnectionString, |
| 661 | host: output.host, |
| 662 | user: output.user, |
| 663 | password: output.password, |
| 664 | } |
| 665 | : {}; |
| 666 | const knownSecrets = mergeConnectionSecrets(secrets, persistedSecrets); |
| 667 | let finalSecrets = knownSecrets; |
| 668 | if ( |
| 669 | database && |
| 670 | (recoverCreateSecrets || |
| 671 | (ownedGeneratedIdentity && !hasCanonicalConnectionSecrets(knownSecrets)) || |
| 672 | defaultDatabaseChanged || |
| 673 | olds !== undefined || |
| 674 | news.rotateCredentialsOnAdopt === true) |
| 675 | ) { |
| 676 | const recovered = yield* recoverDatabaseConnectionSecrets(database, knownSecrets); |
| 677 | database = recovered.database; |
| 678 | finalSecrets = recovered.secrets; |
| 679 | } |
| 680 | |
| 681 | return attrsFrom(project, database, finalSecrets); |
| 682 | }), |
| 683 | delete: Effect.fn(function* ({ output }) { |
| 684 | if (isPrismaDevId(output.projectId)) return; |
| 685 | yield* destroyProjectApps(output.projectId); |
| 686 | }), |
| 687 | }; |
| 688 | }), |
| 689 | ); |
| 690 | |
| 691 | const ProviderLocal = () => |
| 692 | devProvider(Project, ["projectId"], ({ id, news }) => ({ |
| 693 | projectId: devId("project", id), |
| 694 | projectName: news.name ?? id, |
| 695 | workspaceId: devId("workspace", "local"), |
| 696 | createdAt: DEV_TIMESTAMP, |
| 697 | defaultRegion: |
| 698 | news.createDatabase === false ? (news.region ?? null) : (news.region ?? "us-east-1"), |
| 699 | databaseId: news.createDatabase === false ? undefined : devId("database", id), |
| 700 | defaultConnectionId: news.createDatabase === false ? undefined : devId("connection", id), |
| 701 | directConnectionString: undefined, |
| 702 | pooledConnectionString: undefined, |
| 703 | accelerateConnectionString: undefined, |
| 704 | host: undefined, |
| 705 | user: undefined, |
| 706 | password: undefined, |
| 707 | })); |
| 708 | |
| 709 | export const ProjectProvider = () => |
| 710 | ProviderLayer.dual(Project, { |
| 711 | local: () => ProviderLocal(), |
| 712 | live: () => ProviderLive(), |
| 713 | }); |