The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type { App } from "@alchemy.run/prisma/App"; |
| 2 | import { Branch as PrismaBranch, BranchProvider } from "@alchemy.run/prisma/Branch"; |
| 3 | import { PrismaApiError, PrismaClient } from "@alchemy.run/prisma/Client"; |
| 4 | import type { PrismaManagementClient } from "@alchemy.run/prisma/Client"; |
| 5 | import { |
| 6 | CustomDomain as PrismaCustomDomain, |
| 7 | CustomDomainProvider, |
| 8 | } from "@alchemy.run/prisma/CustomDomain"; |
| 9 | import { Database as PrismaDatabase, DatabaseProvider } from "@alchemy.run/prisma/Database"; |
| 10 | import { |
| 11 | EnvironmentVariable as PrismaEnvironmentVariable, |
| 12 | EnvironmentVariableProvider, |
| 13 | } from "@alchemy.run/prisma/EnvironmentVariable"; |
| 14 | import { Project as PrismaProject, ProjectProvider } from "@alchemy.run/prisma/Project"; |
| 15 | import { |
| 16 | SourceRepository as PrismaSourceRepository, |
| 17 | SourceRepositoryProvider, |
| 18 | } from "@alchemy.run/prisma/SourceRepository"; |
| 19 | import type { |
| 20 | Branch as ApiBranch, |
| 21 | CustomDomain as ApiCustomDomain, |
| 22 | Database as ApiDatabase, |
| 23 | DatabaseConnectionWithSecrets, |
| 24 | Project as ApiProject, |
| 25 | SourceRepository as ApiSourceRepository, |
| 26 | } from "@alchemy.run/prisma/Types"; |
| 27 | import { expect, it } from "@alchemy.run/test"; |
| 28 | import * as Test from "@alchemy.run/test/Alchemy"; |
| 29 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 30 | import { AlchemyContext } from "alchemy/AlchemyContext"; |
| 31 | import * as Output from "alchemy/Output"; |
| 32 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 33 | import * as Provider from "alchemy/Provider"; |
| 34 | import { ResourceContext } from "alchemy/ResourceContext"; |
| 35 | import { PlatformServices } from "alchemy/Util/PlatformServices"; |
| 36 | import * as Effect from "effect/Effect"; |
| 37 | import * as Fiber from "effect/Fiber"; |
| 38 | import * as Layer from "effect/Layer"; |
| 39 | import * as Redacted from "effect/Redacted"; |
| 40 | import * as Result from "effect/Result"; |
| 41 | import * as TestClock from "effect/testing/TestClock"; |
| 42 | import { recoverDatabaseConnectionSecrets } from "../../../prisma/src/internal/DatabaseSecrets.ts"; |
| 43 | import { resourceContext } from "../Util/ResourceContext.ts"; |
| 44 | import { |
| 45 | conflict, |
| 46 | data, |
| 47 | dispatchTo, |
| 48 | failure, |
| 49 | type FakeManagementApi, |
| 50 | json, |
| 51 | makeFakeManagementApi, |
| 52 | noContent, |
| 53 | notFound, |
| 54 | page, |
| 55 | unhandled, |
| 56 | } from "./fixtures/FakeManagementApi.ts"; |
| 57 | import { testStackContext } from "./fixtures/StackContext.ts"; |
| 58 | |
| 59 | const createdAt = "2026-01-01T00:00:00.000Z"; |
| 60 | |
| 61 | const liveProviderContext = Layer.succeed(AlchemyContext, { |
| 62 | dotAlchemy: ".alchemy-test", |
| 63 | dev: false, |
| 64 | adopt: false, |
| 65 | }); |
| 66 | |
| 67 | class TestPrismaProviders extends Provider.ProviderCollection<TestPrismaProviders>()("Prisma") {} |
| 68 | |
| 69 | const projectLayer = (fake: FakeManagementApi) => |
| 70 | Layer.effect(TestPrismaProviders, Provider.collection([PrismaProject])).pipe( |
| 71 | Layer.provideMerge(ProjectProvider()), |
| 72 | Layer.provide(liveProviderContext), |
| 73 | Layer.provideMerge(fake.layer), |
| 74 | ); |
| 75 | |
| 76 | /** Wire serializers for the in-memory cloud's Types.ts-shaped records. */ |
| 77 | const toWireProject = (project: ApiProject) => ({ ...project, logicalId: null }); |
| 78 | |
| 79 | const toWireDatabase = (database: ApiDatabase) => database; |
| 80 | |
| 81 | const toWireCreatedDatabase = (database: ApiDatabase) => ({ |
| 82 | ...database, |
| 83 | apiKeys: [], |
| 84 | connectionString: "postgres://direct", |
| 85 | directConnection: { host: "db.prisma.test", user: "prisma", pass: "secret" }, |
| 86 | }); |
| 87 | |
| 88 | const branchLayer = (fake: FakeManagementApi) => |
| 89 | Layer.effect(TestPrismaProviders, Provider.collection([PrismaBranch])).pipe( |
| 90 | Layer.provideMerge(BranchProvider()), |
| 91 | Layer.provide(liveProviderContext), |
| 92 | Layer.provideMerge(fake.layer), |
| 93 | ); |
| 94 | |
| 95 | const databaseLayer = (fake: FakeManagementApi) => |
| 96 | Layer.effect(TestPrismaProviders, Provider.collection([PrismaDatabase])).pipe( |
| 97 | Layer.provideMerge(DatabaseProvider()), |
| 98 | Layer.provide(liveProviderContext), |
| 99 | Layer.provideMerge(fake.layer), |
| 100 | ); |
| 101 | |
| 102 | /** |
| 103 | * Serve the Management API from the same hermetic client-shaped handlers this |
| 104 | * suite declares, for the resources that now call distilled operations. |
| 105 | * `dispatchTo` maps each handler's result onto the wire (see the fixture). |
| 106 | */ |
| 107 | const clientBackedApi = (client: any) => |
| 108 | makeFakeManagementApi((request) => { |
| 109 | // segments[0] is the "v1" prefix. |
| 110 | const [head, id, tail] = request.pathname |
| 111 | .split("/") |
| 112 | .filter((segment) => segment.length > 0) |
| 113 | .slice(1); |
| 114 | const body = request.bodyJson as any; |
| 115 | const query = Object.fromEntries(new URLSearchParams(request.search)); |
| 116 | const { call, callVoid, list } = dispatchTo(request); |
| 117 | |
| 118 | if (head === "projects") { |
| 119 | if (id === undefined && request.method === "GET") { |
| 120 | return call(client.listProjects, [], list); |
| 121 | } |
| 122 | if (tail === "branches" && request.method === "GET") { |
| 123 | return call(client.listBranches, [id, query], list); |
| 124 | } |
| 125 | if (tail === "databases" && request.method === "GET") { |
| 126 | return call(client.listProjectDatabases, [id, query], list); |
| 127 | } |
| 128 | } |
| 129 | if (head === "services" && id === undefined && request.method === "GET") { |
| 130 | return call(client.listApps, [query], list); |
| 131 | } |
| 132 | if (head === "environment-variables") { |
| 133 | if (id === undefined) { |
| 134 | return request.method === "GET" |
| 135 | ? call(client.listEnvironmentVariables, [query], list) |
| 136 | : call(client.createEnvironmentVariable, [body]); |
| 137 | } |
| 138 | if (request.method === "GET") { |
| 139 | return call(client.getEnvironmentVariable, [id]); |
| 140 | } |
| 141 | if (request.method === "PATCH") { |
| 142 | return call(client.updateEnvironmentVariable, [id, body]); |
| 143 | } |
| 144 | if (request.method === "DELETE") { |
| 145 | return callVoid(client.deleteEnvironmentVariable, [id]); |
| 146 | } |
| 147 | } |
| 148 | if (head === "source-repositories") { |
| 149 | if (id === undefined) { |
| 150 | return request.method === "GET" |
| 151 | ? call(client.listSourceRepositories, [query], list) |
| 152 | : call(client.createSourceRepository, [body]); |
| 153 | } |
| 154 | if (request.method === "GET") { |
| 155 | return call(client.getSourceRepository, [id]); |
| 156 | } |
| 157 | if (request.method === "DELETE") { |
| 158 | return callVoid(client.deleteSourceRepository, [id]); |
| 159 | } |
| 160 | } |
| 161 | return unhandled(request); |
| 162 | }); |
| 163 | |
| 164 | const environmentVariableLayer = (client: PrismaManagementClient) => |
| 165 | Layer.effect(TestPrismaProviders, Provider.collection([PrismaEnvironmentVariable])).pipe( |
| 166 | Layer.provideMerge(EnvironmentVariableProvider()), |
| 167 | Layer.provide(liveProviderContext), |
| 168 | Layer.provideMerge(clientBackedApi(client).layer), |
| 169 | ); |
| 170 | |
| 171 | const customDomainLayer = (client: PrismaManagementClient) => |
| 172 | Layer.effect(TestPrismaProviders, Provider.collection([PrismaCustomDomain])).pipe( |
| 173 | Layer.provideMerge(CustomDomainProvider()), |
| 174 | Layer.provideMerge(Layer.succeed(PrismaClient, client)), |
| 175 | Layer.provide(liveProviderContext), |
| 176 | ); |
| 177 | |
| 178 | const sourceRepositoryLayer = (client: PrismaManagementClient) => |
| 179 | Layer.effect(TestPrismaProviders, Provider.collection([PrismaSourceRepository])).pipe( |
| 180 | Layer.provideMerge(SourceRepositoryProvider()), |
| 181 | Layer.provide(liveProviderContext), |
| 182 | Layer.provideMerge(clientBackedApi(client).layer), |
| 183 | ); |
| 184 | |
| 185 | const apiProject = ( |
| 186 | id: string, |
| 187 | name: string, |
| 188 | defaultRegion: string | null = "us-east-1", |
| 189 | ): ApiProject => ({ |
| 190 | id, |
| 191 | type: "project", |
| 192 | url: `https://api.prisma.test/v1/projects/${id}`, |
| 193 | name, |
| 194 | createdAt, |
| 195 | defaultRegion, |
| 196 | workspace: { |
| 197 | id: "workspace-1", |
| 198 | url: "https://api.prisma.test/v1/workspaces/workspace-1", |
| 199 | name: "team", |
| 200 | }, |
| 201 | }); |
| 202 | |
| 203 | const apiConnection = ( |
| 204 | databaseId: string, |
| 205 | connectionId = `connection-${databaseId}`, |
| 206 | ): DatabaseConnectionWithSecrets => ({ |
| 207 | id: connectionId, |
| 208 | type: "connection", |
| 209 | url: `https://api.prisma.test/v1/connections/${connectionId}`, |
| 210 | name: "default", |
| 211 | createdAt, |
| 212 | kind: "postgres", |
| 213 | endpoints: { |
| 214 | direct: { |
| 215 | host: "db.prisma.test", |
| 216 | port: 5432, |
| 217 | connectionString: `postgres://user:password@db.prisma.test/${databaseId}`, |
| 218 | }, |
| 219 | pooled: { |
| 220 | host: "pool.prisma.test", |
| 221 | port: 5432, |
| 222 | connectionString: `postgres://user:password@pool.prisma.test/${databaseId}`, |
| 223 | }, |
| 224 | }, |
| 225 | database: { |
| 226 | id: databaseId, |
| 227 | url: `https://api.prisma.test/v1/databases/${databaseId}`, |
| 228 | name: databaseId, |
| 229 | }, |
| 230 | }); |
| 231 | |
| 232 | it.effect( |
| 233 | "database credential recovery waits for a ready default connection", |
| 234 | () => { |
| 235 | const provisioning: ApiDatabase = { |
| 236 | ...apiDatabase("database-provisioning", { projectId: "project-1", name: "provisioning" }), |
| 237 | status: "provisioning", |
| 238 | defaultConnectionId: null, |
| 239 | connections: [], |
| 240 | }; |
| 241 | const ready: ApiDatabase = { |
| 242 | ...provisioning, |
| 243 | status: "ready", |
| 244 | defaultConnectionId: "connection-provisioning", |
| 245 | }; |
| 246 | let reads = 0; |
| 247 | let rotations = 0; |
| 248 | const fake = makeFakeManagementApi((request) => { |
| 249 | if (request.pathname.startsWith("/v1/databases/")) { |
| 250 | return data(toWireDatabase(reads++ === 0 ? provisioning : ready)); |
| 251 | } |
| 252 | if (request.pathname.endsWith("/rotate")) { |
| 253 | rotations += 1; |
| 254 | return data(apiConnection(ready.id, ready.defaultConnectionId!)); |
| 255 | } |
| 256 | return unhandled(request); |
| 257 | }); |
| 258 | |
| 259 | return Effect.gen(function* () { |
| 260 | const fiber = yield* recoverDatabaseConnectionSecrets(provisioning, {}).pipe( |
| 261 | Effect.forkChild({ startImmediately: true }), |
| 262 | ); |
| 263 | yield* Effect.yieldNow; |
| 264 | yield* TestClock.adjust("1 second"); |
| 265 | const recovered = yield* Fiber.join(fiber); |
| 266 | expect(recovered.database.status).toBe("ready"); |
| 267 | expect(recovered.database.defaultConnectionId).toBe("connection-provisioning"); |
| 268 | expect(Redacted.value(recovered.secrets.directConnectionString!)).toContain(ready.id); |
| 269 | expect(rotations).toBe(1); |
| 270 | }).pipe(Effect.provide(fake.layer), Effect.provide(TestClock.layer())); |
| 271 | }, |
| 272 | { tags: ["unit", "provider:prisma", "provider:prisma:database", "local"] }, |
| 273 | ); |
| 274 | |
| 275 | it.effect( |
| 276 | "database credential recovery has a bounded status-rich timeout", |
| 277 | () => { |
| 278 | const provisioning: ApiDatabase = { |
| 279 | ...apiDatabase("database-stuck", { projectId: "project-1", name: "stuck" }), |
| 280 | status: "provisioning", |
| 281 | defaultConnectionId: null, |
| 282 | connections: [], |
| 283 | }; |
| 284 | const fake = makeFakeManagementApi((request) => { |
| 285 | if (request.pathname.startsWith("/v1/databases/")) { |
| 286 | return data(toWireDatabase(provisioning)); |
| 287 | } |
| 288 | if (request.pathname.endsWith("/rotate")) { |
| 289 | throw new Error("must not rotate while provisioning"); |
| 290 | } |
| 291 | return unhandled(request); |
| 292 | }); |
| 293 | |
| 294 | return Effect.gen(function* () { |
| 295 | const fiber = yield* recoverDatabaseConnectionSecrets(provisioning, {}).pipe( |
| 296 | Effect.result, |
| 297 | Effect.forkChild({ startImmediately: true }), |
| 298 | ); |
| 299 | yield* Effect.yieldNow; |
| 300 | yield* TestClock.adjust("1 minute"); |
| 301 | const result = yield* Fiber.join(fiber); |
| 302 | expect(Result.isFailure(result)).toBe(true); |
| 303 | if (Result.isFailure(result)) { |
| 304 | expect(String(result.failure)).toContain("database-stuck"); |
| 305 | expect(String(result.failure)).toContain("provisioning"); |
| 306 | expect(String(result.failure)).toContain("defaultConnectionId 'null'"); |
| 307 | } |
| 308 | }).pipe(Effect.provide(fake.layer), Effect.provide(TestClock.layer())); |
| 309 | }, |
| 310 | { tags: ["unit", "provider:prisma", "provider:prisma:database", "local"] }, |
| 311 | ); |
| 312 | |
| 313 | const makeProjectCloud = (initial: ApiProject[] = []) => { |
| 314 | const projects = new Map(initial.map((project) => [project.id, project])); |
| 315 | const databases = new Map<string, ApiDatabase>(); |
| 316 | const calls: Array<[string, unknown?]> = []; |
| 317 | let nextId = initial.length + 1; |
| 318 | let nextDatabaseId = 1; |
| 319 | let conflictNextProjectDatabaseCreate = false; |
| 320 | let staleNextProjectDatabaseObservation = false; |
| 321 | let staleProjectReads = 0; |
| 322 | let staleProjectDefaultRegion: string | null = null; |
| 323 | let staleDatabaseLists = 0; |
| 324 | let staleDatabases: ApiDatabase[] = []; |
| 325 | |
| 326 | const currentProject = (project: ApiProject) => { |
| 327 | const database = Array.from(databases.values()).find( |
| 328 | (database) => database.project.id === project.id && database.isDefault, |
| 329 | ); |
| 330 | return { ...project, defaultRegion: database?.region?.id ?? null }; |
| 331 | }; |
| 332 | |
| 333 | const makeDatabase = ( |
| 334 | project: ApiProject, |
| 335 | input: { region?: string; isDefault?: boolean }, |
| 336 | ): ApiDatabase => { |
| 337 | if (input.isDefault) { |
| 338 | for (const [id, database] of databases) { |
| 339 | if (database.project.id === project.id && database.isDefault) { |
| 340 | databases.set(id, { ...database, isDefault: false }); |
| 341 | } |
| 342 | } |
| 343 | } |
| 344 | const id = `project-database-${nextDatabaseId++}`; |
| 345 | const database: ApiDatabase = { |
| 346 | id, |
| 347 | type: "database", |
| 348 | url: `https://api.prisma.test/v1/databases/${id}`, |
| 349 | name: project.name, |
| 350 | status: "ready", |
| 351 | createdAt, |
| 352 | isDefault: input.isDefault ?? false, |
| 353 | defaultConnectionId: `connection-${id}`, |
| 354 | connections: [apiConnection(id)], |
| 355 | project: { id: project.id, url: project.url, name: project.name }, |
| 356 | region: { id: input.region ?? "us-east-1", name: input.region ?? "us-east-1" }, |
| 357 | source: { type: "empty" }, |
| 358 | branchId: null, |
| 359 | }; |
| 360 | databases.set(id, database); |
| 361 | return database; |
| 362 | }; |
| 363 | |
| 364 | // The same in-memory cloud, served over the wire for the resources that |
| 365 | // call distilled operations instead of the client above. |
| 366 | const fake = makeFakeManagementApi((request) => { |
| 367 | const segments = request.pathname.split("/").filter((s) => s.length > 0); |
| 368 | |
| 369 | if (request.pathname === "/v1/services" && request.method === "GET") { |
| 370 | calls.push(["listApps", Object.fromEntries(new URLSearchParams(request.search))]); |
| 371 | return page([]); |
| 372 | } |
| 373 | |
| 374 | if (request.pathname === "/v1/projects" && request.method === "GET") { |
| 375 | calls.push(["listProjects"]); |
| 376 | return page(Array.from(projects.values()).map(currentProject).map(toWireProject)); |
| 377 | } |
| 378 | |
| 379 | if (request.pathname === "/v1/projects" && request.method === "POST") { |
| 380 | const input = request.bodyJson as { |
| 381 | name?: string; |
| 382 | region?: string; |
| 383 | createDatabase?: boolean; |
| 384 | }; |
| 385 | calls.push(["createProject", input]); |
| 386 | const id = `project-${nextId++}`; |
| 387 | const project = apiProject(id, input.name ?? `project-${id}`, null); |
| 388 | projects.set(id, project); |
| 389 | const database = |
| 390 | input.createDatabase === false |
| 391 | ? null |
| 392 | : makeDatabase(project, { region: input.region, isDefault: true }); |
| 393 | return data( |
| 394 | { |
| 395 | ...toWireProject(currentProject(project)), |
| 396 | database: database === null ? null : toWireCreatedDatabase(database), |
| 397 | }, |
| 398 | { status: 201 }, |
| 399 | ); |
| 400 | } |
| 401 | |
| 402 | if (segments.length === 3 && segments[1] === "projects") { |
| 403 | const id = segments[2]!; |
| 404 | if (request.method === "GET") { |
| 405 | calls.push(["getProject", id]); |
| 406 | const stored = projects.get(id); |
| 407 | const project = stored |
| 408 | ? staleProjectReads > 0 |
| 409 | ? { ...currentProject(stored), defaultRegion: staleProjectDefaultRegion } |
| 410 | : currentProject(stored) |
| 411 | : undefined; |
| 412 | if (staleProjectReads > 0) staleProjectReads -= 1; |
| 413 | return project === undefined ? notFound("not found") : data(toWireProject(project)); |
| 414 | } |
| 415 | if (request.method === "PATCH") { |
| 416 | const input = request.bodyJson as { name?: string; settings?: Record<string, unknown> }; |
| 417 | calls.push(["updateProject", { id, input }]); |
| 418 | const project = projects.get(id)!; |
| 419 | const updated = { ...project, name: input.name ?? project.name }; |
| 420 | projects.set(id, updated); |
| 421 | return data(toWireProject(currentProject(updated))); |
| 422 | } |
| 423 | if (request.method === "DELETE") { |
| 424 | calls.push(["deleteProject", id]); |
| 425 | projects.delete(id); |
| 426 | for (const [databaseId, database] of databases) { |
| 427 | if (database.project.id === id) databases.delete(databaseId); |
| 428 | } |
| 429 | return json(null, { status: 204 }); |
| 430 | } |
| 431 | } |
| 432 | |
| 433 | if (segments.length === 4 && segments[1] === "projects" && segments[3] === "databases") { |
| 434 | const projectId = segments[2]!; |
| 435 | if (request.method === "GET") { |
| 436 | calls.push(["listProjectDatabases", projectId]); |
| 437 | if (staleDatabaseLists > 0) { |
| 438 | staleDatabaseLists -= 1; |
| 439 | return page(staleDatabases.map(toWireDatabase)); |
| 440 | } |
| 441 | return page( |
| 442 | Array.from(databases.values()) |
| 443 | .filter((database) => database.project.id === projectId) |
| 444 | .map(toWireDatabase), |
| 445 | ); |
| 446 | } |
| 447 | if (request.method === "POST") { |
| 448 | const input = request.bodyJson as { region?: string; isDefault?: boolean }; |
| 449 | calls.push(["createProjectDatabase", { projectId, input }]); |
| 450 | if (conflictNextProjectDatabaseCreate) { |
| 451 | conflictNextProjectDatabaseCreate = false; |
| 452 | return conflict("default database promotion in progress"); |
| 453 | } |
| 454 | const previousDefault = Array.from(databases.values()).find( |
| 455 | (database) => database.project.id === projectId && database.isDefault, |
| 456 | ); |
| 457 | const created = makeDatabase(projects.get(projectId)!, input); |
| 458 | if (staleNextProjectDatabaseObservation) { |
| 459 | staleNextProjectDatabaseObservation = false; |
| 460 | staleProjectReads = 1; |
| 461 | staleProjectDefaultRegion = previousDefault?.region?.id ?? null; |
| 462 | staleDatabaseLists = 1; |
| 463 | staleDatabases = Array.from(databases.values()) |
| 464 | .filter((database) => database.project.id === projectId) |
| 465 | .map((database) => ({ ...database, isDefault: database.id === previousDefault?.id })); |
| 466 | } |
| 467 | return data(toWireCreatedDatabase(created), { status: 201 }); |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | if (segments.length === 3 && segments[1] === "databases") { |
| 472 | const id = segments[2]!; |
| 473 | if (request.method === "GET") { |
| 474 | calls.push(["getDatabase", id]); |
| 475 | const database = databases.get(id); |
| 476 | return database === undefined ? notFound("not found") : data(toWireDatabase(database)); |
| 477 | } |
| 478 | if (request.method === "DELETE") { |
| 479 | calls.push(["deleteDatabase", id]); |
| 480 | databases.delete(id); |
| 481 | return json(null, { status: 204 }); |
| 482 | } |
| 483 | } |
| 484 | |
| 485 | if ( |
| 486 | segments.length === 4 && |
| 487 | segments[1] === "connections" && |
| 488 | segments[3] === "rotate" && |
| 489 | request.method === "POST" |
| 490 | ) { |
| 491 | const id = segments[2]!; |
| 492 | calls.push(["rotateConnection", id]); |
| 493 | const database = Array.from(databases.values()).find( |
| 494 | (candidate) => candidate.defaultConnectionId === id, |
| 495 | )!; |
| 496 | return data(apiConnection(database.id, id)); |
| 497 | } |
| 498 | |
| 499 | return unhandled(request); |
| 500 | }); |
| 501 | |
| 502 | return { |
| 503 | fake, |
| 504 | calls, |
| 505 | databases, |
| 506 | projects, |
| 507 | conflictNextProjectDatabaseCreate: () => { |
| 508 | conflictNextProjectDatabaseCreate = true; |
| 509 | }, |
| 510 | staleNextProjectDatabaseObservation: () => { |
| 511 | staleNextProjectDatabaseObservation = true; |
| 512 | }, |
| 513 | }; |
| 514 | }; |
| 515 | |
| 516 | const foreignProject = apiProject("project-foreign", "app"); |
| 517 | const refusalCloud = makeProjectCloud([foreignProject]); |
| 518 | const refusal = Test.make({ providers: projectLayer(refusalCloud.fake) }); |
| 519 | |
| 520 | refusal.test.provider( |
| 521 | "Plan refuses cold adoption of a foreign Prisma project", |
| 522 | (stack) => |
| 523 | Effect.gen(function* () { |
| 524 | refusalCloud.projects.clear(); |
| 525 | refusalCloud.projects.set(foreignProject.id, foreignProject); |
| 526 | refusalCloud.calls.length = 0; |
| 527 | yield* stack.destroy(); |
| 528 | |
| 529 | const result = yield* stack |
| 530 | .deploy(PrismaProject("Project", { name: "app", createDatabase: false })) |
| 531 | .pipe(Effect.result); |
| 532 | |
| 533 | expect(Result.isFailure(result)).toBe(true); |
| 534 | if (Result.isFailure(result)) { |
| 535 | expect(String(result.failure)).toContain("Cannot adopt resource"); |
| 536 | } |
| 537 | expect(refusalCloud.projects.get("project-foreign")?.name).toBe("app"); |
| 538 | expect(refusalCloud.calls.map(([operation]) => operation)).not.toContain("updateProject"); |
| 539 | |
| 540 | yield* stack.destroy(); |
| 541 | }), |
| 542 | { |
| 543 | tags: [ |
| 544 | "unit", |
| 545 | "provider:prisma", |
| 546 | "provider:prisma:database", |
| 547 | "provider:prisma:project", |
| 548 | "local", |
| 549 | ], |
| 550 | }, |
| 551 | ); |
| 552 | |
| 553 | const generatedProjectRecoveryCloud = makeProjectCloud(); |
| 554 | const generatedProjectRecovery = Test.make({ |
| 555 | providers: projectLayer(generatedProjectRecoveryCloud.fake), |
| 556 | }); |
| 557 | |
| 558 | generatedProjectRecovery.test.provider( |
| 559 | "generated Project physical names recover as owned for the same instance", |
| 560 | (stack) => |
| 561 | Effect.gen(function* () { |
| 562 | generatedProjectRecoveryCloud.projects.clear(); |
| 563 | yield* stack.destroy(); |
| 564 | const instanceId = "00000000000000000000000000000000"; |
| 565 | const name = yield* createPhysicalName({ id: "Project" }).pipe( |
| 566 | Effect.provideService(ResourceContext, resourceContext(instanceId)), |
| 567 | ); |
| 568 | generatedProjectRecoveryCloud.projects.set( |
| 569 | "project-generated", |
| 570 | apiProject("project-generated", name, null), |
| 571 | ); |
| 572 | const provider = yield* Provider.findProvider(PrismaProject); |
| 573 | const observed = yield* provider.read!({ |
| 574 | id: "Project", |
| 575 | instanceId, |
| 576 | olds: { createDatabase: false }, |
| 577 | output: undefined, |
| 578 | } as never).pipe(Effect.provideService(ResourceContext, resourceContext(instanceId))); |
| 579 | |
| 580 | expect(observed).toBeDefined(); |
| 581 | expect(Unowned.is(observed!)).toBe(false); |
| 582 | expect((observed as PrismaProject["Attributes"]).projectName).toBe(name); |
| 583 | generatedProjectRecoveryCloud.databases.set("database-new-default", { |
| 584 | ...apiDatabase("database-new-default", { |
| 585 | projectId: "project-generated", |
| 586 | name: "new-default", |
| 587 | isDefault: true, |
| 588 | }), |
| 589 | connections: [], |
| 590 | }); |
| 591 | const staleSecret = Redacted.make("postgres://old-project-secret"); |
| 592 | const switched = yield* provider.read!({ |
| 593 | id: "Project", |
| 594 | instanceId, |
| 595 | olds: { createDatabase: true }, |
| 596 | output: { |
| 597 | ...(observed as PrismaProject["Attributes"]), |
| 598 | databaseId: "database-old-default", |
| 599 | directConnectionString: staleSecret, |
| 600 | pooledConnectionString: staleSecret, |
| 601 | accelerateConnectionString: staleSecret, |
| 602 | password: Redacted.make("old-password"), |
| 603 | }, |
| 604 | } as never).pipe(Effect.provideService(ResourceContext, resourceContext(instanceId))); |
| 605 | expect((switched as PrismaProject["Attributes"]).databaseId).toBe("database-new-default"); |
| 606 | expect((switched as PrismaProject["Attributes"]).directConnectionString).toBeUndefined(); |
| 607 | expect((switched as PrismaProject["Attributes"]).password).toBeUndefined(); |
| 608 | const cannotDropAdoptedDefault = yield* provider |
| 609 | .reconcile({ |
| 610 | id: "Project", |
| 611 | instanceId, |
| 612 | news: { createDatabase: false }, |
| 613 | olds: undefined, |
| 614 | output: switched, |
| 615 | bindings: [], |
| 616 | } as never) |
| 617 | .pipe(Effect.provideService(ResourceContext, resourceContext(instanceId)), Effect.result); |
| 618 | expect(Result.isFailure(cannotDropAdoptedDefault)).toBe(true); |
| 619 | if (Result.isFailure(cannotDropAdoptedDefault)) { |
| 620 | expect(String(cannotDropAdoptedDefault.failure)).toContain("cannot be removed in place"); |
| 621 | } |
| 622 | generatedProjectRecoveryCloud.calls.length = 0; |
| 623 | const recoveredSecrets = yield* provider |
| 624 | .reconcile({ |
| 625 | id: "Project", |
| 626 | instanceId, |
| 627 | news: { createDatabase: true }, |
| 628 | olds: { createDatabase: true }, |
| 629 | output: switched, |
| 630 | bindings: [], |
| 631 | } as never) |
| 632 | .pipe(Effect.provideService(ResourceContext, resourceContext(instanceId))); |
| 633 | expect(Redacted.value(recoveredSecrets.directConnectionString!)).toContain( |
| 634 | "database-new-default", |
| 635 | ); |
| 636 | expect(generatedProjectRecoveryCloud.calls).toContainEqual([ |
| 637 | "rotateConnection", |
| 638 | "connection-database-new-default", |
| 639 | ]); |
| 640 | generatedProjectRecoveryCloud.projects.clear(); |
| 641 | generatedProjectRecoveryCloud.databases.clear(); |
| 642 | yield* stack.destroy(); |
| 643 | }), |
| 644 | { |
| 645 | tags: [ |
| 646 | "unit", |
| 647 | "provider:prisma", |
| 648 | "provider:prisma:database", |
| 649 | "provider:prisma:project", |
| 650 | "local", |
| 651 | ], |
| 652 | }, |
| 653 | ); |
| 654 | |
| 655 | const adoptionCloud = makeProjectCloud([foreignProject]); |
| 656 | const adoption = Test.make({ providers: projectLayer(adoptionCloud.fake), adopt: true }); |
| 657 | |
| 658 | adoption.test.provider( |
| 659 | "Plan adopts explicitly and applies write-only project settings", |
| 660 | (stack) => |
| 661 | Effect.gen(function* () { |
| 662 | adoptionCloud.projects.clear(); |
| 663 | adoptionCloud.projects.set(foreignProject.id, foreignProject); |
| 664 | adoptionCloud.calls.length = 0; |
| 665 | yield* stack.destroy(); |
| 666 | |
| 667 | const project = yield* stack.deploy( |
| 668 | PrismaProject("Project", { |
| 669 | name: "app", |
| 670 | createDatabase: true, |
| 671 | region: "us-east-1", |
| 672 | settings: {}, |
| 673 | }), |
| 674 | ); |
| 675 | |
| 676 | expect(project.projectId).toBe("project-foreign"); |
| 677 | expect(adoptionCloud.calls).toContainEqual([ |
| 678 | "updateProject", |
| 679 | { id: "project-foreign", input: { name: "app", settings: {} } }, |
| 680 | ]); |
| 681 | |
| 682 | yield* stack.destroy(); |
| 683 | }), |
| 684 | { |
| 685 | tags: [ |
| 686 | "unit", |
| 687 | "provider:prisma", |
| 688 | "provider:prisma:database", |
| 689 | "provider:prisma:project", |
| 690 | "local", |
| 691 | ], |
| 692 | }, |
| 693 | ); |
| 694 | |
| 695 | const replacementCloud = makeProjectCloud(); |
| 696 | const replacement = Test.make({ providers: projectLayer(replacementCloud.fake) }); |
| 697 | |
| 698 | replacement.test.provider( |
| 699 | "Apply refuses to replace a data-bearing default database for a region change", |
| 700 | (stack) => |
| 701 | Effect.gen(function* () { |
| 702 | replacementCloud.projects.clear(); |
| 703 | replacementCloud.calls.length = 0; |
| 704 | yield* stack.destroy(); |
| 705 | |
| 706 | const first = yield* stack.deploy( |
| 707 | PrismaProject("Project", { name: "app", createDatabase: true, region: "us-east-1" }), |
| 708 | ); |
| 709 | replacementCloud.calls.length = 0; |
| 710 | |
| 711 | const result = yield* stack |
| 712 | .deploy( |
| 713 | PrismaProject("Project", { |
| 714 | name: "app", |
| 715 | createDatabase: true, |
| 716 | region: "us-west-1" as const, |
| 717 | }), |
| 718 | ) |
| 719 | .pipe(Effect.result); |
| 720 | |
| 721 | expect(Result.isFailure(result)).toBe(true); |
| 722 | if (Result.isFailure(result)) { |
| 723 | expect(String(result.failure)).toContain("Cannot safely change"); |
| 724 | expect(String(result.failure)).toContain("explicit data migration"); |
| 725 | } |
| 726 | expect(first.projectId).toBeDefined(); |
| 727 | const operations = replacementCloud.calls.map(([operation]) => operation); |
| 728 | expect(operations).not.toContain("createProjectDatabase"); |
| 729 | expect(operations).not.toContain("deleteDatabase"); |
| 730 | expect(operations).not.toContain("deleteProject"); |
| 731 | expect(Array.from(replacementCloud.databases.values())).toHaveLength(1); |
| 732 | expect(Array.from(replacementCloud.databases.values())[0]?.region?.id).toBe("us-east-1"); |
| 733 | |
| 734 | yield* stack.destroy(); |
| 735 | }), |
| 736 | { |
| 737 | tags: [ |
| 738 | "unit", |
| 739 | "provider:prisma", |
| 740 | "provider:prisma:database", |
| 741 | "provider:prisma:project", |
| 742 | "local", |
| 743 | ], |
| 744 | }, |
| 745 | ); |
| 746 | |
| 747 | const eventuallyConsistentRegionCloud = makeProjectCloud(); |
| 748 | const eventuallyConsistentRegion = Test.make({ |
| 749 | providers: projectLayer(eventuallyConsistentRegionCloud.fake), |
| 750 | }); |
| 751 | |
| 752 | eventuallyConsistentRegion.test.provider( |
| 753 | "Project default database creation retries one stale observation", |
| 754 | (stack) => |
| 755 | Effect.gen(function* () { |
| 756 | eventuallyConsistentRegionCloud.projects.clear(); |
| 757 | eventuallyConsistentRegionCloud.databases.clear(); |
| 758 | yield* stack.destroy(); |
| 759 | |
| 760 | const first = yield* stack.deploy( |
| 761 | PrismaProject("Project", { name: "app", createDatabase: false }), |
| 762 | ); |
| 763 | eventuallyConsistentRegionCloud.calls.length = 0; |
| 764 | eventuallyConsistentRegionCloud.staleNextProjectDatabaseObservation(); |
| 765 | const second = yield* stack.deploy( |
| 766 | PrismaProject("Project", { |
| 767 | name: "app", |
| 768 | createDatabase: true, |
| 769 | region: "us-west-1" as const, |
| 770 | }), |
| 771 | ); |
| 772 | |
| 773 | expect(second.projectId).toBe(first.projectId); |
| 774 | expect(second.defaultRegion).toBe("us-west-1"); |
| 775 | expect(Redacted.value(second.directConnectionString!)).toContain(second.databaseId!); |
| 776 | expect( |
| 777 | eventuallyConsistentRegionCloud.calls.filter(([operation]) => operation === "getProject") |
| 778 | .length, |
| 779 | ).toBeGreaterThanOrEqual(3); |
| 780 | expect( |
| 781 | eventuallyConsistentRegionCloud.calls.filter( |
| 782 | ([operation]) => operation === "listProjectDatabases", |
| 783 | ).length, |
| 784 | ).toBeGreaterThanOrEqual(3); |
| 785 | |
| 786 | yield* stack.destroy(); |
| 787 | }), |
| 788 | { |
| 789 | tags: [ |
| 790 | "unit", |
| 791 | "provider:prisma", |
| 792 | "provider:prisma:database", |
| 793 | "provider:prisma:project", |
| 794 | "local", |
| 795 | ], |
| 796 | }, |
| 797 | ); |
| 798 | |
| 799 | const conflictingRegionCloud = makeProjectCloud(); |
| 800 | const conflictingRegion = Test.make({ providers: projectLayer(conflictingRegionCloud.fake) }); |
| 801 | |
| 802 | conflictingRegion.test.provider( |
| 803 | "Project default database creation rejects a conflict without an observed default", |
| 804 | (stack) => |
| 805 | Effect.gen(function* () { |
| 806 | conflictingRegionCloud.projects.clear(); |
| 807 | conflictingRegionCloud.databases.clear(); |
| 808 | yield* stack.destroy(); |
| 809 | |
| 810 | const first = yield* stack.deploy( |
| 811 | PrismaProject("Project", { name: "app", createDatabase: false }), |
| 812 | ); |
| 813 | conflictingRegionCloud.calls.length = 0; |
| 814 | conflictingRegionCloud.conflictNextProjectDatabaseCreate(); |
| 815 | |
| 816 | const result = yield* stack |
| 817 | .deploy( |
| 818 | PrismaProject("Project", { |
| 819 | name: "app", |
| 820 | createDatabase: true, |
| 821 | region: "us-west-1" as const, |
| 822 | }), |
| 823 | ) |
| 824 | .pipe(Effect.result); |
| 825 | |
| 826 | expect(Result.isFailure(result)).toBe(true); |
| 827 | if (Result.isFailure(result)) { |
| 828 | expect(String(result.failure)).toContain("does not expose the requested default database"); |
| 829 | } |
| 830 | expect(first.databaseId).toBeUndefined(); |
| 831 | expect(conflictingRegionCloud.databases.size).toBe(0); |
| 832 | expect(conflictingRegionCloud.calls.map(([operation]) => operation)).not.toContain( |
| 833 | "deleteDatabase", |
| 834 | ); |
| 835 | |
| 836 | conflictingRegionCloud.databases.clear(); |
| 837 | yield* stack.destroy(); |
| 838 | }), |
| 839 | { |
| 840 | tags: [ |
| 841 | "unit", |
| 842 | "provider:prisma", |
| 843 | "provider:prisma:database", |
| 844 | "provider:prisma:project", |
| 845 | "local", |
| 846 | ], |
| 847 | }, |
| 848 | ); |
| 849 | |
| 850 | const addDefaultCloud = makeProjectCloud(); |
| 851 | const addDefault = Test.make({ providers: projectLayer(addDefaultCloud.fake) }); |
| 852 | |
| 853 | addDefault.test.provider( |
| 854 | "Apply adds a missing Project default database without replacing the Project", |
| 855 | (stack) => |
| 856 | Effect.gen(function* () { |
| 857 | addDefaultCloud.projects.clear(); |
| 858 | addDefaultCloud.databases.clear(); |
| 859 | yield* stack.destroy(); |
| 860 | |
| 861 | const first = yield* stack.deploy( |
| 862 | PrismaProject("Project", { name: "app", createDatabase: false }), |
| 863 | ); |
| 864 | addDefaultCloud.calls.length = 0; |
| 865 | const second = yield* stack.deploy( |
| 866 | PrismaProject("Project", { |
| 867 | name: "app", |
| 868 | createDatabase: true, |
| 869 | region: "us-west-1" as const, |
| 870 | }), |
| 871 | ); |
| 872 | |
| 873 | expect(second.projectId).toBe(first.projectId); |
| 874 | expect(second.defaultRegion).toBe("us-west-1"); |
| 875 | expect(addDefaultCloud.databases.size).toBe(1); |
| 876 | expect(addDefaultCloud.calls.map(([operation]) => operation)).toContain( |
| 877 | "createProjectDatabase", |
| 878 | ); |
| 879 | expect(addDefaultCloud.calls.map(([operation]) => operation)).not.toContain("deleteProject"); |
| 880 | |
| 881 | yield* stack.destroy(); |
| 882 | }), |
| 883 | { |
| 884 | tags: [ |
| 885 | "unit", |
| 886 | "provider:prisma", |
| 887 | "provider:prisma:database", |
| 888 | "provider:prisma:project", |
| 889 | "local", |
| 890 | ], |
| 891 | }, |
| 892 | ); |
| 893 | |
| 894 | const removeDefaultCloud = makeProjectCloud(); |
| 895 | const removeDefault = Test.make({ providers: projectLayer(removeDefaultCloud.fake) }); |
| 896 | |
| 897 | removeDefault.test.provider( |
| 898 | "Apply replaces a Project when removing its last default database", |
| 899 | (stack) => |
| 900 | Effect.gen(function* () { |
| 901 | removeDefaultCloud.projects.clear(); |
| 902 | removeDefaultCloud.databases.clear(); |
| 903 | yield* stack.destroy(); |
| 904 | |
| 905 | const first = yield* stack.deploy( |
| 906 | PrismaProject("Project", { name: "app", createDatabase: true }), |
| 907 | ); |
| 908 | removeDefaultCloud.calls.length = 0; |
| 909 | const second = yield* stack.deploy( |
| 910 | PrismaProject("Project", { name: "app", createDatabase: false }), |
| 911 | ); |
| 912 | |
| 913 | expect(second.projectId).not.toBe(first.projectId); |
| 914 | expect(second.databaseId).toBeUndefined(); |
| 915 | const operations = removeDefaultCloud.calls.map(([operation]) => operation); |
| 916 | expect(operations.indexOf("deleteProject")).toBeLessThan(operations.indexOf("createProject")); |
| 917 | |
| 918 | yield* stack.destroy(); |
| 919 | }), |
| 920 | { |
| 921 | tags: [ |
| 922 | "unit", |
| 923 | "provider:prisma", |
| 924 | "provider:prisma:database", |
| 925 | "provider:prisma:project", |
| 926 | "local", |
| 927 | ], |
| 928 | }, |
| 929 | ); |
| 930 | |
| 931 | const apiDatabase = ( |
| 932 | id: string, |
| 933 | input: { |
| 934 | projectId: string; |
| 935 | name?: string; |
| 936 | region?: string; |
| 937 | isDefault?: boolean; |
| 938 | source?: ApiDatabase["source"]; |
| 939 | }, |
| 940 | ): ApiDatabase => ({ |
| 941 | id, |
| 942 | type: "database", |
| 943 | url: `https://api.prisma.test/v1/databases/${id}`, |
| 944 | name: input.name ?? `database-${id}`, |
| 945 | status: "ready", |
| 946 | createdAt, |
| 947 | isDefault: input.isDefault ?? false, |
| 948 | defaultConnectionId: `connection-${id}`, |
| 949 | connections: [apiConnection(id)], |
| 950 | project: { |
| 951 | id: input.projectId, |
| 952 | url: `https://api.prisma.test/v1/projects/${input.projectId}`, |
| 953 | name: "app", |
| 954 | }, |
| 955 | region: { id: input.region ?? "us-east-1", name: "Region" }, |
| 956 | source: input.source ?? { type: "empty" }, |
| 957 | branchId: null, |
| 958 | }); |
| 959 | |
| 960 | const makeDatabaseCloud = () => { |
| 961 | const databases = new Map<string, ApiDatabase>(); |
| 962 | const calls: Array<[string, unknown?]> = []; |
| 963 | const project = { defaultRegion: null as string | null }; |
| 964 | let nextId = 1; |
| 965 | // The same in-memory cloud, served over the wire for the Database resource. |
| 966 | const fake = makeFakeManagementApi((request) => { |
| 967 | const segments = request.pathname.split("/").filter((s) => s.length > 0); |
| 968 | |
| 969 | if (segments.length === 3 && segments[1] === "projects" && request.method === "GET") { |
| 970 | return data(toWireProject(apiProject(segments[2]!, "app", project.defaultRegion))); |
| 971 | } |
| 972 | |
| 973 | if (request.pathname === "/v1/databases" && request.method === "GET") { |
| 974 | return page(Array.from(databases.values()).map(toWireDatabase)); |
| 975 | } |
| 976 | if (request.pathname === "/v1/databases" && request.method === "POST") { |
| 977 | const input = request.bodyJson as { |
| 978 | projectId: string; |
| 979 | name?: string; |
| 980 | region?: string; |
| 981 | isDefault?: boolean; |
| 982 | source?: ApiDatabase["source"]; |
| 983 | }; |
| 984 | calls.push(["createDatabase", input]); |
| 985 | if (input.isDefault) { |
| 986 | for (const [id, database] of databases) { |
| 987 | if (database.project.id === input.projectId && database.isDefault) { |
| 988 | databases.set(id, { ...database, isDefault: false }); |
| 989 | } |
| 990 | } |
| 991 | } |
| 992 | const id = `database-${nextId++}`; |
| 993 | const database = apiDatabase(id, input); |
| 994 | databases.set(id, database); |
| 995 | return data(toWireCreatedDatabase(database), { status: 201 }); |
| 996 | } |
| 997 | |
| 998 | // No branches: the logical-ID lookup resolves no branch and falls back to the name. |
| 999 | if ( |
| 1000 | segments.length === 4 && |
| 1001 | segments[1] === "projects" && |
| 1002 | segments[3] === "branches" && |
| 1003 | request.method === "GET" |
| 1004 | ) { |
| 1005 | return page([]); |
| 1006 | } |
| 1007 | |
| 1008 | if ( |
| 1009 | segments.length === 4 && |
| 1010 | segments[1] === "projects" && |
| 1011 | segments[3] === "databases" && |
| 1012 | request.method === "GET" |
| 1013 | ) { |
| 1014 | const projectId = segments[2]!; |
| 1015 | return page( |
| 1016 | Array.from(databases.values()) |
| 1017 | .filter((database) => database.project.id === projectId) |
| 1018 | .map(toWireDatabase), |
| 1019 | ); |
| 1020 | } |
| 1021 | |
| 1022 | if (segments.length === 3 && segments[1] === "databases") { |
| 1023 | const id = segments[2]!; |
| 1024 | if (request.method === "GET") { |
| 1025 | calls.push(["getDatabase", id]); |
| 1026 | const database = databases.get(id); |
| 1027 | return database === undefined ? notFound("not found") : data(toWireDatabase(database)); |
| 1028 | } |
| 1029 | if (request.method === "PATCH") { |
| 1030 | const input = request.bodyJson as { name?: string }; |
| 1031 | const database = databases.get(id)!; |
| 1032 | const updated = { ...database, name: input.name ?? database.name }; |
| 1033 | databases.set(id, updated); |
| 1034 | return data(toWireDatabase(updated)); |
| 1035 | } |
| 1036 | if (request.method === "DELETE") { |
| 1037 | calls.push(["deleteDatabase", id]); |
| 1038 | databases.delete(id); |
| 1039 | return json(null, { status: 204 }); |
| 1040 | } |
| 1041 | } |
| 1042 | |
| 1043 | if ( |
| 1044 | segments.length === 4 && |
| 1045 | segments[1] === "connections" && |
| 1046 | segments[3] === "rotate" && |
| 1047 | request.method === "POST" |
| 1048 | ) { |
| 1049 | const id = segments[2]!; |
| 1050 | calls.push(["rotateConnection", id]); |
| 1051 | const database = Array.from(databases.values()).find( |
| 1052 | (candidate) => candidate.defaultConnectionId === id, |
| 1053 | )!; |
| 1054 | return data(apiConnection(database.id, id)); |
| 1055 | } |
| 1056 | |
| 1057 | return unhandled(request); |
| 1058 | }); |
| 1059 | |
| 1060 | return { fake, calls, databases, project }; |
| 1061 | }; |
| 1062 | |
| 1063 | const generatedDatabaseRecoveryCloud = makeDatabaseCloud(); |
| 1064 | const generatedDatabaseRecovery = Test.make({ |
| 1065 | providers: databaseLayer(generatedDatabaseRecoveryCloud.fake), |
| 1066 | }); |
| 1067 | |
| 1068 | generatedDatabaseRecovery.test.provider( |
| 1069 | "unnamed Database physical names recover exactly without adoption", |
| 1070 | (stack) => |
| 1071 | Effect.gen(function* () { |
| 1072 | generatedDatabaseRecoveryCloud.databases.clear(); |
| 1073 | yield* stack.destroy(); |
| 1074 | const instanceId = "00000000000000000000000000000000"; |
| 1075 | const name = yield* createPhysicalName({ id: "Database" }).pipe( |
| 1076 | Effect.provideService(ResourceContext, resourceContext(instanceId)), |
| 1077 | ); |
| 1078 | generatedDatabaseRecoveryCloud.databases.set("database-generated", { |
| 1079 | ...apiDatabase("database-generated", { projectId: "project-1", name, isDefault: false }), |
| 1080 | connections: [], |
| 1081 | }); |
| 1082 | const provider = yield* Provider.findProvider(PrismaDatabase); |
| 1083 | const observed = yield* provider.read!({ |
| 1084 | id: "Database", |
| 1085 | instanceId, |
| 1086 | olds: { project: "project-1", isDefault: false }, |
| 1087 | output: undefined, |
| 1088 | } as never).pipe(Effect.provideService(ResourceContext, resourceContext(instanceId))); |
| 1089 | |
| 1090 | expect(observed).toBeDefined(); |
| 1091 | expect(Unowned.is(observed!)).toBe(false); |
| 1092 | expect((observed as PrismaDatabase["Attributes"]).databaseName).toBe(name); |
| 1093 | const localSecret = Redacted.make("postgres://local-dev-secret"); |
| 1094 | const fromDev = yield* provider.read!({ |
| 1095 | id: "Database", |
| 1096 | instanceId, |
| 1097 | olds: { project: "project-1", isDefault: false }, |
| 1098 | output: { |
| 1099 | databaseId: "dev:database:Database", |
| 1100 | databaseName: "local", |
| 1101 | projectId: "dev:project:Project", |
| 1102 | status: "ready", |
| 1103 | region: null, |
| 1104 | isDefault: false, |
| 1105 | branchId: null, |
| 1106 | defaultConnectionId: null, |
| 1107 | createdAt, |
| 1108 | directConnectionString: localSecret, |
| 1109 | pooledConnectionString: localSecret, |
| 1110 | accelerateConnectionString: localSecret, |
| 1111 | host: "127.0.0.1", |
| 1112 | user: "postgres", |
| 1113 | password: Redacted.make("local-password"), |
| 1114 | }, |
| 1115 | } as never).pipe(Effect.provideService(ResourceContext, resourceContext(instanceId))); |
| 1116 | expect((fromDev as PrismaDatabase["Attributes"]).databaseId).toBe("database-generated"); |
| 1117 | expect((fromDev as PrismaDatabase["Attributes"]).directConnectionString).toBeUndefined(); |
| 1118 | expect((fromDev as PrismaDatabase["Attributes"]).password).toBeUndefined(); |
| 1119 | |
| 1120 | generatedDatabaseRecoveryCloud.calls.length = 0; |
| 1121 | const recovered = yield* provider |
| 1122 | .reconcile({ |
| 1123 | id: "Database", |
| 1124 | instanceId, |
| 1125 | news: { project: "project-1", isDefault: false }, |
| 1126 | olds: { project: "project-1", isDefault: false }, |
| 1127 | output: observed, |
| 1128 | bindings: [], |
| 1129 | } as never) |
| 1130 | .pipe(Effect.provideService(ResourceContext, resourceContext(instanceId))); |
| 1131 | expect(Redacted.value(recovered.directConnectionString!)).toContain("database-generated"); |
| 1132 | expect(generatedDatabaseRecoveryCloud.calls).toContainEqual([ |
| 1133 | "rotateConnection", |
| 1134 | "connection-database-generated", |
| 1135 | ]); |
| 1136 | |
| 1137 | const explicit = { |
| 1138 | ...apiDatabase("database-explicit", { |
| 1139 | projectId: "project-1", |
| 1140 | name: "explicit", |
| 1141 | isDefault: false, |
| 1142 | }), |
| 1143 | connections: [], |
| 1144 | }; |
| 1145 | generatedDatabaseRecoveryCloud.databases.set(explicit.id, explicit); |
| 1146 | const adoptionObserved = yield* provider.read!({ |
| 1147 | id: "ExplicitDatabase", |
| 1148 | instanceId, |
| 1149 | olds: { project: "project-1", name: "explicit", isDefault: false }, |
| 1150 | output: undefined, |
| 1151 | } as never).pipe(Effect.provideService(ResourceContext, resourceContext(instanceId))); |
| 1152 | expect(Unowned.is(adoptionObserved!)).toBe(true); |
| 1153 | const wrongRegion = yield* provider |
| 1154 | .reconcile({ |
| 1155 | id: "ExplicitDatabase", |
| 1156 | instanceId, |
| 1157 | news: { project: "project-1", name: "explicit", region: "us-west-1", isDefault: false }, |
| 1158 | olds: undefined, |
| 1159 | output: adoptionObserved, |
| 1160 | bindings: [], |
| 1161 | } as never) |
| 1162 | .pipe(Effect.provideService(ResourceContext, resourceContext(instanceId)), Effect.result); |
| 1163 | expect(Result.isFailure(wrongRegion)).toBe(true); |
| 1164 | if (Result.isFailure(wrongRegion)) { |
| 1165 | expect(String(wrongRegion.failure)).toContain("immutable region"); |
| 1166 | } |
| 1167 | const cannotPromoteAdopted = yield* provider |
| 1168 | .reconcile({ |
| 1169 | id: "ExplicitDatabase", |
| 1170 | instanceId, |
| 1171 | news: { project: "project-1", name: "explicit", isDefault: true }, |
| 1172 | olds: undefined, |
| 1173 | output: adoptionObserved, |
| 1174 | bindings: [], |
| 1175 | } as never) |
| 1176 | .pipe(Effect.provideService(ResourceContext, resourceContext(instanceId)), Effect.result); |
| 1177 | expect(Result.isFailure(cannotPromoteAdopted)).toBe(true); |
| 1178 | if (Result.isFailure(cannotPromoteAdopted)) { |
| 1179 | expect(String(cannotPromoteAdopted.failure)).toContain("cannot manage a default database"); |
| 1180 | } |
| 1181 | const adopted = yield* provider |
| 1182 | .reconcile({ |
| 1183 | id: "ExplicitDatabase", |
| 1184 | instanceId, |
| 1185 | news: { project: "project-1", name: "explicit", isDefault: false }, |
| 1186 | olds: undefined, |
| 1187 | output: adoptionObserved, |
| 1188 | bindings: [], |
| 1189 | } as never) |
| 1190 | .pipe(Effect.provideService(ResourceContext, resourceContext(instanceId))); |
| 1191 | expect(adopted.directConnectionString).toBeUndefined(); |
| 1192 | expect( |
| 1193 | generatedDatabaseRecoveryCloud.calls.filter( |
| 1194 | ([operation, id]) => |
| 1195 | operation === "rotateConnection" && id === "connection-database-explicit", |
| 1196 | ), |
| 1197 | ).toEqual([]); |
| 1198 | |
| 1199 | const adoptedWithRotation = yield* provider |
| 1200 | .reconcile({ |
| 1201 | id: "ExplicitDatabase", |
| 1202 | instanceId, |
| 1203 | news: { |
| 1204 | project: "project-1", |
| 1205 | name: "explicit", |
| 1206 | isDefault: false, |
| 1207 | rotateCredentialsOnAdopt: true, |
| 1208 | }, |
| 1209 | olds: undefined, |
| 1210 | output: adoptionObserved, |
| 1211 | bindings: [], |
| 1212 | } as never) |
| 1213 | .pipe(Effect.provideService(ResourceContext, resourceContext(instanceId))); |
| 1214 | expect(Redacted.value(adoptedWithRotation.directConnectionString!)).toContain( |
| 1215 | "database-explicit", |
| 1216 | ); |
| 1217 | expect(generatedDatabaseRecoveryCloud.calls).toContainEqual([ |
| 1218 | "rotateConnection", |
| 1219 | "connection-database-explicit", |
| 1220 | ]); |
| 1221 | generatedDatabaseRecoveryCloud.databases.clear(); |
| 1222 | yield* stack.destroy(); |
| 1223 | }), |
| 1224 | { tags: ["unit", "provider:prisma", "provider:prisma:database", "local"] }, |
| 1225 | ); |
| 1226 | |
| 1227 | it.effect( |
| 1228 | "refuses an undeletable standalone default database", |
| 1229 | () => { |
| 1230 | let created = false; |
| 1231 | const client = { |
| 1232 | createDatabase: () => |
| 1233 | Effect.sync(() => { |
| 1234 | created = true; |
| 1235 | throw new Error("must fail before create"); |
| 1236 | }), |
| 1237 | } as unknown as PrismaManagementClient; |
| 1238 | |
| 1239 | return Effect.gen(function* () { |
| 1240 | const provider = yield* PrismaDatabase.Provider; |
| 1241 | const error = yield* provider |
| 1242 | .reconcile({ |
| 1243 | id: "Database", |
| 1244 | instanceId: "00000000000000000000000000000000", |
| 1245 | news: { project: "project-1", name: "primary", region: "us-east-1", isDefault: true }, |
| 1246 | olds: undefined, |
| 1247 | output: undefined, |
| 1248 | bindings: [], |
| 1249 | } as never) |
| 1250 | .pipe(Effect.flip); |
| 1251 | |
| 1252 | expect(String(error)).toContain("could never be destroyed"); |
| 1253 | expect(created).toBe(false); |
| 1254 | }).pipe( |
| 1255 | Effect.provide(DatabaseProvider()), |
| 1256 | Effect.provide(Layer.succeed(PrismaClient, client)), |
| 1257 | Effect.provide(liveProviderContext), |
| 1258 | Effect.provide(testStackContext), |
| 1259 | Effect.provide(makeFakeManagementApi(unhandled).layer), |
| 1260 | Effect.provide(PlatformServices), |
| 1261 | ); |
| 1262 | }, |
| 1263 | { tags: ["unit", "provider:prisma", "provider:prisma:database", "local"] }, |
| 1264 | ); |
| 1265 | |
| 1266 | const inheritedRegionCloud = makeDatabaseCloud(); |
| 1267 | const inheritedRegion = Test.make({ providers: databaseLayer(inheritedRegionCloud.fake) }); |
| 1268 | |
| 1269 | inheritedRegion.test.provider( |
| 1270 | "Database region inherit falls back to the default database region", |
| 1271 | (stack) => |
| 1272 | Effect.gen(function* () { |
| 1273 | inheritedRegionCloud.databases.clear(); |
| 1274 | yield* stack.destroy(); |
| 1275 | inheritedRegionCloud.databases.set( |
| 1276 | "project-default", |
| 1277 | apiDatabase("project-default", { |
| 1278 | projectId: "project-1", |
| 1279 | name: "project-default", |
| 1280 | region: "us-east-1", |
| 1281 | isDefault: true, |
| 1282 | }), |
| 1283 | ); |
| 1284 | |
| 1285 | const first = yield* stack.deploy( |
| 1286 | PrismaDatabase("Database", { project: "project-1", name: "inherited", region: "inherit" }), |
| 1287 | ); |
| 1288 | expect(first.region).toBe("us-east-1"); |
| 1289 | |
| 1290 | inheritedRegionCloud.calls.length = 0; |
| 1291 | const second = yield* stack.deploy( |
| 1292 | PrismaDatabase("Database", { project: "project-1", name: "inherited", region: "inherit" }), |
| 1293 | ); |
| 1294 | expect(second.databaseId).toBe(first.databaseId); |
| 1295 | expect(inheritedRegionCloud.calls.map(([operation]) => operation)).not.toContain( |
| 1296 | "createDatabase", |
| 1297 | ); |
| 1298 | |
| 1299 | inheritedRegionCloud.databases.set("project-default", { |
| 1300 | ...inheritedRegionCloud.databases.get("project-default")!, |
| 1301 | region: { id: "us-west-1", name: "US West" }, |
| 1302 | }); |
| 1303 | inheritedRegionCloud.calls.length = 0; |
| 1304 | const moved = yield* stack.deploy( |
| 1305 | PrismaDatabase("Database", { project: "project-1", name: "inherited", region: "inherit" }), |
| 1306 | ); |
| 1307 | expect(moved.databaseId).not.toBe(first.databaseId); |
| 1308 | expect(moved.region).toBe("us-west-1"); |
| 1309 | expect(inheritedRegionCloud.calls.map(([operation]) => operation)).toContain( |
| 1310 | "createDatabase", |
| 1311 | ); |
| 1312 | |
| 1313 | yield* stack.destroy(); |
| 1314 | inheritedRegionCloud.databases.clear(); |
| 1315 | }), |
| 1316 | { tags: ["unit", "provider:prisma", "provider:prisma:database", "local"] }, |
| 1317 | ); |
| 1318 | |
| 1319 | const environmentVariable = { |
| 1320 | id: "env-1", |
| 1321 | type: "environment-variable" as const, |
| 1322 | url: "https://api.prisma.test/v1/environment-variables/env-1", |
| 1323 | projectId: "project-1", |
| 1324 | branchId: null, |
| 1325 | class: "production" as const, |
| 1326 | key: "TOKEN", |
| 1327 | valueKid: "kid-1", |
| 1328 | isManagedBySystem: false, |
| 1329 | createdAt, |
| 1330 | updatedAt: createdAt, |
| 1331 | }; |
| 1332 | const environmentSecrets = new Map([[environmentVariable.id, "foreign"]]); |
| 1333 | const environmentCalls: Array<[string, unknown?]> = []; |
| 1334 | const environmentClient = { |
| 1335 | listEnvironmentVariables: () => Effect.succeed([environmentVariable]), |
| 1336 | getEnvironmentVariable: (id: string) => Effect.succeed({ ...environmentVariable, id }), |
| 1337 | createEnvironmentVariable: () => |
| 1338 | Effect.fail( |
| 1339 | new PrismaApiError({ |
| 1340 | method: "POST", |
| 1341 | path: "/v1/environment-variables", |
| 1342 | status: 409, |
| 1343 | message: "already exists", |
| 1344 | }), |
| 1345 | ), |
| 1346 | updateEnvironmentVariable: (id: string, input: { value: string }) => |
| 1347 | Effect.sync(() => { |
| 1348 | environmentCalls.push(["updateEnvironmentVariable", { id, input }]); |
| 1349 | environmentSecrets.set(id, input.value); |
| 1350 | return { ...environmentVariable, id }; |
| 1351 | }), |
| 1352 | deleteEnvironmentVariable: (id: string) => |
| 1353 | Effect.sync(() => { |
| 1354 | environmentSecrets.delete(id); |
| 1355 | }), |
| 1356 | } as unknown as PrismaManagementClient; |
| 1357 | const environmentAdoption = Test.make({ |
| 1358 | providers: environmentVariableLayer(environmentClient), |
| 1359 | adopt: true, |
| 1360 | }); |
| 1361 | |
| 1362 | environmentAdoption.test.provider( |
| 1363 | "adoption and ordinary deploys always converge write-only environment secrets", |
| 1364 | (stack) => |
| 1365 | Effect.gen(function* () { |
| 1366 | environmentSecrets.clear(); |
| 1367 | environmentSecrets.set(environmentVariable.id, "foreign"); |
| 1368 | environmentCalls.length = 0; |
| 1369 | yield* stack.destroy(); |
| 1370 | |
| 1371 | const deploy = () => |
| 1372 | stack.deploy( |
| 1373 | PrismaEnvironmentVariable("Token", { |
| 1374 | project: "project-1", |
| 1375 | class: "production", |
| 1376 | key: "TOKEN", |
| 1377 | value: Redacted.make("desired"), |
| 1378 | }), |
| 1379 | ); |
| 1380 | |
| 1381 | yield* deploy(); |
| 1382 | expect(environmentSecrets.get("env-1")).toBe("desired"); |
| 1383 | |
| 1384 | environmentSecrets.set("env-1", "externally-drifted"); |
| 1385 | yield* deploy(); |
| 1386 | expect(environmentSecrets.get("env-1")).toBe("desired"); |
| 1387 | expect( |
| 1388 | environmentCalls.filter(([operation]) => operation === "updateEnvironmentVariable"), |
| 1389 | ).toHaveLength(2); |
| 1390 | |
| 1391 | yield* stack.destroy(); |
| 1392 | }), |
| 1393 | { tags: ["unit", "provider:prisma", "provider:prisma:environmentvariable", "local"] }, |
| 1394 | ); |
| 1395 | |
| 1396 | const customDomainCalls: Array<[string, unknown?]> = []; |
| 1397 | const customDomainCloud = new Map<string, ApiCustomDomain>(); |
| 1398 | let nextCustomDomainId = 1; |
| 1399 | const customDomainClient = { |
| 1400 | listAppDomains: (appId: string) => |
| 1401 | Effect.sync(() => { |
| 1402 | customDomainCalls.push(["listAppDomains", appId]); |
| 1403 | return Array.from(customDomainCloud.values()).filter((domain) => domain.appId === appId); |
| 1404 | }), |
| 1405 | getCustomDomain: (id: string) => |
| 1406 | Effect.suspend(() => { |
| 1407 | const domain = customDomainCloud.get(id); |
| 1408 | return domain |
| 1409 | ? Effect.succeed(domain) |
| 1410 | : Effect.fail( |
| 1411 | new PrismaApiError({ |
| 1412 | method: "GET", |
| 1413 | path: `/v1/domains/${id}`, |
| 1414 | status: 404, |
| 1415 | message: "not found", |
| 1416 | }), |
| 1417 | ); |
| 1418 | }), |
| 1419 | createAppDomain: (appId: string, input: { hostname: string }) => |
| 1420 | Effect.sync(() => { |
| 1421 | customDomainCalls.push(["createAppDomain", { appId, input }]); |
| 1422 | const id = `domain-${nextCustomDomainId++}`; |
| 1423 | const domain: ApiCustomDomain = { |
| 1424 | id, |
| 1425 | type: "custom-domain" as const, |
| 1426 | url: `https://api.prisma.test/v1/domains/${id}`, |
| 1427 | hostname: input.hostname, |
| 1428 | appId, |
| 1429 | status: "pending_dns" as const, |
| 1430 | foundryStatus: "pending", |
| 1431 | failureReason: null, |
| 1432 | failureCategory: null, |
| 1433 | certExpiresAt: null, |
| 1434 | dnsRecords: [ |
| 1435 | { type: "CNAME" as const, name: input.hostname, value: "api.prisma.build", ttl: null }, |
| 1436 | ], |
| 1437 | createdAt, |
| 1438 | updatedAt: createdAt, |
| 1439 | }; |
| 1440 | customDomainCloud.set(id, domain); |
| 1441 | return { status: 201 as const, domain }; |
| 1442 | }), |
| 1443 | retryCustomDomain: (id: string) => |
| 1444 | Effect.sync(() => { |
| 1445 | customDomainCalls.push(["retryCustomDomain", id]); |
| 1446 | const domain = customDomainCloud.get(id)!; |
| 1447 | const retried: ApiCustomDomain = { |
| 1448 | ...domain, |
| 1449 | status: "verifying", |
| 1450 | foundryStatus: "provisioning", |
| 1451 | failureReason: null, |
| 1452 | failureCategory: null, |
| 1453 | updatedAt: createdAt, |
| 1454 | }; |
| 1455 | customDomainCloud.set(id, retried); |
| 1456 | return retried; |
| 1457 | }), |
| 1458 | deleteCustomDomain: (id: string) => |
| 1459 | Effect.sync(() => { |
| 1460 | customDomainCalls.push(["deleteCustomDomain", id]); |
| 1461 | customDomainCloud.delete(id); |
| 1462 | }), |
| 1463 | } as unknown as PrismaManagementClient; |
| 1464 | const customDomains = Test.make({ providers: customDomainLayer(customDomainClient) }); |
| 1465 | |
| 1466 | customDomains.test.provider( |
| 1467 | "custom domains use the canonical App API and exact status fields", |
| 1468 | (stack) => |
| 1469 | Effect.gen(function* () { |
| 1470 | customDomainCalls.length = 0; |
| 1471 | customDomainCloud.clear(); |
| 1472 | nextCustomDomainId = 1; |
| 1473 | yield* stack.destroy(); |
| 1474 | |
| 1475 | const domain = yield* stack.deploy( |
| 1476 | PrismaCustomDomain("Domain", { |
| 1477 | app: { appId: Output.asOutput("app-1") } as unknown as App, |
| 1478 | hostname: "NEW.EXAMPLE.COM.", |
| 1479 | }), |
| 1480 | ); |
| 1481 | |
| 1482 | expect(domain.appId).toBe("app-1"); |
| 1483 | expect(domain.hostname).toBe("new.example.com"); |
| 1484 | expect(domain.foundryStatus).toBe("pending"); |
| 1485 | expect(customDomainCalls).toContainEqual(["listAppDomains", "app-1"]); |
| 1486 | expect(customDomainCalls).toContainEqual([ |
| 1487 | "createAppDomain", |
| 1488 | { appId: "app-1", input: { hostname: "new.example.com" } }, |
| 1489 | ]); |
| 1490 | |
| 1491 | const replacement = domain; |
| 1492 | |
| 1493 | customDomainCloud.set(replacement.customDomainId, { |
| 1494 | ...customDomainCloud.get(replacement.customDomainId)!, |
| 1495 | status: "failed", |
| 1496 | foundryStatus: "failed", |
| 1497 | failureReason: "DNS verification failed", |
| 1498 | failureCategory: "dns", |
| 1499 | }); |
| 1500 | const provider = yield* Provider.findProvider(PrismaCustomDomain); |
| 1501 | const failed = yield* provider.read!({ |
| 1502 | id: "Domain", |
| 1503 | instanceId: "00000000000000000000000000000000", |
| 1504 | olds: { app: "app-1", hostname: "new.example.com" }, |
| 1505 | output: replacement, |
| 1506 | } as never); |
| 1507 | const failedDiff = yield* provider.diff!({ |
| 1508 | id: "Domain", |
| 1509 | instanceId: "00000000000000000000000000000000", |
| 1510 | olds: { app: "app-1", hostname: "new.example.com" }, |
| 1511 | news: { app: "app-1", hostname: "new.example.com" }, |
| 1512 | output: failed, |
| 1513 | oldBindings: [], |
| 1514 | newBindings: [], |
| 1515 | } as never); |
| 1516 | expect(failedDiff).toEqual({ action: "update" }); |
| 1517 | const activeDiff = yield* provider.diff!({ |
| 1518 | id: "Domain", |
| 1519 | instanceId: "00000000000000000000000000000000", |
| 1520 | olds: { app: "app-1", hostname: "new.example.com" }, |
| 1521 | news: { app: "app-1", hostname: "new.example.com" }, |
| 1522 | output: { ...replacement, status: "active" }, |
| 1523 | oldBindings: [], |
| 1524 | newBindings: [], |
| 1525 | } as never); |
| 1526 | expect(activeDiff).toBeUndefined(); |
| 1527 | customDomainCalls.length = 0; |
| 1528 | const retried = yield* provider.reconcile({ |
| 1529 | id: "Domain", |
| 1530 | instanceId: "00000000000000000000000000000000", |
| 1531 | news: { app: "app-1", hostname: "new.example.com" }, |
| 1532 | olds: { app: "app-1", hostname: "new.example.com" }, |
| 1533 | output: failed, |
| 1534 | bindings: [], |
| 1535 | } as never); |
| 1536 | expect(retried.customDomainId).toBe(replacement.customDomainId); |
| 1537 | expect(retried.status).toBe("verifying"); |
| 1538 | expect(customDomainCalls).toContainEqual(["retryCustomDomain", replacement.customDomainId]); |
| 1539 | expect( |
| 1540 | customDomainCalls.filter(([operation]) => operation === "retryCustomDomain"), |
| 1541 | ).toHaveLength(1); |
| 1542 | const moveDiff = yield* provider.diff!({ |
| 1543 | id: "Domain", |
| 1544 | instanceId: "00000000000000000000000000000000", |
| 1545 | olds: { app: "app-1", hostname: "new.example.com" }, |
| 1546 | news: { app: "app-2", hostname: "new.example.com" }, |
| 1547 | output: retried, |
| 1548 | oldBindings: [], |
| 1549 | newBindings: [], |
| 1550 | } as never).pipe(Effect.result); |
| 1551 | expect(Result.isFailure(moveDiff)).toBe(true); |
| 1552 | if (Result.isFailure(moveDiff)) { |
| 1553 | expect(String(moveDiff.failure)).toContain("cannot atomically replace"); |
| 1554 | } |
| 1555 | const hostnameDiff = yield* provider.diff!({ |
| 1556 | id: "Domain", |
| 1557 | instanceId: "00000000000000000000000000000000", |
| 1558 | olds: { app: "app-1", hostname: "new.example.com" }, |
| 1559 | news: { app: "app-1", hostname: "other.example.com" }, |
| 1560 | output: retried, |
| 1561 | oldBindings: [], |
| 1562 | newBindings: [], |
| 1563 | } as never).pipe(Effect.result); |
| 1564 | expect(Result.isFailure(hostnameDiff)).toBe(true); |
| 1565 | |
| 1566 | const mismatch = yield* provider |
| 1567 | .reconcile({ |
| 1568 | id: "Domain", |
| 1569 | instanceId: "00000000000000000000000000000000", |
| 1570 | news: { app: "app-2", hostname: "new.example.com" }, |
| 1571 | olds: { app: "app-1", hostname: "new.example.com" }, |
| 1572 | output: retried, |
| 1573 | bindings: [], |
| 1574 | } as never) |
| 1575 | .pipe(Effect.result); |
| 1576 | expect(Result.isFailure(mismatch)).toBe(true); |
| 1577 | |
| 1578 | yield* stack.destroy(); |
| 1579 | }), |
| 1580 | { |
| 1581 | tags: [ |
| 1582 | "unit", |
| 1583 | "provider:prisma", |
| 1584 | "provider:prisma:app", |
| 1585 | "provider:prisma:customdomain", |
| 1586 | "local", |
| 1587 | ], |
| 1588 | }, |
| 1589 | ); |
| 1590 | |
| 1591 | const sourceRepositoryCloud = new Map<string, ApiSourceRepository>(); |
| 1592 | const sourceRepositoryCalls: Array<[string, unknown?]> = []; |
| 1593 | let nextSourceRepositoryId = 1; |
| 1594 | const sourceRepositoryClient = { |
| 1595 | listProjects: () => |
| 1596 | Effect.succeed([apiProject("project-1", "one", null), apiProject("project-2", "two", null)]), |
| 1597 | listSourceRepositories: ({ projectId }: { projectId: string }) => |
| 1598 | Effect.succeed( |
| 1599 | Array.from(sourceRepositoryCloud.values()).filter( |
| 1600 | (repository) => repository.projectId === projectId && repository.status === "active", |
| 1601 | ), |
| 1602 | ), |
| 1603 | listApps: () => Effect.succeed([]), |
| 1604 | listProjectDatabases: () => Effect.succeed([]), |
| 1605 | listBranches: (projectId: string) => |
| 1606 | Effect.succeed([ |
| 1607 | { |
| 1608 | id: `branch-${projectId}`, |
| 1609 | type: "branch" as const, |
| 1610 | url: `https://api.prisma.test/v1/branches/branch-${projectId}`, |
| 1611 | gitName: "main", |
| 1612 | isDefault: true, |
| 1613 | role: "production" as const, |
| 1614 | createdAt, |
| 1615 | updatedAt: createdAt, |
| 1616 | project: { |
| 1617 | id: projectId, |
| 1618 | url: `https://api.prisma.test/v1/projects/${projectId}`, |
| 1619 | name: projectId, |
| 1620 | }, |
| 1621 | }, |
| 1622 | ]), |
| 1623 | getSourceRepository: (id: string) => |
| 1624 | Effect.suspend(() => { |
| 1625 | const repository = sourceRepositoryCloud.get(id); |
| 1626 | return repository?.status === "active" |
| 1627 | ? Effect.succeed(repository) |
| 1628 | : Effect.fail( |
| 1629 | new PrismaApiError({ |
| 1630 | method: "GET", |
| 1631 | path: `/v1/source-repositories/${id}`, |
| 1632 | status: 404, |
| 1633 | message: "not found", |
| 1634 | }), |
| 1635 | ); |
| 1636 | }), |
| 1637 | createSourceRepository: (input: { |
| 1638 | projectId: string; |
| 1639 | provider: "github"; |
| 1640 | providerRepositoryId: number; |
| 1641 | installationId?: string; |
| 1642 | }) => |
| 1643 | Effect.suspend(() => { |
| 1644 | sourceRepositoryCalls.push(["createSourceRepository", input]); |
| 1645 | const conflict = Array.from(sourceRepositoryCloud.values()).some( |
| 1646 | (repository) => |
| 1647 | repository.status === "active" && |
| 1648 | (repository.projectId === input.projectId || |
| 1649 | repository.repoId === input.providerRepositoryId), |
| 1650 | ); |
| 1651 | if (conflict) { |
| 1652 | return Effect.fail( |
| 1653 | new PrismaApiError({ |
| 1654 | method: "POST", |
| 1655 | path: "/v1/source-repositories", |
| 1656 | status: 409, |
| 1657 | message: "already linked", |
| 1658 | }), |
| 1659 | ); |
| 1660 | } |
| 1661 | const id = `source-${nextSourceRepositoryId++}`; |
| 1662 | const repository: ApiSourceRepository = { |
| 1663 | id, |
| 1664 | type: "source-repository", |
| 1665 | url: `https://api.prisma.test/v1/source-repositories/${id}`, |
| 1666 | repoId: input.providerRepositoryId, |
| 1667 | provider: input.provider, |
| 1668 | repoFullName: `owner/repo-${input.providerRepositoryId}`, |
| 1669 | defaultBranch: "main", |
| 1670 | isPrivate: false, |
| 1671 | status: "active", |
| 1672 | projectId: input.projectId, |
| 1673 | installationId: input.installationId ?? "installation-auto", |
| 1674 | createdAt, |
| 1675 | updatedAt: createdAt, |
| 1676 | }; |
| 1677 | sourceRepositoryCloud.set(id, repository); |
| 1678 | return Effect.succeed(repository); |
| 1679 | }), |
| 1680 | deleteSourceRepository: (id: string) => |
| 1681 | Effect.sync(() => { |
| 1682 | sourceRepositoryCalls.push(["deleteSourceRepository", id]); |
| 1683 | const repository = sourceRepositoryCloud.get(id); |
| 1684 | if (repository) { |
| 1685 | sourceRepositoryCloud.set(id, { ...repository, status: "archived" }); |
| 1686 | } |
| 1687 | }), |
| 1688 | } as unknown as PrismaManagementClient; |
| 1689 | const sourceRepositories = Test.make({ providers: sourceRepositoryLayer(sourceRepositoryClient) }); |
| 1690 | |
| 1691 | sourceRepositories.test.provider( |
| 1692 | "source repository links reject non-atomic relinks without mutating the live link", |
| 1693 | (stack) => |
| 1694 | Effect.gen(function* () { |
| 1695 | sourceRepositoryCloud.clear(); |
| 1696 | sourceRepositoryCalls.length = 0; |
| 1697 | nextSourceRepositoryId = 1; |
| 1698 | yield* stack.destroy(); |
| 1699 | |
| 1700 | const first = yield* stack.deploy( |
| 1701 | PrismaSourceRepository("Repository", { project: "project-1", providerRepositoryId: 123 }), |
| 1702 | ); |
| 1703 | sourceRepositoryCalls.length = 0; |
| 1704 | const relink = yield* stack |
| 1705 | .deploy( |
| 1706 | PrismaSourceRepository("Repository", { project: "project-2", providerRepositoryId: 456 }), |
| 1707 | ) |
| 1708 | .pipe(Effect.result); |
| 1709 | expect(Result.isFailure(relink)).toBe(true); |
| 1710 | if (Result.isFailure(relink)) { |
| 1711 | expect(String(relink.failure)).toContain("cannot be replaced atomically"); |
| 1712 | } |
| 1713 | expect(sourceRepositoryCalls).toEqual([]); |
| 1714 | expect(sourceRepositoryCloud.get(first.sourceRepositoryId)?.status).toBe("active"); |
| 1715 | |
| 1716 | const provider = yield* PrismaSourceRepository.Provider; |
| 1717 | const archivedDiff = yield* provider.diff!({ |
| 1718 | id: "Repository", |
| 1719 | instanceId: "00000000000000000000000000000000", |
| 1720 | olds: { project: "project-1", providerRepositoryId: 123 }, |
| 1721 | news: { project: "project-1", providerRepositoryId: 123 }, |
| 1722 | output: { ...first, status: "archived" as const }, |
| 1723 | oldBindings: [], |
| 1724 | newBindings: [], |
| 1725 | } as never).pipe(Effect.result); |
| 1726 | expect(Result.isFailure(archivedDiff)).toBe(true); |
| 1727 | |
| 1728 | yield* stack.destroy(); |
| 1729 | expect(sourceRepositoryCloud.get(first.sourceRepositoryId)?.status).toBe("archived"); |
| 1730 | }), |
| 1731 | { |
| 1732 | tags: [ |
| 1733 | "unit", |
| 1734 | "provider:prisma", |
| 1735 | "provider:prisma:project", |
| 1736 | "provider:prisma:sourcerepository", |
| 1737 | "local", |
| 1738 | ], |
| 1739 | }, |
| 1740 | ); |
| 1741 | |
| 1742 | const branchCloud = new Map<string, ApiBranch>(); |
| 1743 | const branchCalls: Array<[string, unknown?]> = []; |
| 1744 | let nextBranchId = 1; |
| 1745 | const branchClient = { |
| 1746 | listProjects: () => Effect.succeed([apiProject("project-1", "app")]), |
| 1747 | listBranches: (_projectId: string, query?: { gitName?: string }) => |
| 1748 | Effect.succeed( |
| 1749 | Array.from(branchCloud.values()).filter( |
| 1750 | (branch) => query?.gitName === undefined || branch.gitName === query.gitName, |
| 1751 | ), |
| 1752 | ), |
| 1753 | getBranch: (id: string) => Effect.succeed(branchCloud.get(id)!), |
| 1754 | createBranch: (projectId: string, input: { gitName: string; isDefault?: boolean }) => |
| 1755 | Effect.sync(() => { |
| 1756 | branchCalls.push(["createBranch", { projectId, input }]); |
| 1757 | const first = branchCloud.size === 0; |
| 1758 | const makeDefault = first || input.isDefault === true; |
| 1759 | if (makeDefault) { |
| 1760 | for (const [id, branch] of branchCloud) { |
| 1761 | branchCloud.set(id, { ...branch, isDefault: false }); |
| 1762 | } |
| 1763 | } |
| 1764 | const id = `branch-${nextBranchId++}`; |
| 1765 | const branch = { |
| 1766 | id, |
| 1767 | type: "branch" as const, |
| 1768 | url: `https://api.prisma.test/v1/branches/${id}`, |
| 1769 | gitName: input.gitName, |
| 1770 | isDefault: makeDefault, |
| 1771 | role: first ? ("production" as const) : ("preview" as const), |
| 1772 | createdAt, |
| 1773 | updatedAt: createdAt, |
| 1774 | project: { |
| 1775 | id: projectId, |
| 1776 | url: `https://api.prisma.test/v1/projects/${projectId}`, |
| 1777 | name: "app", |
| 1778 | }, |
| 1779 | }; |
| 1780 | branchCloud.set(id, branch); |
| 1781 | return branch; |
| 1782 | }), |
| 1783 | updateBranch: (id: string, input: { isDefault?: boolean | null }) => |
| 1784 | Effect.sync(() => { |
| 1785 | branchCalls.push(["updateBranch", { id, input }]); |
| 1786 | if (input.isDefault !== true) { |
| 1787 | throw new Error("the Management API rejects default demotion"); |
| 1788 | } |
| 1789 | for (const [branchId, branch] of branchCloud) { |
| 1790 | branchCloud.set(branchId, { ...branch, isDefault: branchId === id }); |
| 1791 | } |
| 1792 | return branchCloud.get(id)!; |
| 1793 | }), |
| 1794 | deleteBranch: (id: string) => |
| 1795 | Effect.sync(() => { |
| 1796 | branchCalls.push(["deleteBranch", id]); |
| 1797 | branchCloud.delete(id); |
| 1798 | }), |
| 1799 | } as unknown as PrismaManagementClient; |
| 1800 | |
| 1801 | // The same in-memory branch cloud, served over the wire. |
| 1802 | const branchFake = makeFakeManagementApi((request) => { |
| 1803 | const segments = request.pathname.split("/").filter((s) => s.length > 0); |
| 1804 | |
| 1805 | if (request.pathname === "/v1/projects" && request.method === "GET") { |
| 1806 | return page([toWireProject(apiProject("project-1", "app"))]); |
| 1807 | } |
| 1808 | |
| 1809 | if (segments.length === 4 && segments[1] === "projects" && segments[3] === "branches") { |
| 1810 | const projectId = segments[2]!; |
| 1811 | if (request.method === "GET") { |
| 1812 | const gitName = request.search.includes("gitName=") |
| 1813 | ? new URLSearchParams(request.search).get("gitName") |
| 1814 | : null; |
| 1815 | return page( |
| 1816 | Array.from(branchCloud.values()).filter( |
| 1817 | (branch) => gitName === null || branch.gitName === gitName, |
| 1818 | ), |
| 1819 | ); |
| 1820 | } |
| 1821 | if (request.method === "POST") { |
| 1822 | const input = request.bodyJson as { gitName: string; isDefault?: boolean }; |
| 1823 | branchCalls.push(["createBranch", { projectId, input }]); |
| 1824 | const first = branchCloud.size === 0; |
| 1825 | const makeDefault = first || input.isDefault === true; |
| 1826 | if (makeDefault) { |
| 1827 | for (const [id, branch] of branchCloud) { |
| 1828 | branchCloud.set(id, { ...branch, isDefault: false }); |
| 1829 | } |
| 1830 | } |
| 1831 | const id = `branch-${nextBranchId++}`; |
| 1832 | const branch = { |
| 1833 | id, |
| 1834 | type: "branch" as const, |
| 1835 | url: `https://api.prisma.test/v1/branches/${id}`, |
| 1836 | gitName: input.gitName, |
| 1837 | isDefault: makeDefault, |
| 1838 | role: first ? ("production" as const) : ("preview" as const), |
| 1839 | createdAt, |
| 1840 | updatedAt: createdAt, |
| 1841 | project: { |
| 1842 | id: projectId, |
| 1843 | url: `https://api.prisma.test/v1/projects/${projectId}`, |
| 1844 | name: "app", |
| 1845 | }, |
| 1846 | }; |
| 1847 | branchCloud.set(id, branch); |
| 1848 | return data(branch, { status: 201 }); |
| 1849 | } |
| 1850 | } |
| 1851 | |
| 1852 | if (segments.length === 3 && segments[1] === "branches") { |
| 1853 | const id = segments[2]!; |
| 1854 | if (request.method === "GET") { |
| 1855 | const branch = branchCloud.get(id); |
| 1856 | return branch === undefined ? notFound("not found") : data(branch); |
| 1857 | } |
| 1858 | if (request.method === "PATCH") { |
| 1859 | const input = request.bodyJson as { isDefault?: boolean | null }; |
| 1860 | branchCalls.push(["updateBranch", { id, input }]); |
| 1861 | if (input.isDefault !== true) { |
| 1862 | throw new Error("the Management API rejects default demotion"); |
| 1863 | } |
| 1864 | for (const [branchId, branch] of branchCloud) { |
| 1865 | branchCloud.set(branchId, { ...branch, isDefault: branchId === id }); |
| 1866 | } |
| 1867 | return data(branchCloud.get(id)!); |
| 1868 | } |
| 1869 | if (request.method === "DELETE") { |
| 1870 | branchCalls.push(["deleteBranch", id]); |
| 1871 | branchCloud.delete(id); |
| 1872 | return json(null, { status: 204 }); |
| 1873 | } |
| 1874 | } |
| 1875 | |
| 1876 | return unhandled(request); |
| 1877 | }); |
| 1878 | |
| 1879 | const branches = Test.make({ providers: branchLayer(branchFake) }); |
| 1880 | |
| 1881 | branches.test.provider( |
| 1882 | "branch promotion persists and restores the displaced default on destroy", |
| 1883 | (stack) => |
| 1884 | Effect.gen(function* () { |
| 1885 | branchCloud.clear(); |
| 1886 | branchCalls.length = 0; |
| 1887 | nextBranchId = 1; |
| 1888 | yield* stack.destroy(); |
| 1889 | |
| 1890 | const main: ApiBranch = { |
| 1891 | id: "branch-main", |
| 1892 | type: "branch", |
| 1893 | url: "https://api.prisma.test/v1/branches/branch-main", |
| 1894 | gitName: "main", |
| 1895 | isDefault: true, |
| 1896 | role: "production", |
| 1897 | createdAt, |
| 1898 | updatedAt: createdAt, |
| 1899 | project: { |
| 1900 | id: "project-1", |
| 1901 | url: "https://api.prisma.test/v1/projects/project-1", |
| 1902 | name: "app", |
| 1903 | }, |
| 1904 | }; |
| 1905 | branchCloud.set(main.id, main); |
| 1906 | |
| 1907 | const preview = yield* stack.deploy( |
| 1908 | PrismaBranch("Preview", { project: "project-1", gitName: "preview", isDefault: true }), |
| 1909 | ); |
| 1910 | expect(preview.isDefault).toBe(true); |
| 1911 | expect(preview.role).toBe("preview"); |
| 1912 | expect(preview.previousDefaultBranchId).toBe(main.id); |
| 1913 | expect(branchCloud.get(main.id)?.isDefault).toBe(false); |
| 1914 | expect(branchCloud.get(main.id)?.role).toBe("production"); |
| 1915 | |
| 1916 | const provider = yield* Provider.findProvider(PrismaBranch); |
| 1917 | const alreadyDefaultDiff = yield* provider.diff!({ |
| 1918 | id: "Preview", |
| 1919 | instanceId: "00000000000000000000000000000000", |
| 1920 | olds: { project: "project-1", gitName: "preview", isDefault: true }, |
| 1921 | news: { project: "project-1", gitName: "preview", isDefault: true }, |
| 1922 | output: preview, |
| 1923 | oldBindings: [], |
| 1924 | newBindings: [], |
| 1925 | } as never); |
| 1926 | expect(alreadyDefaultDiff).toBeUndefined(); |
| 1927 | |
| 1928 | // A different API client can promote another branch, atomically |
| 1929 | // demoting the desired default. The next deploy must observe and heal it |
| 1930 | // even though desired props did not change. |
| 1931 | branchCloud.set(main.id, { ...branchCloud.get(main.id)!, isDefault: true }); |
| 1932 | branchCloud.set(preview.branchId, { |
| 1933 | ...branchCloud.get(preview.branchId)!, |
| 1934 | isDefault: false, |
| 1935 | }); |
| 1936 | branchCalls.length = 0; |
| 1937 | const observed = yield* provider.read!({ |
| 1938 | id: "Preview", |
| 1939 | instanceId: "00000000000000000000000000000000", |
| 1940 | olds: { project: "project-1", gitName: "preview", isDefault: true }, |
| 1941 | output: preview, |
| 1942 | } as never); |
| 1943 | const driftDiff = yield* provider.diff!({ |
| 1944 | id: "Preview", |
| 1945 | instanceId: "00000000000000000000000000000000", |
| 1946 | olds: { project: "project-1", gitName: "preview", isDefault: true }, |
| 1947 | news: { project: "project-1", gitName: "preview", isDefault: true }, |
| 1948 | output: observed, |
| 1949 | oldBindings: [], |
| 1950 | newBindings: [], |
| 1951 | } as never); |
| 1952 | expect(driftDiff).toEqual({ action: "update" }); |
| 1953 | yield* provider.reconcile({ |
| 1954 | id: "Preview", |
| 1955 | instanceId: "00000000000000000000000000000000", |
| 1956 | news: { project: "project-1", gitName: "preview", isDefault: true }, |
| 1957 | olds: { project: "project-1", gitName: "preview", isDefault: true }, |
| 1958 | output: observed, |
| 1959 | bindings: [], |
| 1960 | } as never); |
| 1961 | expect(branchCloud.get(preview.branchId)?.isDefault).toBe(true); |
| 1962 | expect(branchCalls).toContainEqual([ |
| 1963 | "updateBranch", |
| 1964 | { id: preview.branchId, input: { isDefault: true } }, |
| 1965 | ]); |
| 1966 | expect(yield* provider.list()).toEqual([]); |
| 1967 | branchCalls.length = 0; |
| 1968 | yield* stack.destroy(); |
| 1969 | expect(branchCloud.get(main.id)?.isDefault).toBe(true); |
| 1970 | expect(branchCloud.has(preview.branchId)).toBe(false); |
| 1971 | expect(branchCalls).toContainEqual([ |
| 1972 | "updateBranch", |
| 1973 | { id: main.id, input: { isDefault: true } }, |
| 1974 | ]); |
| 1975 | expect(branchCalls).toContainEqual(["deleteBranch", preview.branchId]); |
| 1976 | |
| 1977 | branchCloud.clear(); |
| 1978 | branchCalls.length = 0; |
| 1979 | const firstBranch = yield* provider |
| 1980 | .reconcile({ |
| 1981 | id: "UnsafeFirst", |
| 1982 | instanceId: "00000000000000000000000000000000", |
| 1983 | news: { project: "project-1", gitName: "main", isDefault: false }, |
| 1984 | olds: undefined, |
| 1985 | output: undefined, |
| 1986 | bindings: [], |
| 1987 | } as never) |
| 1988 | .pipe(Effect.result); |
| 1989 | expect(Result.isFailure(firstBranch)).toBe(true); |
| 1990 | if (Result.isFailure(firstBranch)) { |
| 1991 | expect(String(firstBranch.failure)).toContain("undeletable production branch"); |
| 1992 | } |
| 1993 | expect(branchCalls.map(([operation]) => operation)).not.toContain("createBranch"); |
| 1994 | }), |
| 1995 | { |
| 1996 | tags: ["unit", "provider:prisma", "provider:prisma:branch", "provider:prisma:project", "local"], |
| 1997 | }, |
| 1998 | ); |