@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 6,936 lines 259 KB
Raw
1 import { gunzipSync } from "node:zlib";
2 import {
3 PrismaApiError,
4 PrismaClient,
5 type PrismaManagementClient,
6 } from "@alchemy.run/prisma/Client";
7 import {
8 Compute,
9 ComputeDevProvider,
10 ComputeProvider,
11 syncComputeEnvironment,
12 waitForDeploymentUrl,
13 type ComputeProps,
14 } from "@alchemy.run/prisma/Compute";
15 import type { Branch as ApiBranch } from "@alchemy.run/prisma/Types";
16 import { describe, expect, it } from "@alchemy.run/test";
17 import { fromApiToken } from "@distilled.cloud/prisma";
18 import { Unowned } from "alchemy/AdoptPolicy";
19 import { AlchemyContext } from "alchemy/AlchemyContext";
20 import * as Output from "alchemy/Output";
21 import * as Provider from "alchemy/Provider";
22 import type { ResourceBinding } from "alchemy/Resource";
23 import { Stack } from "alchemy/Stack";
24 import { PlatformServices } from "alchemy/Util/PlatformServices";
25 import * as Effect from "effect/Effect";
26 import * as FileSystem from "effect/FileSystem";
27 import * as FetchHttpClient from "effect/http/FetchHttpClient";
28 import * as HttpBody from "effect/http/HttpBody";
29 import * as HttpClient from "effect/http/HttpClient";
30 import * as HttpClientResponse from "effect/http/HttpClientResponse";
31 import * as Layer from "effect/Layer";
32 import * as Option from "effect/Option";
33 import * as Path from "effect/Path";
34 import * as Redacted from "effect/Redacted";
35 import * as Stream from "effect/Stream";
36 import { WebSocketServer } from "ws";
37 import { Credentials } from "../../../prisma/src/internal/Credentials.ts";
38 import {
39 type Captured,
40 data,
41 dispatchTo,
42 failure,
43 FAKE_API_BASE_URL,
44 makeFakeManagementApi,
45 unhandled,
46 } from "./fixtures/FakeManagementApi.ts";
47 import { testStackContext } from "./fixtures/StackContext.ts";
48
49 const testBranch = (id: string, role: "production" | "preview" = "production"): ApiBranch => ({
50 id,
51 type: "branch",
52 url: `https://api.prisma.test/v1/branches/${id}`,
53 gitName: id === "branch-main" ? "main" : id,
54 isDefault: role === "production" && id === "branch-main",
55 role,
56 createdAt: "2026-01-01T00:00:00Z",
57 updatedAt: "2026-01-01T00:00:00Z",
58 project: {
59 id: "project-1",
60 url: "https://api.prisma.test/v1/projects/project-1",
61 name: "project",
62 },
63 });
64
65 const withDefaultBranch = <T extends object>(
66 client: T,
67 role: "production" | "preview" = "production",
68 ): PrismaManagementClient => {
69 const mock = client as Record<string, (...args: any[]) => any>;
70 return {
71 ...client,
72 getBranch: (id: string) => mock.getBranch?.(id) ?? Effect.succeed(testBranch(id, role)),
73 listBranches: (projectId: string, query?: { gitName?: string }) =>
74 mock.listBranches?.(projectId, query) ?? Effect.succeed([testBranch("branch-main", role)]),
75 listApps: (query: { projectId?: string; limit?: number }) =>
76 mock.listApps?.length >= 2
77 ? mock.listApps(query.projectId, { limit: query.limit })
78 : mock.listApps?.(query),
79 createApp: (input: { projectId: string } & Record<string, unknown>) => {
80 if (mock.createApp?.length < 2) return mock.createApp(input);
81 const { projectId, ...body } = input;
82 return mock.createApp(projectId, body);
83 },
84 createAppDeployment: (appId: string, input: unknown) =>
85 mock.createAppDeployment?.(appId, input),
86 getDeployment: (id: string) => mock.getDeployment?.(id),
87 startDeployment: (id: string) => mock.startDeployment?.(id),
88 stopDeployment: (id: string) => mock.stopDeployment?.(id),
89 deleteDeployment: (id: string) => mock.deleteDeployment?.(id),
90 listAppDeployments: (appId: string, query: unknown) => mock.listAppDeployments?.(appId, query),
91 promoteApp: (appId: string, target: { deploymentId: string }) => mock.promoteApp(appId, target),
92 rollbackApp: (appId: string, target: { deploymentId: string }) =>
93 mock.rollbackApp?.(appId, target),
94 } as unknown as PrismaManagementClient;
95 };
96
97 const fixtureArtifactPath = `${import.meta.dirname}/fixtures/artifact-archive.bin`;
98 const fixtureArtifactV1Path = `${import.meta.dirname}/fixtures/artifact-v1.bin`;
99 const fixtureArtifactV2Path = `${import.meta.dirname}/fixtures/artifact-v2.bin`;
100
101 const readHttpBodyBytes = Effect.fn(function* (body: HttpBody.HttpBody) {
102 if (body._tag === "Uint8Array") return body.body;
103 if (body._tag !== "Stream") return new Uint8Array();
104 const chunks = yield* Stream.runCollect(body.stream).pipe(Effect.orDie);
105 const output = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.byteLength, 0));
106 let offset = 0;
107 for (const chunk of chunks) {
108 output.set(chunk, offset);
109 offset += chunk.byteLength;
110 }
111 return output;
112 });
113
114 const readTarString = (buffer: Uint8Array, start: number, length: number) => {
115 const bytes = buffer.slice(start, start + length);
116 const end = bytes.indexOf(0);
117 return new TextDecoder().decode(end >= 0 ? bytes.slice(0, end) : bytes);
118 };
119
120 const readTarFile = (buffer: Uint8Array, expectedName: string) => {
121 let offset = 0;
122 while (offset + 512 <= buffer.length) {
123 const header = buffer.slice(offset, offset + 512);
124 if (header.every((byte) => byte === 0)) break;
125 const name = readTarString(header, 0, 100);
126 const prefix = readTarString(header, 345, 155);
127 const fullName = prefix ? `${prefix}/${name}` : name;
128 const size = Number.parseInt(readTarString(header, 124, 12).trim() || "0", 8);
129 const bodyStart = offset + 512;
130 if (fullName === expectedName) {
131 return new TextDecoder().decode(buffer.slice(bodyStart, bodyStart + size));
132 }
133 offset = bodyStart + size + ((512 - (size % 512)) % 512);
134 }
135 throw new Error(`Missing tar entry '${expectedName}'.`);
136 };
137
138 const httpBodyContentType = (body: HttpBody.HttpBody) =>
139 body._tag === "Uint8Array" || body._tag === "Stream" ? body.contentType : undefined;
140
141 const makeHealthLifecycleFixture = (options?: {
142 latestDeploymentId?: string | null;
143 previewStatus?: number;
144 stableStatus?: number;
145 rollbackFailures?: number;
146 getAppFailureCalls?: readonly number[];
147 promoteUpdatesLatest?: boolean;
148 rollbackUpdatesLatest?: boolean;
149 }) => {
150 const calls: Array<[string, unknown?]> = [];
151 const deployments = new Map<string, "new" | "running" | "provisioning" | "stopped" | "failed">([
152 ["version-old", "running"],
153 ]);
154 let deploymentCounter = 0;
155 let previewStatus = options?.previewStatus ?? 204;
156 let stableStatus = options?.stableStatus ?? 204;
157 let rollbackFailuresRemaining = options?.rollbackFailures ?? 0;
158 let getAppCalls = 0;
159 let latestDeploymentId =
160 options?.latestDeploymentId === undefined ? "version-old" : options.latestDeploymentId;
161
162 const app = () => ({
163 id: "service-1",
164 type: "app" as const,
165 url: "https://api.prisma.test/v1/services/service-1",
166 name: "api",
167 region: { id: "us-east-1", name: "US East" },
168 projectId: "project-1",
169 branchId: "branch-main",
170 latestDeploymentId,
171 appEndpointDomain: "api.prisma.build",
172 createdAt: "2026-01-01T00:00:00Z",
173 });
174 const client = {
175 getApp: (id: string) => {
176 getAppCalls += 1;
177 calls.push(["getApp", id]);
178 if (options?.getAppFailureCalls?.includes(getAppCalls)) {
179 return Effect.fail(
180 new PrismaApiError({
181 method: "GET",
182 path: `/v1/services/${id}`,
183 // Non-transient on purpose: a 5xx would be replayed by the
184 // retry policy.
185 status: 400,
186 message: "app observation unavailable",
187 }),
188 );
189 }
190 return Effect.succeed(app());
191 },
192 createAppDeployment: (appId: string, input: unknown) => {
193 calls.push(["createAppDeployment", { appId, input }]);
194 deploymentCounter += 1;
195 const deploymentId =
196 deploymentCounter === 1 ? "version-new" : `version-new-${deploymentCounter}`;
197 deployments.set(deploymentId, "new");
198 return Effect.succeed({
199 id: deploymentId,
200 type: "deployment" as const,
201 url: `https://api.prisma.test/v1/deployments/${deploymentId}`,
202 foundryVersionId: `foundry-${deploymentId}`,
203 uploadUrl: `https://upload.prisma.test/${deploymentId}.tar.gz`,
204 });
205 },
206 getDeployment: (id: string) => {
207 calls.push(["getDeployment", id]);
208 const status = deployments.get(id);
209 return status
210 ? Effect.succeed({
211 id,
212 type: "deployment" as const,
213 serviceId: "service-1",
214 url: `https://api.prisma.test/v1/deployments/${id}`,
215 foundryVersionId: `foundry-${id}`,
216 status,
217 previewDomain: `${id}.preview.prisma.build`,
218 createdAt: "2026-01-01T00:00:00Z",
219 })
220 : Effect.fail(
221 new PrismaApiError({
222 method: "GET",
223 path: `/v1/deployments/${id}`,
224 status: 404,
225 message: "not found",
226 }),
227 );
228 },
229 startDeployment: (id: string) =>
230 Effect.sync(() => {
231 calls.push(["startDeployment", id]);
232 deployments.set(id, "running");
233 return { previewDomain: `${id}.preview.prisma.build` };
234 }),
235 promoteApp: (appId: string, target: { deploymentId: string }) =>
236 Effect.sync(() => {
237 calls.push(["promoteApp", { appId, ...target }]);
238 if (options?.promoteUpdatesLatest !== false) {
239 latestDeploymentId = target.deploymentId;
240 }
241 return { appEndpointDomain: "api.prisma.build", reassignedDomains: 0 };
242 }),
243 rollbackApp: (appId: string, target: { deploymentId: string }) =>
244 Effect.gen(function* () {
245 calls.push(["rollbackApp", { appId, ...target }]);
246 if (rollbackFailuresRemaining > 0) {
247 rollbackFailuresRemaining -= 1;
248 return yield* Effect.fail(
249 new PrismaApiError({
250 method: "POST",
251 path: `/v1/services/${appId}/rollback`,
252 status: 400,
253 message: "rollback unavailable",
254 }),
255 );
256 }
257 if (options?.rollbackUpdatesLatest !== false) {
258 latestDeploymentId = target.deploymentId;
259 }
260 return { appEndpointDomain: "api.prisma.build", reassignedDomains: 0 };
261 }),
262 stopDeployment: (id: string) =>
263 Effect.sync(() => {
264 calls.push(["stopDeployment", id]);
265 deployments.set(id, "stopped");
266 }),
267 deleteDeployment: (id: string) =>
268 Effect.sync(() => {
269 calls.push(["deleteDeployment", id]);
270 deployments.delete(id);
271 }),
272 } as unknown as PrismaManagementClient;
273 const http = HttpClient.make((request) => {
274 if (request.url.startsWith("https://upload.prisma.test/")) {
275 calls.push(["upload", request.url]);
276 return readHttpBodyBytes(request.body as HttpBody.HttpBody).pipe(
277 Effect.as(HttpClientResponse.fromWeb(request, new Response(null))),
278 );
279 }
280 calls.push(["healthRequest", request.url]);
281 return Effect.succeed(
282 HttpClientResponse.fromWeb(
283 request,
284 new Response(null, {
285 status: new URL(request.url).hostname.endsWith(".preview.prisma.build")
286 ? previewStatus
287 : stableStatus,
288 }),
289 ),
290 );
291 });
292
293 return {
294 calls,
295 client,
296 http,
297 hasDeployment: (id: string) => deployments.has(id),
298 latestDeploymentId: () => latestDeploymentId,
299 setPreviewStatus: (status: number) => {
300 previewStatus = status;
301 },
302 setStableStatus: (status: number) => {
303 stableStatus = status;
304 },
305 setDeploymentStatus: (
306 id: string,
307 status: "new" | "running" | "provisioning" | "stopped" | "failed",
308 ) => {
309 deployments.set(id, status);
310 },
311 };
312 };
313
314 const liveProviderContext = Layer.succeed(AlchemyContext, {
315 dotAlchemy: ".alchemy-test",
316 dev: false,
317 adopt: false,
318 });
319
320 const computeProviderLive = () =>
321 ComputeProvider().pipe(
322 Layer.provide(Layer.mergeAll(liveProviderContext, testStackContext, PlatformServices)),
323 );
324
325 /**
326 * Serve the Management API from the same hermetic client-shaped handlers this
327 * suite declares, for the routes Compute now reaches through distilled
328 * operations. `dispatchTo` maps each handler's result onto the wire (see the
329 * fixture). The log tail still resolves the hand-rolled client, so the
330 * `PrismaClient` layer stays provided alongside.
331 */
332 const dispatchManagement = (client: any, request: Captured): Response => {
333 const [head, id, tail] = request.pathname
334 .split("/")
335 .filter((segment) => segment.length > 0)
336 .slice(1);
337 const body = request.bodyJson as any;
338 const query = Object.fromEntries(new URLSearchParams(request.search));
339 const { call, callVoid, list } = dispatchTo(request);
340
341 if (head === "services") {
342 if (id === undefined) {
343 return request.method === "GET"
344 ? call(client.listApps, [query], list)
345 : call(client.createApp, [body]);
346 }
347 if (tail === "deployments") {
348 return request.method === "GET"
349 ? call(client.listAppDeployments, [id, query], list)
350 : call(client.createAppDeployment, [id, body]);
351 }
352 if (tail === "promote") return call(client.promoteApp, [id, body]);
353 if (tail === "rollback") return call(client.rollbackApp, [id, body]);
354 if (tail === undefined) {
355 if (request.method === "GET") return call(client.getApp, [id]);
356 if (request.method === "PATCH") return call(client.updateApp, [id, body]);
357 if (request.method === "DELETE") {
358 return callVoid(client.deleteApp, [id]);
359 }
360 }
361 }
362 if (head === "branches" && id !== undefined && request.method === "GET") {
363 return call(client.getBranch, [id]);
364 }
365 if (head === "projects" && id !== undefined) {
366 if (tail === "branches" && request.method === "GET") {
367 return call(client.listBranches, [id, query], list);
368 }
369 if (tail === undefined && request.method === "DELETE") {
370 return callVoid(client.deleteProject, [id]);
371 }
372 }
373 if (head === "deployments" && id !== undefined) {
374 if (tail === "start") return call(client.startDeployment, [id]);
375 if (tail === "stop") {
376 return callVoid(client.stopDeployment, [id]);
377 }
378 if (request.method === "GET") return call(client.getDeployment, [id]);
379 if (request.method === "DELETE") {
380 return callVoid(client.deleteDeployment, [id]);
381 }
382 }
383 if (head === "environment-variables") {
384 if (id === undefined) {
385 return request.method === "GET"
386 ? call(client.listEnvironmentVariables, [query], list)
387 : call(client.createEnvironmentVariable, [body]);
388 }
389 if (request.method === "GET") {
390 return call(client.getEnvironmentVariable, [id]);
391 }
392 if (request.method === "PATCH") {
393 return call(client.updateEnvironmentVariable, [id, body]);
394 }
395 if (request.method === "DELETE") {
396 return callVoid(client.deleteEnvironmentVariable, [id]);
397 }
398 }
399 return unhandled(request);
400 };
401
402 /**
403 * Ambient HTTP for a Compute test: Management API requests dispatch to the
404 * client-shaped handlers; anything else (uploads, health probes) falls back
405 * to the HttpClient provided beneath this layer, when there is one.
406 */
407 const apiRoutedHttp = (client: any) =>
408 Layer.mergeAll(
409 Layer.effect(
410 HttpClient.HttpClient,
411 Effect.gen(function* () {
412 const fallback = yield* Effect.serviceOption(HttpClient.HttpClient);
413 return HttpClient.make((request) => {
414 if (!request.url.startsWith(FAKE_API_BASE_URL)) {
415 return Option.isSome(fallback)
416 ? fallback.value.execute(request)
417 : Effect.sync(() =>
418 HttpClientResponse.fromWeb(
419 request,
420 unhandled({
421 url: request.url,
422 method: request.method,
423 pathname: new URL(request.url).pathname,
424 search: "",
425 authorization: undefined,
426 bodyJson: undefined,
427 }),
428 ),
429 );
430 }
431 return Effect.sync(() => {
432 const url = new URL(request.url);
433 const body = request.body as HttpBody.HttpBody;
434 const bodyText = body._tag === "Uint8Array" ? new TextDecoder().decode(body.body) : "";
435 return HttpClientResponse.fromWeb(
436 request,
437 dispatchManagement(client, {
438 url: request.url,
439 method: request.method,
440 pathname: url.pathname,
441 search: url.search,
442 authorization: request.headers.authorization,
443 bodyJson: bodyText ? JSON.parse(bodyText) : undefined,
444 }),
445 );
446 });
447 });
448 }),
449 ),
450 fromApiToken({ apiToken: Redacted.make("fake-service-token"), apiBaseUrl: FAKE_API_BASE_URL }),
451 );
452
453 describe(
454 "Prisma Compute",
455 { tags: ["unit", "provider:prisma", "provider:prisma:compute", "local"] },
456 () => {
457 it.live("accepts a streaming 200 response without consuming its body", () => {
458 const body = new ReadableStream<Uint8Array>({
459 pull() {
460 // Deliberately never enqueue or close. Reading this body would hang.
461 },
462 });
463 const http = HttpClient.make((request) =>
464 Effect.succeed(HttpClientResponse.fromWeb(request, new Response(body, { status: 200 }))),
465 );
466
467 return waitForDeploymentUrl("https://app.prisma.build", {
468 project: "project-1",
469 appName: "api",
470 urlReadinessTimeoutSeconds: 0.05,
471 }).pipe(Effect.provide(Layer.succeed(HttpClient.HttpClient, http)));
472 });
473
474 it.live("waits for the configured application health contract", () => {
475 const requests: string[] = [];
476 const http = HttpClient.make((request) => {
477 requests.push(request.url);
478 return Effect.succeed(
479 HttpClientResponse.fromWeb(
480 request,
481 new Response(null, { status: requests.length === 1 ? 503 : 204 }),
482 ),
483 );
484 });
485
486 return Effect.gen(function* () {
487 yield* waitForDeploymentUrl("https://app.prisma.build", {
488 project: "project-1",
489 appName: "api",
490 healthCheck: { path: "/api/health" },
491 pollIntervalMs: 1,
492 // Wall-clock deadline (live clock). The mock succeeds on the second
493 // poll, so the pass path never waits this long — it only needs to
494 // not fire spuriously when a saturated event loop (full-suite run)
495 // delays the second poll beyond a tight budget.
496 urlReadinessTimeoutSeconds: 30,
497 });
498
499 expect(requests).toEqual([
500 "https://app.prisma.build/api/health",
501 "https://app.prisma.build/api/health",
502 ]);
503 }).pipe(Effect.provide(Layer.succeed(HttpClient.HttpClient, http)));
504 });
505
506 it.effect("rejects unsafe application health contracts", () =>
507 Effect.gen(function* () {
508 const pathError = yield* waitForDeploymentUrl("https://app.prisma.build", {
509 project: "project-1",
510 appName: "api",
511 healthCheck: { path: "//attacker.example/health" },
512 }).pipe(Effect.flip);
513 const statusError = yield* waitForDeploymentUrl("https://app.prisma.build", {
514 project: "project-1",
515 appName: "api",
516 healthCheck: { path: "/health", statusCodes: [] },
517 }).pipe(Effect.flip);
518
519 expect(pathError.message).toContain("healthCheck.path");
520 expect(statusError.message).toContain("healthCheck.statusCodes");
521 }),
522 );
523
524 it.effect("fails closed when an application health probe cannot run", () =>
525 Effect.gen(function* () {
526 const props = {
527 project: "project-1",
528 appName: "api",
529 healthCheck: { path: "/health" },
530 } as const;
531 const missingUrl = yield* waitForDeploymentUrl(undefined, props).pipe(Effect.flip);
532 const missingRoutingUrl = yield* waitForDeploymentUrl(undefined, {
533 project: "project-1",
534 appName: "api",
535 }).pipe(Effect.flip);
536 const disabled = yield* waitForDeploymentUrl("https://app.prisma.build", {
537 ...props,
538 verifyUrl: false,
539 }).pipe(Effect.flip);
540 const missingClient = yield* waitForDeploymentUrl("https://app.prisma.build", props).pipe(
541 Effect.flip,
542 );
543
544 expect(missingUrl.message).toContain("did not return");
545 expect(missingRoutingUrl.message).toContain("readiness verification");
546 expect(disabled.message).toContain("verifyUrl: false");
547 expect(missingClient.message).toContain("HTTP client");
548 }),
549 );
550
551 it.live("observes health redirects without following them", () => {
552 const redirects: RequestRedirect[] = [];
553 const fetch = (async (
554 _input: Parameters<typeof globalThis.fetch>[0],
555 init?: Parameters<typeof globalThis.fetch>[1],
556 ) => {
557 redirects.push(init?.redirect ?? "follow");
558 return init?.redirect === "manual"
559 ? new Response(null, { status: 302, headers: { location: "https://attacker.example/" } })
560 : new Response(null, { status: 200 });
561 }) as typeof globalThis.fetch;
562
563 return Effect.gen(function* () {
564 yield* waitForDeploymentUrl("https://app.prisma.build", {
565 project: "project-1",
566 appName: "api",
567 healthCheck: { path: "/health", statusCodes: [302] },
568 pollIntervalMs: 1,
569 urlReadinessTimeoutSeconds: 0.05,
570 });
571 const defaultStatusError = yield* waitForDeploymentUrl("https://app.prisma.build", {
572 project: "project-1",
573 appName: "api",
574 healthCheck: { path: "/health" },
575 pollIntervalMs: 1,
576 urlReadinessTimeoutSeconds: 0.01,
577 }).pipe(Effect.flip);
578
579 expect(redirects.length).toBeGreaterThanOrEqual(2);
580 expect(redirects.every((redirect) => redirect === "manual")).toBe(true);
581 expect(defaultStatusError.message).toContain("HTTP 302");
582 }).pipe(
583 Effect.provide(FetchHttpClient.layer),
584 Effect.provideService(FetchHttpClient.Fetch, fetch),
585 );
586 });
587
588 it.live("enforces one deadline for stalled requests and 404 bodies", () => {
589 const stalledRequest = HttpClient.make(() => Effect.never);
590 const stalledBody = HttpClient.make((request) =>
591 Effect.succeed(
592 HttpClientResponse.fromWeb(
593 request,
594 new Response(
595 new ReadableStream<Uint8Array>({
596 pull() {
597 // Deliberately never enqueue or close.
598 },
599 }),
600 { status: 404 },
601 ),
602 ),
603 ),
604 );
605 const props = {
606 project: "project-1",
607 appName: "api",
608 pollIntervalMs: 1,
609 urlReadinessTimeoutSeconds: 0.03,
610 } as const;
611
612 return Effect.gen(function* () {
613 const requestError = yield* waitForDeploymentUrl(
614 "https://request.prisma.build",
615 props,
616 ).pipe(Effect.provide(Layer.succeed(HttpClient.HttpClient, stalledRequest)), Effect.flip);
617 const bodyError = yield* waitForDeploymentUrl("https://body.prisma.build", props).pipe(
618 Effect.provide(Layer.succeed(HttpClient.HttpClient, stalledBody)),
619 Effect.flip,
620 );
621
622 expect(requestError.message).toContain("Timed out");
623 expect(bodyError.message).toContain("Timed out");
624 });
625 });
626
627 it.live("bounds the inspected prefix of a large Prisma edge 404", () => {
628 let requests = 0;
629 const hugeBody = `${"There is no service on this URL"}${"x".repeat(256 * 1024)}`;
630 const http = HttpClient.make((request) => {
631 requests += 1;
632 return requests === 1
633 ? Effect.succeed(
634 HttpClientResponse.fromWeb(request, new Response(hugeBody, { status: 404 })),
635 )
636 : Effect.never;
637 });
638
639 return Effect.gen(function* () {
640 const error = yield* waitForDeploymentUrl("https://missing.prisma.build", {
641 project: "project-1",
642 appName: "api",
643 pollIntervalMs: 1,
644 urlReadinessTimeoutSeconds: 0.05,
645 }).pipe(Effect.provide(Layer.succeed(HttpClient.HttpClient, http)), Effect.flip);
646
647 expect(error.message).toContain("There is no service on this URL");
648 expect(requests).toBeGreaterThanOrEqual(1);
649 });
650 });
651
652 it.effect("rejects invalid URL readiness timings before making a request", () => {
653 const http = HttpClient.make(() => Effect.die("invalid readiness options must fail first"));
654
655 return Effect.gen(function* () {
656 const error = yield* waitForDeploymentUrl("https://app.prisma.build", {
657 project: "project-1",
658 appName: "api",
659 pollIntervalMs: 0,
660 }).pipe(Effect.provide(Layer.succeed(HttpClient.HttpClient, http)), Effect.flip);
661
662 expect(error.message).toContain("pollIntervalMs");
663 });
664 });
665 it.effect(
666 "rejects destroyOldDeployment when promotion is skipped",
667 () => {
668 const client = {} as PrismaManagementClient;
669
670 return Effect.gen(function* () {
671 const provider = yield* Compute.Provider;
672 const error = yield* provider
673 .reconcile({
674 id: "App",
675 fqn: "App",
676 instanceId: "00000000000000000000000000000000",
677 news: {
678 project: "project-1",
679 appName: "api",
680 skipPromote: true,
681 destroyOldDeployment: true,
682 },
683 olds: undefined,
684 output: undefined,
685 session: undefined as never,
686 bindings: [],
687 })
688 .pipe(Effect.flip);
689
690 expect(error).toBeInstanceOf(Error);
691 expect(error.message).toContain(
692 "destroyOldDeployment cannot be combined with skipPromote",
693 );
694 }).pipe(
695 Effect.provide(computeProviderLive()),
696 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
697 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
698 );
699 },
700 { tags: ["provider:prisma:branch"] },
701 );
702
703 it.effect("rejects a health check when deployment start is disabled", () => {
704 const client = {} as PrismaManagementClient;
705
706 return Effect.gen(function* () {
707 const provider = yield* Compute.Provider;
708 const error = yield* provider
709 .reconcile({
710 id: "App",
711 fqn: "App",
712 instanceId: "00000000000000000000000000000000",
713 news: {
714 project: "project-1",
715 appName: "api",
716 start: false,
717 skipPromote: true,
718 healthCheck: { path: "/health" },
719 },
720 olds: undefined,
721 output: undefined,
722 session: undefined as never,
723 bindings: [],
724 })
725 .pipe(Effect.flip);
726
727 expect(error.message).toContain("healthCheck requires start");
728 }).pipe(
729 Effect.provide(computeProviderLive()),
730 Effect.provide(Layer.succeed(PrismaClient, client)),
731 Effect.provide(apiRoutedHttp(client)),
732 Effect.provide(PlatformServices),
733 );
734 });
735
736 it.effect(
737 "rejects disabled start when promotion is enabled",
738 () => {
739 const client = {} as PrismaManagementClient;
740
741 return Effect.gen(function* () {
742 const provider = yield* Compute.Provider;
743 const error = yield* provider
744 .reconcile({
745 id: "App",
746 fqn: "App",
747 instanceId: "00000000000000000000000000000000",
748 news: { project: "project-1", appName: "api", start: false },
749 olds: undefined,
750 output: undefined,
751 session: undefined as never,
752 bindings: [],
753 })
754 .pipe(Effect.flip);
755
756 expect(error).toBeInstanceOf(Error);
757 expect(error.message).toContain("start: false requires skipPromote: true");
758 }).pipe(
759 Effect.provide(computeProviderLive()),
760 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
761 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
762 );
763 },
764 { tags: ["provider:prisma:branch"] },
765 );
766
767 it.effect(
768 "rejects conflicting branch attachment inputs",
769 () => {
770 const client = {} as PrismaManagementClient;
771
772 return Effect.gen(function* () {
773 const provider = yield* Compute.Provider;
774 const error = yield* provider
775 .reconcile({
776 id: "App",
777 fqn: "App",
778 instanceId: "00000000000000000000000000000000",
779 news: {
780 project: "project-1",
781 appName: "api",
782 branchId: "branch-1",
783 branchGitName: "main",
784 },
785 olds: undefined,
786 output: undefined,
787 session: undefined as never,
788 bindings: [],
789 })
790 .pipe(Effect.flip);
791
792 expect(error).toBeInstanceOf(Error);
793 expect(error.message).toContain("branchId and branchGitName are mutually exclusive");
794 }).pipe(
795 Effect.provide(computeProviderLive()),
796 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
797 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
798 );
799 },
800 { tags: ["provider:prisma:branch"] },
801 );
802
803 it.effect(
804 "rejects invalid production and dev ports",
805 () => {
806 const client = {} as PrismaManagementClient;
807
808 return Effect.gen(function* () {
809 const provider = yield* Compute.Provider;
810 for (const props of [
811 { port: 0 },
812 { port: 65_536 },
813 { port: 1.5 },
814 { dev: { port: Number.NaN } },
815 ]) {
816 const error = yield* provider
817 .reconcile({
818 id: "App",
819 fqn: "App",
820 instanceId: "00000000000000000000000000000000",
821 news: { project: "project-1", appName: "api", ...props },
822 olds: undefined,
823 output: undefined,
824 session: undefined as never,
825 bindings: [],
826 })
827 .pipe(Effect.flip);
828 expect(error.message).toContain("must be an integer between 1 and 65535");
829 }
830 }).pipe(
831 Effect.provide(computeProviderLive()),
832 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
833 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
834 );
835 },
836 { tags: ["provider:prisma:branch"] },
837 );
838
839 it.effect(
840 "rejects unassigned branch attachment for Compute deploys",
841 () => {
842 const client = {} as PrismaManagementClient;
843
844 return Effect.gen(function* () {
845 const provider = yield* Compute.Provider;
846 for (const branchProps of [{ branchId: null }, { branchGitName: null }]) {
847 const error = yield* provider
848 .reconcile({
849 id: "App",
850 fqn: "App",
851 instanceId: "00000000000000000000000000000000",
852 news: {
853 project: "project-1",
854 appName: "api",
855 ...branchProps,
856 } as unknown as ComputeProps,
857 olds: undefined,
858 output: undefined,
859 session: undefined as never,
860 bindings: [],
861 })
862 .pipe(Effect.flip);
863
864 expect(error).toBeInstanceOf(Error);
865 expect(error.message).toContain("requires an attached branch");
866 }
867 }).pipe(
868 Effect.provide(computeProviderLive()),
869 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
870 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
871 );
872 },
873 { tags: ["provider:prisma:branch"] },
874 );
875
876 it.effect(
877 "rejects skipCodeUpload without a version to fork",
878 () => {
879 const calls: Array<[string, unknown]> = [];
880 const client = {
881 getApp: (id: string) => {
882 calls.push(["getApp", id]);
883 return Effect.succeed({
884 id,
885 type: "app" as const,
886 url: `https://api.prisma.test/v1/services/${id}`,
887 name: "api",
888 region: { id: "us-east-1", name: "US East" },
889 projectId: "project-1",
890 branchId: "branch-main",
891 latestDeploymentId: null,
892 appEndpointDomain: "api.prisma.build",
893 createdAt: "2026-01-01T00:00:00Z",
894 });
895 },
896 } as unknown as PrismaManagementClient;
897
898 return Effect.gen(function* () {
899 const provider = yield* Compute.Provider;
900 const error = yield* provider
901 .reconcile({
902 id: "App",
903 fqn: "App",
904 instanceId: "00000000000000000000000000000000",
905 news: {
906 project: "project-1",
907 appName: "api",
908 branchId: "branch-main",
909 skipCodeUpload: true,
910 start: false,
911 skipPromote: true,
912 },
913 olds: undefined,
914 output: {
915 appId: "service-1",
916 deploymentId: undefined,
917 projectId: "project-1",
918 appName: "api",
919 regionId: "us-east-1",
920 deploymentEndpointDomain: undefined,
921 deploymentUrl: undefined,
922 appEndpointDomain: "api.prisma.build",
923 url: "https://api.prisma.build",
924 promoted: false,
925 previousDeploymentId: undefined,
926 previousDeploymentAction: undefined,
927 artifactHash: undefined,
928 local: false,
929 },
930 session: undefined as never,
931 bindings: [],
932 })
933 .pipe(Effect.flip);
934
935 expect(error).toBeInstanceOf(Error);
936 expect(error.message).toContain("skipCodeUpload requires an existing Prisma deployment");
937 expect(calls).toEqual([["getApp", "service-1"]]);
938 }).pipe(
939 Effect.provide(computeProviderLive()),
940 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
941 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
942 );
943 },
944 { tags: ["provider:prisma:branch"] },
945 );
946
947 it.effect(
948 "rejects effect-native Compute without a main module",
949 () => {
950 const client = {} as PrismaManagementClient;
951
952 return Effect.gen(function* () {
953 const provider = yield* Compute.Provider;
954 const error = yield* provider
955 .reconcile({
956 id: "App",
957 fqn: "App",
958 instanceId: "00000000000000000000000000000000",
959 news: { project: "project-1", appName: "api", exports: { default: "runtime" } },
960 olds: undefined,
961 output: undefined,
962 session: undefined as never,
963 bindings: [],
964 })
965 .pipe(Effect.flip);
966
967 expect(error).toBeInstanceOf(Error);
968 expect(error.message).toContain("Effect-native Prisma Compute apps require `main`");
969 }).pipe(
970 Effect.provide(computeProviderLive()),
971 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
972 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
973 );
974 },
975 { tags: ["provider:prisma:branch"] },
976 );
977
978 it.effect(
979 "rejects effect-native Compute with an external build",
980 () => {
981 const client = {} as PrismaManagementClient;
982
983 return Effect.gen(function* () {
984 const provider = yield* Compute.Provider;
985 const error = yield* provider
986 .reconcile({
987 id: "App",
988 fqn: "App",
989 instanceId: "00000000000000000000000000000000",
990 news: {
991 project: "project-1",
992 appName: "api",
993 main: "app.ts",
994 build: { command: "bun run build", outdir: "dist" },
995 },
996 olds: undefined,
997 output: undefined,
998 session: undefined as never,
999 bindings: [],
1000 })
1001 .pipe(Effect.flip);
1002
1003 expect(error).toBeInstanceOf(Error);
1004 expect(error.message).toContain("Effect-native Prisma Compute apps cannot use build");
1005 }).pipe(
1006 Effect.provide(computeProviderLive()),
1007 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
1008 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
1009 );
1010 },
1011 { tags: ["provider:prisma:branch"] },
1012 );
1013
1014 it.effect(
1015 "rejects effect-native Compute with an invalid handler name",
1016 () => {
1017 const client = {} as PrismaManagementClient;
1018
1019 return Effect.gen(function* () {
1020 const provider = yield* Compute.Provider;
1021 const error = yield* provider
1022 .reconcile({
1023 id: "App",
1024 fqn: "App",
1025 instanceId: "00000000000000000000000000000000",
1026 news: {
1027 project: "project-1",
1028 appName: "api",
1029 main: "app.ts",
1030 handler: "Api;console.log('nope')",
1031 },
1032 olds: undefined,
1033 output: undefined,
1034 session: undefined as never,
1035 bindings: [],
1036 })
1037 .pipe(Effect.flip);
1038
1039 expect(error).toBeInstanceOf(Error);
1040 expect(error.message).toContain(
1041 "handler must be `default` or a valid JavaScript export identifier",
1042 );
1043 }).pipe(
1044 Effect.provide(computeProviderLive()),
1045 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
1046 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
1047 );
1048 },
1049 { tags: ["provider:prisma:branch"] },
1050 );
1051
1052 it.effect(
1053 "replaces Compute when region changes even if project is unresolved",
1054 () => {
1055 const client = {} as PrismaManagementClient;
1056
1057 return Effect.gen(function* () {
1058 const provider = yield* Compute.Provider;
1059 const error = yield* provider.diff!({
1060 id: "App",
1061 fqn: "App",
1062 instanceId: "00000000000000000000000000000000",
1063 olds: { project: "project-1", appName: "api", regionId: "us-east-1" },
1064 news: { project: Output.asOutput("project-1"), appName: "api", regionId: "us-west-2" },
1065 oldBindings: [],
1066 newBindings: [],
1067 output: {
1068 appId: "service-1",
1069 deploymentId: "version-1",
1070 projectId: "project-1",
1071 appName: "api",
1072 regionId: "us-east-1",
1073 deploymentEndpointDomain: "version-1.preview.prisma.build",
1074 deploymentUrl: "https://version-1.preview.prisma.build",
1075 appEndpointDomain: "api.prisma.build",
1076 url: "https://api.prisma.build",
1077 promoted: true,
1078 previousDeploymentId: undefined,
1079 previousDeploymentAction: undefined,
1080 artifactHash: Redacted.make("hash-1"),
1081 local: false,
1082 },
1083 } as never).pipe(Effect.flip);
1084
1085 expect(String(error)).toContain("cannot be changed atomically");
1086 }).pipe(
1087 Effect.provide(computeProviderLive()),
1088 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
1089 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
1090 );
1091 },
1092 { tags: ["provider:prisma:branch"] },
1093 );
1094
1095 it.effect(
1096 "replaces Compute when project changes even if region is unresolved",
1097 () => {
1098 const client = {} as PrismaManagementClient;
1099
1100 return Effect.gen(function* () {
1101 const provider = yield* Compute.Provider;
1102 const diff = yield* provider.diff!({
1103 id: "App",
1104 fqn: "App",
1105 instanceId: "00000000000000000000000000000000",
1106 olds: { project: "project-1", appName: "api", regionId: "us-east-1" },
1107 news: { project: "project-2", appName: "api", regionId: Output.asOutput("us-east-1") },
1108 oldBindings: [],
1109 newBindings: [],
1110 output: {
1111 appId: "service-1",
1112 deploymentId: "version-1",
1113 projectId: "project-1",
1114 appName: "api",
1115 regionId: "us-east-1",
1116 deploymentEndpointDomain: "version-1.preview.prisma.build",
1117 deploymentUrl: "https://version-1.preview.prisma.build",
1118 appEndpointDomain: "api.prisma.build",
1119 url: "https://api.prisma.build",
1120 promoted: true,
1121 previousDeploymentId: undefined,
1122 previousDeploymentAction: undefined,
1123 artifactHash: Redacted.make("hash-1"),
1124 local: false,
1125 },
1126 } as never);
1127
1128 expect(diff).toEqual({ action: "replace" });
1129 }).pipe(
1130 Effect.provide(computeProviderLive()),
1131 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
1132 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
1133 );
1134 },
1135 { tags: ["provider:prisma:branch"] },
1136 );
1137
1138 it.effect(
1139 "updates Compute when props are unchanged so artifacts can rehash",
1140 () => {
1141 const client = {} as PrismaManagementClient;
1142
1143 return Effect.gen(function* () {
1144 const provider = yield* Compute.Provider;
1145 const diff = yield* provider.diff!({
1146 id: "App",
1147 fqn: "App",
1148 instanceId: "00000000000000000000000000000000",
1149 olds: {
1150 project: "project-1",
1151 appName: "api",
1152 regionId: "us-east-1",
1153 path: ".",
1154 entrypoint: "server.ts",
1155 },
1156 news: {
1157 project: "project-1",
1158 appName: "api",
1159 regionId: "us-east-1",
1160 path: ".",
1161 entrypoint: "server.ts",
1162 },
1163 oldBindings: [],
1164 newBindings: [],
1165 output: {
1166 appId: "service-1",
1167 deploymentId: "version-1",
1168 projectId: "project-1",
1169 appName: "api",
1170 regionId: "us-east-1",
1171 deploymentEndpointDomain: "version-1.preview.prisma.build",
1172 deploymentUrl: "https://version-1.preview.prisma.build",
1173 appEndpointDomain: "api.prisma.build",
1174 url: "https://api.prisma.build",
1175 promoted: true,
1176 previousDeploymentId: undefined,
1177 previousDeploymentAction: undefined,
1178 artifactHash: Redacted.make("hash-1"),
1179 local: false,
1180 },
1181 } as never);
1182
1183 expect(diff).toEqual({ action: "update" });
1184 }).pipe(
1185 Effect.provide(computeProviderLive()),
1186 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
1187 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
1188 );
1189 },
1190 { tags: ["provider:prisma:branch"] },
1191 );
1192
1193 it.effect("dev provider applies the same Compute prop validation", () =>
1194 Effect.gen(function* () {
1195 const provider = yield* Compute.Provider;
1196 const error = yield* provider
1197 .reconcile({
1198 id: "App",
1199 fqn: "App",
1200 instanceId: "00000000000000000000000000000000",
1201 news: {
1202 project: "project-1",
1203 appName: "api",
1204 skipPromote: true,
1205 destroyOldDeployment: true,
1206 dev: { url: "http://localhost:3000" },
1207 },
1208 olds: undefined,
1209 output: undefined,
1210 session: undefined as never,
1211 bindings: [],
1212 })
1213 .pipe(Effect.flip);
1214
1215 expect(error).toBeInstanceOf(Error);
1216 expect(error.message).toContain("destroyOldDeployment cannot be combined with skipPromote");
1217 }).pipe(
1218 Effect.provide(ComputeDevProvider()),
1219 Effect.provide(
1220 Layer.succeed(AlchemyContext, { dotAlchemy: ".alchemy", dev: true, adopt: false }),
1221 ),
1222 Effect.provide(PlatformServices),
1223 ),
1224 );
1225
1226 it.effect(
1227 "adopts only the matching branch's latest deployment as Unowned",
1228 () => {
1229 const calls: Array<[string, unknown]> = [];
1230 const client = {
1231 listApps: (projectId: string, query: unknown) => {
1232 calls.push(["listApps", { projectId, query }]);
1233 return Effect.succeed([
1234 {
1235 id: "service-1",
1236 type: "app" as const,
1237 url: "https://api.prisma.test/v1/services/service-1",
1238 name: "api",
1239 region: { id: "us-east-1", name: "US East" },
1240 projectId,
1241 branchId: "branch-main",
1242 latestDeploymentId: "version-live",
1243 appEndpointDomain: "api.prisma.build",
1244 createdAt: "2026-01-01T00:00:00Z",
1245 },
1246 {
1247 id: "service-feature",
1248 type: "app" as const,
1249 url: "https://api.prisma.test/v1/services/service-feature",
1250 name: "api",
1251 region: { id: "us-east-1", name: "US East" },
1252 projectId,
1253 branchId: "branch-feature",
1254 latestDeploymentId: "version-feature",
1255 appEndpointDomain: "feature.prisma.build",
1256 createdAt: "2026-01-01T00:00:00Z",
1257 },
1258 ]);
1259 },
1260 getDeployment: (id: string) => {
1261 calls.push(["getDeployment", id]);
1262 return Effect.succeed({
1263 id,
1264 type: "deployment" as const,
1265 serviceId: "service-1",
1266 url: `https://api.prisma.test/v1/deployments/${id}`,
1267 foundryVersionId: "foundry-live",
1268 status: "running",
1269 previewDomain: "version-live.preview.prisma.build",
1270 createdAt: "2026-01-01T00:00:00Z",
1271 });
1272 },
1273 listAppDeployments: () =>
1274 Effect.succeed([
1275 {
1276 id: "version-old",
1277 type: "deployment" as const,
1278 serviceId: "service-1",
1279 url: "https://api.prisma.test/v1/deployments/version-old",
1280 foundryVersionId: "foundry-version-old",
1281 createdAt: "2026-01-01T00:00:00Z",
1282 },
1283 ]),
1284 } as unknown as PrismaManagementClient;
1285
1286 return Effect.gen(function* () {
1287 const provider = yield* Provider.findProvider(Compute);
1288 const output = yield* provider.read!({
1289 id: "App",
1290 fqn: "App",
1291 instanceId: "00000000000000000000000000000000",
1292 olds: { project: "project-1", appName: "api" },
1293 output: undefined,
1294 });
1295
1296 expect(output?.appId).toBe("service-1");
1297 expect(output?.deploymentId).toBe("version-live");
1298 expect(output?.deploymentEndpointDomain).toBe("version-live.preview.prisma.build");
1299 expect(output?.deploymentUrl).toBe("https://version-live.preview.prisma.build");
1300 expect(output?.appEndpointDomain).toBe("api.prisma.build");
1301 expect(output?.url).toBe("https://api.prisma.build");
1302 expect(output?.promoted).toBe(true);
1303 expect(Unowned.is(output!)).toBe(true);
1304 expect(calls).toEqual([
1305 ["listApps", { projectId: "project-1", query: { limit: "100" } }],
1306 ["getDeployment", "version-live"],
1307 ]);
1308 }).pipe(
1309 Effect.provide(computeProviderLive()),
1310 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
1311 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
1312 Effect.provide(FetchHttpClient.layer),
1313 Effect.provide(PlatformServices),
1314 );
1315 },
1316 { tags: ["provider:prisma:branch"] },
1317 );
1318
1319 it.effect(
1320 "reads the live deployment through the canonical route",
1321 () => {
1322 const calls: Array<[string, unknown]> = [];
1323 const client = {
1324 listApps: (projectId: string, query: unknown) => {
1325 calls.push(["listApps", { projectId, query }]);
1326 return Effect.succeed([
1327 {
1328 id: "service-1",
1329 type: "app" as const,
1330 url: "https://api.prisma.test/v1/services/service-1",
1331 name: "api",
1332 region: { id: "us-east-1", name: "US East" },
1333 projectId,
1334 branchId: "branch-main",
1335 latestDeploymentId: "version-live",
1336 appEndpointDomain: "api.prisma.build",
1337 createdAt: "2026-01-01T00:00:00Z",
1338 },
1339 ]);
1340 },
1341 getDeployment: (id: string) => {
1342 calls.push(["getDeployment", id]);
1343 return Effect.succeed({
1344 id,
1345 type: "deployment" as const,
1346 serviceId: "service-1",
1347 url: `https://api.prisma.test/v1/deployments/${id}`,
1348 foundryVersionId: "foundry-live",
1349 status: "running",
1350 previewDomain: "version-live.preview.prisma.build",
1351 createdAt: "2026-01-01T00:00:00Z",
1352 });
1353 },
1354 } as unknown as PrismaManagementClient;
1355
1356 return Effect.gen(function* () {
1357 const provider = yield* Provider.findProvider(Compute);
1358 const output = yield* provider.read!({
1359 id: "App",
1360 fqn: "App",
1361 instanceId: "00000000000000000000000000000000",
1362 olds: { project: "project-1", appName: "api" },
1363 output: undefined,
1364 });
1365
1366 expect(output?.deploymentId).toBe("version-live");
1367 expect(output?.promoted).toBe(true);
1368 expect(output?.deploymentUrl).toBe("https://version-live.preview.prisma.build");
1369 expect(calls).toEqual([
1370 ["listApps", { projectId: "project-1", query: { limit: "100" } }],
1371 ["getDeployment", "version-live"],
1372 ]);
1373 }).pipe(
1374 Effect.provide(computeProviderLive()),
1375 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
1376 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
1377 Effect.provide(FetchHttpClient.layer),
1378 Effect.provide(PlatformServices),
1379 );
1380 },
1381 { tags: ["provider:prisma:branch"] },
1382 );
1383
1384 it.effect(
1385 "marks stored deployment unpromoted when live latest differs",
1386 () => {
1387 const calls: Array<[string, unknown]> = [];
1388 const client = {
1389 getApp: (id: string) => {
1390 calls.push(["getApp", id]);
1391 return Effect.succeed({
1392 id,
1393 type: "app" as const,
1394 url: "https://api.prisma.test/v1/services/service-1",
1395 name: "api",
1396 region: { id: "us-east-1", name: "US East" },
1397 projectId: "project-1",
1398 branchId: "branch-main",
1399 latestDeploymentId: "version-live",
1400 appEndpointDomain: "api.prisma.build",
1401 createdAt: "2026-01-01T00:00:00Z",
1402 });
1403 },
1404 getDeployment: (id: string) => {
1405 calls.push(["getDeployment", id]);
1406 return Effect.succeed({
1407 id,
1408 type: "deployment" as const,
1409 serviceId: "service-1",
1410 url: `https://api.prisma.test/v1/deployments/${id}`,
1411 foundryVersionId: `foundry-${id}`,
1412 status: "running",
1413 previewDomain: `${id}.preview.prisma.build`,
1414 createdAt: "2026-01-01T00:00:00Z",
1415 });
1416 },
1417 listAppDeployments: () =>
1418 Effect.succeed([
1419 {
1420 id: "version-old",
1421 type: "deployment" as const,
1422 serviceId: "service-1",
1423 url: "https://api.prisma.test/v1/deployments/version-old",
1424 foundryVersionId: "foundry-version-old",
1425 createdAt: "2026-01-01T00:00:00Z",
1426 },
1427 ]),
1428 } as unknown as PrismaManagementClient;
1429
1430 return Effect.gen(function* () {
1431 const provider = yield* Provider.findProvider(Compute);
1432 const output = yield* provider.read!({
1433 id: "App",
1434 fqn: "App",
1435 instanceId: "00000000000000000000000000000000",
1436 olds: { project: "project-1", appName: "api" },
1437 output: {
1438 appId: "service-1",
1439 deploymentId: "version-old",
1440 projectId: "project-1",
1441 appName: "api",
1442 regionId: "us-east-1",
1443 deploymentEndpointDomain: "version-old.preview.prisma.build",
1444 deploymentUrl: "https://version-old.preview.prisma.build",
1445 appEndpointDomain: "api.prisma.build",
1446 url: "https://api.prisma.build",
1447 promoted: true,
1448 previousDeploymentId: undefined,
1449 previousDeploymentAction: undefined,
1450 artifactHash: Redacted.make("hash-old"),
1451 local: false,
1452 },
1453 });
1454
1455 expect(output?.deploymentId).toBe("version-old");
1456 expect(output?.promoted).toBe(false);
1457 expect(output?.deploymentEndpointDomain).toBe("version-old.preview.prisma.build");
1458 expect(output?.url).toBe("https://version-old.preview.prisma.build");
1459 expect(calls).toEqual([
1460 ["getApp", "service-1"],
1461 ["getDeployment", "version-old"],
1462 ]);
1463 }).pipe(
1464 Effect.provide(computeProviderLive()),
1465 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
1466 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
1467 Effect.provide(FetchHttpClient.layer),
1468 Effect.provide(PlatformServices),
1469 );
1470 },
1471 { tags: ["provider:prisma:branch"] },
1472 );
1473
1474 it.effect(
1475 "returns the preview URL for unpromoted Compute deploys",
1476 () => {
1477 const calls: Array<[string, unknown?]> = [];
1478 let status = "new";
1479 const client = {
1480 getApp: (id: string) => {
1481 calls.push(["getApp", id]);
1482 return Effect.succeed({
1483 id,
1484 type: "app" as const,
1485 url: "https://api.prisma.test/v1/services/service-1",
1486 name: "api",
1487 region: { id: "us-east-1", name: "US East" },
1488 projectId: "project-1",
1489 branchId: "branch-main",
1490 latestDeploymentId: "version-live",
1491 appEndpointDomain: "api.prisma.build",
1492 createdAt: "2026-01-01T00:00:00Z",
1493 });
1494 },
1495 listEnvironmentVariables: () => Effect.succeed([]),
1496 createAppDeployment: (appId: string, input: unknown) => {
1497 calls.push(["createAppDeployment", { appId, input }]);
1498 return Effect.succeed({
1499 id: "version-new",
1500 type: "deployment" as const,
1501 url: "https://api.prisma.test/v1/deployments/version-new",
1502 foundryVersionId: "foundry-new",
1503 uploadUrl: null,
1504 });
1505 },
1506 getDeployment: (id: string) => {
1507 calls.push(["getDeployment", id]);
1508 return Effect.succeed({
1509 id,
1510 type: "deployment" as const,
1511 serviceId: "service-1",
1512 url: `https://api.prisma.test/v1/deployments/${id}`,
1513 foundryVersionId: `foundry-${id}`,
1514 status,
1515 previewDomain: "version-new.preview.prisma.build",
1516 createdAt: "2026-01-01T00:00:00Z",
1517 });
1518 },
1519 startDeployment: (id: string) =>
1520 Effect.sync(() => {
1521 calls.push(["startDeployment", id]);
1522 status = "running";
1523 return { previewDomain: "version-new.preview.prisma.build" };
1524 }),
1525 } as unknown as PrismaManagementClient;
1526
1527 return Effect.gen(function* () {
1528 const provider = yield* Compute.Provider;
1529 const output = yield* provider.reconcile({
1530 id: "App",
1531 fqn: "App",
1532 instanceId: "00000000000000000000000000000000",
1533 news: {
1534 project: "project-1",
1535 appName: "api",
1536 branchId: "branch-main",
1537 skipCodeUpload: true,
1538 skipPromote: true,
1539 verifyUrl: false,
1540 },
1541 olds: undefined,
1542 output: {
1543 appId: "service-1",
1544 deploymentId: undefined,
1545 projectId: "project-1",
1546 appName: "api",
1547 regionId: "us-east-1",
1548 deploymentEndpointDomain: undefined,
1549 deploymentUrl: undefined,
1550 appEndpointDomain: "api.prisma.build",
1551 url: "https://api.prisma.build",
1552 promoted: true,
1553 previousDeploymentId: undefined,
1554 previousDeploymentAction: undefined,
1555 artifactHash: undefined,
1556 local: false,
1557 },
1558 session: undefined as never,
1559 bindings: [],
1560 });
1561
1562 expect(output.promoted).toBe(false);
1563 expect(output.deploymentUrl).toBe("https://version-new.preview.prisma.build");
1564 expect(output.appEndpointDomain).toBe("api.prisma.build");
1565 expect(output.url).toBe("https://version-new.preview.prisma.build");
1566 expect(calls).toEqual([
1567 ["getApp", "service-1"],
1568 [
1569 "createAppDeployment",
1570 { appId: "service-1", input: { portMapping: { http: 8080 }, skipCodeUpload: true } },
1571 ],
1572 ["getDeployment", "version-new"],
1573 ["startDeployment", "version-new"],
1574 ["getDeployment", "version-new"],
1575 ]);
1576 }).pipe(
1577 Effect.provide(computeProviderLive()),
1578 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
1579 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
1580 Effect.provide(FetchHttpClient.layer),
1581 Effect.provide(PlatformServices),
1582 );
1583 },
1584 { tags: ["provider:prisma:branch"] },
1585 );
1586
1587 it.effect(
1588 "syncs a newly created service branch before creating a version",
1589 () => {
1590 const calls: Array<[string, unknown]> = [];
1591 const client = {
1592 listApps: (projectId: string, query: unknown) => {
1593 calls.push(["listApps", { projectId, query }]);
1594 return Effect.succeed([]);
1595 },
1596 createApp: (projectId: string, input: unknown) => {
1597 calls.push(["createApp", { projectId, input }]);
1598 return Effect.succeed({
1599 id: "service-1",
1600 type: "app" as const,
1601 url: "https://api.prisma.test/v1/services/service-1",
1602 name: "api",
1603 region: { id: "us-east-1", name: "US East" },
1604 projectId,
1605 branchId: null,
1606 latestDeploymentId: null,
1607 appEndpointDomain: "api.prisma.build",
1608 createdAt: "2026-01-01T00:00:00Z",
1609 });
1610 },
1611 updateApp: (id: string, input: unknown) => {
1612 calls.push(["updateApp", { id, input }]);
1613 return Effect.succeed({
1614 id,
1615 type: "app" as const,
1616 url: "https://api.prisma.test/v1/services/service-1",
1617 name: "api",
1618 region: { id: "us-east-1", name: "US East" },
1619 projectId: "project-1",
1620 branchId: "branch-main",
1621 latestDeploymentId: null,
1622 appEndpointDomain: "api.prisma.build",
1623 createdAt: "2026-01-01T00:00:00Z",
1624 });
1625 },
1626 createAppDeployment: (appId: string, input: unknown) => {
1627 calls.push(["createAppDeployment", { appId, input }]);
1628 return Effect.succeed({
1629 id: "version-1",
1630 type: "deployment" as const,
1631 url: "https://api.prisma.test/v1/deployments/version-1",
1632 foundryVersionId: "foundry-1",
1633 uploadUrl: "https://upload.prisma.test/version-1.tar.gz",
1634 });
1635 },
1636 getDeployment: (id: string) => {
1637 calls.push(["getDeployment", id]);
1638 return Effect.succeed({
1639 id,
1640 type: "deployment" as const,
1641 serviceId: "service-1",
1642 url: "https://api.prisma.test/v1/deployments/version-1",
1643 foundryVersionId: "foundry-1",
1644 status: "new",
1645 previewDomain: "version-1.preview.prisma.build",
1646 createdAt: "2026-01-01T00:00:00Z",
1647 });
1648 },
1649 } as unknown as PrismaManagementClient;
1650 const http = HttpClient.make((request) =>
1651 Effect.succeed(HttpClientResponse.fromWeb(request, new Response(null))),
1652 );
1653 return Effect.gen(function* () {
1654 const provider = yield* Compute.Provider;
1655 const output = yield* provider.reconcile({
1656 id: "App",
1657 fqn: "App",
1658 instanceId: "00000000000000000000000000000000",
1659 news: {
1660 project: "project-1",
1661 appName: "api",
1662 branchId: "branch-main",
1663 artifactPath: fixtureArtifactPath,
1664 start: false,
1665 skipPromote: true,
1666 },
1667 olds: undefined,
1668 output: undefined,
1669 session: undefined as never,
1670 bindings: [],
1671 });
1672
1673 expect(output.appId).toBe("service-1");
1674 expect(output.deploymentId).toBe("version-1");
1675 expect(calls).toContainEqual([
1676 "createApp",
1677 {
1678 projectId: "project-1",
1679 input: {
1680 displayName: "api",
1681 regionId: undefined,
1682 branchId: "branch-main",
1683 branchGitName: undefined,
1684 },
1685 },
1686 ]);
1687 expect(calls).toContainEqual([
1688 "updateApp",
1689 {
1690 id: "service-1",
1691 input: { displayName: "api", branchId: "branch-main", branchGitName: undefined },
1692 },
1693 ]);
1694 const updateIndex = calls.findIndex(([name]) => name === "updateApp");
1695 const versionIndex = calls.findIndex(([name]) => name === "createAppDeployment");
1696 expect(updateIndex).toBeGreaterThan(-1);
1697 expect(versionIndex).toBeGreaterThan(updateIndex);
1698 }).pipe(
1699 Effect.provide(computeProviderLive()),
1700 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
1701 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
1702 Effect.provide(Layer.succeed(HttpClient.HttpClient, http)),
1703 Effect.provide(PlatformServices),
1704 );
1705 },
1706 { tags: ["provider:prisma:branch"] },
1707 );
1708
1709 it.effect(
1710 "creates a new version when branch attachment changes without artifact changes",
1711 () => {
1712 const calls: Array<[string, unknown]> = [];
1713 let branchId: string | null = "branch-main";
1714 let versionCounter = 0;
1715
1716 const service = () => ({
1717 id: "service-1",
1718 type: "app" as const,
1719 url: "https://api.prisma.test/v1/services/service-1",
1720 name: "api",
1721 region: { id: "us-east-1", name: "US East" },
1722 projectId: "project-1",
1723 branchId,
1724 latestDeploymentId: "version-seed",
1725 appEndpointDomain: "api.prisma.build",
1726 createdAt: "2026-01-01T00:00:00Z",
1727 });
1728
1729 const client = {
1730 getApp: (id: string) => {
1731 calls.push(["getApp", id]);
1732 return Effect.succeed(service());
1733 },
1734 updateApp: (id: string, input: { branchId?: string | null }) => {
1735 calls.push(["updateApp", { id, input }]);
1736 branchId = input.branchId ?? null;
1737 return Effect.succeed(service());
1738 },
1739 createAppDeployment: (appId: string, input: unknown) => {
1740 versionCounter += 1;
1741 const id = `version-${versionCounter}`;
1742 calls.push(["createAppDeployment", { appId, input, id }]);
1743 return Effect.succeed({
1744 id,
1745 type: "deployment" as const,
1746 url: `https://api.prisma.test/v1/deployments/${id}`,
1747 foundryVersionId: `foundry-${versionCounter}`,
1748 uploadUrl: null,
1749 });
1750 },
1751 getDeployment: (id: string) => {
1752 calls.push(["getDeployment", id]);
1753 return Effect.succeed({
1754 id,
1755 type: "deployment" as const,
1756 serviceId: "service-1",
1757 url: `https://api.prisma.test/v1/deployments/${id}`,
1758 foundryVersionId: id.replace("version", "foundry"),
1759 status: "new",
1760 previewDomain: `${id}.preview.prisma.build`,
1761 createdAt: "2026-01-01T00:00:00Z",
1762 });
1763 },
1764 } as unknown as PrismaManagementClient;
1765
1766 const baseProps = {
1767 project: "project-1",
1768 appName: "api",
1769 branchId: "branch-main",
1770 skipCodeUpload: true,
1771 start: false,
1772 skipPromote: true,
1773 };
1774
1775 return Effect.gen(function* () {
1776 const provider = yield* Compute.Provider;
1777 const first = yield* provider.reconcile({
1778 id: "App",
1779 fqn: "App",
1780 instanceId: "00000000000000000000000000000000",
1781 news: baseProps,
1782 olds: undefined,
1783 output: {
1784 appId: "service-1",
1785 deploymentId: undefined,
1786 projectId: "project-1",
1787 appName: "api",
1788 regionId: "us-east-1",
1789 deploymentEndpointDomain: undefined,
1790 deploymentUrl: undefined,
1791 appEndpointDomain: "api.prisma.build",
1792 url: "https://api.prisma.build",
1793 promoted: false,
1794 previousDeploymentId: undefined,
1795 previousDeploymentAction: undefined,
1796 artifactHash: undefined,
1797 local: false,
1798 },
1799 session: undefined as never,
1800 bindings: [],
1801 });
1802
1803 const second = yield* provider.reconcile({
1804 id: "App",
1805 fqn: "App",
1806 instanceId: "00000000000000000000000000000000",
1807 news: { ...baseProps, branchId: "branch-feature" },
1808 olds: baseProps,
1809 output: first,
1810 session: undefined as never,
1811 bindings: [],
1812 });
1813
1814 expect(first.deploymentId).toBe("version-1");
1815 expect(second.deploymentId).toBe("version-2");
1816 expect(second.artifactHash).not.toBe(first.artifactHash);
1817 expect(calls).toContainEqual([
1818 "updateApp",
1819 {
1820 id: "service-1",
1821 input: { displayName: "api", branchId: "branch-feature", branchGitName: undefined },
1822 },
1823 ]);
1824 expect(calls.filter(([name]) => name === "createAppDeployment")).toHaveLength(2);
1825 }).pipe(
1826 Effect.provide(computeProviderLive()),
1827 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
1828 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
1829 );
1830 },
1831 { tags: ["provider:prisma:branch"] },
1832 );
1833
1834 it.effect(
1835 "does not mutate remote Compute state when artifact resolution fails",
1836 () => {
1837 const calls: Array<[string, unknown?]> = [];
1838 const client = {
1839 listApps: (projectId: string, query: unknown) => {
1840 calls.push(["listApps", { projectId, query }]);
1841 return Effect.succeed([]);
1842 },
1843 createApp: (projectId: string, input: unknown) => {
1844 calls.push(["createApp", { projectId, input }]);
1845 return Effect.die("should not create service");
1846 },
1847 listEnvironmentVariables: (query: unknown) => {
1848 calls.push(["listEnvironmentVariables", query]);
1849 return Effect.succeed([]);
1850 },
1851 createEnvironmentVariable: (input: unknown) => {
1852 calls.push(["createEnvironmentVariable", input]);
1853 return Effect.die("should not create env");
1854 },
1855 } as unknown as PrismaManagementClient;
1856
1857 return Effect.gen(function* () {
1858 const path = yield* Path.Path;
1859 const missingArtifact = path.resolve("tmp", "alchemy-prisma-missing-artifact.tar.gz");
1860
1861 const provider = yield* Compute.Provider;
1862 const error = yield* provider
1863 .reconcile({
1864 id: "App",
1865 fqn: "App",
1866 instanceId: "00000000000000000000000000000000",
1867 news: {
1868 project: "project-1",
1869 appName: "api",
1870 artifactPath: missingArtifact,
1871 env: { TOKEN: "secret" },
1872 },
1873 olds: undefined,
1874 output: undefined,
1875 session: undefined as never,
1876 bindings: [],
1877 })
1878 .pipe(Effect.flip);
1879
1880 expect(error).toBeDefined();
1881 expect(calls).toEqual([]);
1882 }).pipe(
1883 Effect.provide(computeProviderLive()),
1884 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
1885 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
1886 Effect.provide(PlatformServices),
1887 );
1888 },
1889 { tags: ["provider:prisma:branch"] },
1890 );
1891
1892 it.effect(
1893 "forwards command build output limits before cloud mutation",
1894 () =>
1895 Effect.gen(function* () {
1896 const fs = yield* FileSystem.FileSystem;
1897 const root = yield* fs.makeTempDirectory({
1898 prefix: "alchemy-prisma-compute-build-limit-",
1899 });
1900 const provider = yield* Compute.Provider;
1901 const error = yield* provider
1902 .reconcile({
1903 id: "App",
1904 fqn: "App",
1905 instanceId: "00000000000000000000000000000000",
1906 news: {
1907 project: "project-1",
1908 appName: "api",
1909 path: root,
1910 build: {
1911 command: "mkdir -p dist; printf '123456789'",
1912 outdir: "dist",
1913 entrypoint: "server.js",
1914 outputLimitBytes: 8,
1915 },
1916 },
1917 olds: undefined,
1918 output: undefined,
1919 session: undefined as never,
1920 bindings: [],
1921 })
1922 .pipe(Effect.flip);
1923
1924 expect(error.message).toContain("Build stdout exceeded the 8 byte output safety limit");
1925 }).pipe(
1926 Effect.provide(computeProviderLive()),
1927 Effect.provide(
1928 Layer.succeed(PrismaClient, withDefaultBranch({} as PrismaManagementClient)),
1929 ),
1930 // Fails before any cloud mutation: every Management API route is
1931 // unregistered so a stray call fails loudly.
1932 Effect.provide(makeFakeManagementApi(unhandled).layer),
1933 Effect.provide(PlatformServices),
1934 ),
1935 { tags: ["provider:prisma:branch"] },
1936 );
1937
1938 it.effect(
1939 "fails when Prisma omits an upload URL for app artifacts",
1940 () => {
1941 const calls: Array<[string, unknown?]> = [];
1942 const client = {
1943 getApp: () => {
1944 calls.push(["getApp"]);
1945 return Effect.succeed({
1946 id: "service-1",
1947 type: "app" as const,
1948 url: "https://api.prisma.test/v1/services/service-1",
1949 name: "api",
1950 region: { id: "us-east-1", name: "US East" },
1951 projectId: "project-1",
1952 branchId: "branch-main",
1953 latestDeploymentId: "version-old",
1954 appEndpointDomain: "api.prisma.build",
1955 createdAt: "2026-01-01T00:00:00Z",
1956 });
1957 },
1958 listEnvironmentVariables: () => Effect.succeed([]),
1959 createAppDeployment: () => {
1960 calls.push(["createAppDeployment"]);
1961 return Effect.succeed({
1962 id: "version-1",
1963 type: "deployment" as const,
1964 url: "https://api.prisma.test/v1/deployments/version-1",
1965 foundryVersionId: "foundry-1",
1966 uploadUrl: null,
1967 });
1968 },
1969 getDeployment: (id: string) => {
1970 calls.push(["getDeployment", id]);
1971 return Effect.succeed({
1972 id,
1973 type: "deployment" as const,
1974 serviceId: "service-1",
1975 url: `https://api.prisma.test/v1/deployments/${id}`,
1976 foundryVersionId: "foundry-1",
1977 status: "new",
1978 previewDomain: null,
1979 createdAt: "2026-01-01T00:00:00Z",
1980 });
1981 },
1982 deleteDeployment: (id: string) => {
1983 calls.push(["deleteDeployment", id]);
1984 return Effect.void;
1985 },
1986 } as unknown as PrismaManagementClient;
1987
1988 return Effect.gen(function* () {
1989 const provider = yield* Compute.Provider;
1990 const error = yield* provider
1991 .reconcile({
1992 id: "App",
1993 fqn: "App",
1994 instanceId: "00000000000000000000000000000000",
1995 news: {
1996 project: "project-1",
1997 appName: "api",
1998 artifactPath: fixtureArtifactPath,
1999 branchId: "branch-main",
2000 start: false,
2001 skipPromote: true,
2002 },
2003 olds: undefined,
2004 output: {
2005 appId: "service-1",
2006 deploymentId: undefined,
2007 projectId: "project-1",
2008 appName: "api",
2009 regionId: "us-east-1",
2010 deploymentEndpointDomain: undefined,
2011 deploymentUrl: undefined,
2012 appEndpointDomain: "api.prisma.build",
2013 url: "https://api.prisma.build",
2014 promoted: false,
2015 previousDeploymentId: undefined,
2016 previousDeploymentAction: undefined,
2017 artifactHash: undefined,
2018 local: false,
2019 },
2020 session: undefined as never,
2021 bindings: [],
2022 })
2023 .pipe(Effect.flip);
2024
2025 expect(error).toBeInstanceOf(Error);
2026 expect(error.message).toContain("did not return an upload URL");
2027 expect(calls).toContainEqual(["deleteDeployment", "version-1"]);
2028 }).pipe(
2029 Effect.provide(computeProviderLive()),
2030 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
2031 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
2032 Effect.provide(PlatformServices),
2033 );
2034 },
2035 { tags: ["provider:prisma:branch"] },
2036 );
2037
2038 it.effect(
2039 "refuses a persisted App with mismatched immutable identity",
2040 () => {
2041 const calls: string[] = [];
2042 const client = {
2043 getApp: () => {
2044 calls.push("getApp");
2045 return Effect.succeed({
2046 id: "service-1",
2047 type: "app" as const,
2048 url: "https://api.prisma.test/v1/services/service-1",
2049 name: "api",
2050 region: { id: "us-east-1", name: "US East" },
2051 projectId: "project-other",
2052 branchId: "branch-main",
2053 latestDeploymentId: null,
2054 appEndpointDomain: "api.prisma.build",
2055 createdAt: "2026-01-01T00:00:00Z",
2056 });
2057 },
2058 updateApp: () => Effect.die("must not patch immutable identity drift"),
2059 createAppDeployment: () => Effect.die("must not deploy against immutable identity drift"),
2060 } as unknown as PrismaManagementClient;
2061
2062 return Effect.gen(function* () {
2063 const provider = yield* Compute.Provider;
2064 const error = yield* provider
2065 .reconcile({
2066 id: "App",
2067 fqn: "App",
2068 instanceId: "00000000000000000000000000000000",
2069 news: {
2070 project: "project-1",
2071 appName: "api",
2072 artifactPath: fixtureArtifactPath,
2073 branchId: "branch-main",
2074 start: false,
2075 skipPromote: true,
2076 },
2077 olds: undefined,
2078 output: {
2079 appId: "service-1",
2080 deploymentId: undefined,
2081 projectId: "project-1",
2082 appName: "api",
2083 regionId: "us-east-1",
2084 deploymentEndpointDomain: undefined,
2085 deploymentUrl: undefined,
2086 appEndpointDomain: "api.prisma.build",
2087 url: "https://api.prisma.build",
2088 promoted: false,
2089 previousDeploymentId: undefined,
2090 previousDeploymentAction: undefined,
2091 artifactHash: undefined,
2092 local: false,
2093 },
2094 session: undefined as never,
2095 bindings: [],
2096 })
2097 .pipe(Effect.flip);
2098
2099 expect(error.message).toContain("project-other");
2100 expect(error.message).toContain("Refusing to patch");
2101 expect(calls).toEqual(["getApp"]);
2102 }).pipe(
2103 Effect.provide(computeProviderLive()),
2104 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
2105 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
2106 Effect.provide(FetchHttpClient.layer),
2107 Effect.provide(PlatformServices),
2108 );
2109 },
2110 { tags: ["provider:prisma:branch"] },
2111 );
2112
2113 it.effect(
2114 "deletes a newly created App when a later create step fails",
2115 () => {
2116 const calls: Array<[string, unknown?]> = [];
2117 const client = {
2118 listApps: (projectId: string, query: unknown) => {
2119 calls.push(["listApps", { projectId, query }]);
2120 return Effect.succeed([]);
2121 },
2122 createApp: (projectId: string, input: unknown) => {
2123 calls.push(["createApp", { projectId, input }]);
2124 return Effect.succeed({
2125 id: "service-1",
2126 type: "app" as const,
2127 url: "https://api.prisma.test/v1/services/service-1",
2128 name: "api",
2129 region: { id: "us-east-1", name: "US East" },
2130 projectId,
2131 branchId: "branch-main",
2132 latestDeploymentId: null,
2133 appEndpointDomain: "api.prisma.build",
2134 createdAt: "2026-01-01T00:00:00Z",
2135 });
2136 },
2137 listEnvironmentVariables: () => Effect.succeed([]),
2138 createAppDeployment: () => {
2139 calls.push(["createAppDeployment"]);
2140 return Effect.succeed({
2141 id: "version-1",
2142 type: "deployment" as const,
2143 url: "https://api.prisma.test/v1/deployments/version-1",
2144 foundryVersionId: "foundry-1",
2145 uploadUrl: null,
2146 });
2147 },
2148 getDeployment: (id: string) => {
2149 calls.push(["getDeployment", id]);
2150 return Effect.succeed({
2151 id,
2152 type: "deployment" as const,
2153 serviceId: "service-1",
2154 url: `https://api.prisma.test/v1/deployments/${id}`,
2155 foundryVersionId: "foundry-1",
2156 status: "new",
2157 previewDomain: null,
2158 createdAt: "2026-01-01T00:00:00Z",
2159 });
2160 },
2161 deleteDeployment: (id: string) => {
2162 calls.push(["deleteDeployment", id]);
2163 return Effect.void;
2164 },
2165 listAppDeployments: (appId: string) => {
2166 calls.push(["listAppDeployments", appId]);
2167 return Effect.succeed([]);
2168 },
2169 deleteApp: (id: string) => {
2170 calls.push(["deleteApp", id]);
2171 return Effect.void;
2172 },
2173 } as unknown as PrismaManagementClient;
2174
2175 return Effect.gen(function* () {
2176 const provider = yield* Compute.Provider;
2177 const error = yield* provider
2178 .reconcile({
2179 id: "App",
2180 fqn: "App",
2181 instanceId: "00000000000000000000000000000000",
2182 news: {
2183 project: "project-1",
2184 appName: "api",
2185 artifactPath: fixtureArtifactPath,
2186 branchId: "branch-main",
2187 start: false,
2188 skipPromote: true,
2189 },
2190 olds: undefined,
2191 output: undefined,
2192 session: undefined as never,
2193 bindings: [],
2194 })
2195 .pipe(Effect.flip);
2196
2197 expect(error).toBeInstanceOf(Error);
2198 expect(error.message).toContain("did not return an upload URL");
2199 expect(calls).toContainEqual(["deleteDeployment", "version-1"]);
2200 expect(calls).toContainEqual(["deleteApp", "service-1"]);
2201 }).pipe(
2202 Effect.provide(computeProviderLive()),
2203 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
2204 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
2205 Effect.provide(PlatformServices),
2206 );
2207 },
2208 { tags: ["provider:prisma:branch"] },
2209 );
2210
2211 it.effect(
2212 "deletes created deployment when artifact upload fails",
2213 () => {
2214 const calls: Array<[string, unknown?]> = [];
2215 const client = {
2216 getApp: () =>
2217 Effect.succeed({
2218 id: "service-1",
2219 type: "app" as const,
2220 url: "https://api.prisma.test/v1/services/service-1",
2221 name: "api",
2222 region: { id: "us-east-1", name: "US East" },
2223 projectId: "project-1",
2224 branchId: "branch-main",
2225 latestDeploymentId: null,
2226 appEndpointDomain: "api.prisma.build",
2227 createdAt: "2026-01-01T00:00:00Z",
2228 }),
2229 listEnvironmentVariables: () => Effect.succeed([]),
2230 createAppDeployment: () => {
2231 calls.push(["createAppDeployment"]);
2232 return Effect.succeed({
2233 id: "version-1",
2234 type: "deployment" as const,
2235 url: "https://api.prisma.test/v1/deployments/version-1",
2236 foundryVersionId: "foundry-1",
2237 uploadUrl: "https://upload.prisma.test/app.tar.gz",
2238 });
2239 },
2240 getDeployment: (id: string) => {
2241 calls.push(["getDeployment", id]);
2242 return Effect.succeed({
2243 id,
2244 type: "deployment" as const,
2245 serviceId: "service-1",
2246 url: `https://api.prisma.test/v1/deployments/${id}`,
2247 foundryVersionId: "foundry-1",
2248 status: "new",
2249 previewDomain: null,
2250 createdAt: "2026-01-01T00:00:00Z",
2251 });
2252 },
2253 deleteDeployment: (id: string) => {
2254 calls.push(["deleteDeployment", id]);
2255 return Effect.void;
2256 },
2257 } as unknown as PrismaManagementClient;
2258 const http = HttpClient.make((request) =>
2259 Effect.succeed(
2260 HttpClientResponse.fromWeb(request, new Response("upload failed", { status: 500 })),
2261 ),
2262 );
2263
2264 return Effect.gen(function* () {
2265 const provider = yield* Compute.Provider;
2266 const error = yield* provider
2267 .reconcile({
2268 id: "App",
2269 fqn: "App",
2270 instanceId: "00000000000000000000000000000000",
2271 news: {
2272 project: "project-1",
2273 appName: "api",
2274 artifactPath: fixtureArtifactPath,
2275 branchId: "branch-main",
2276 start: false,
2277 skipPromote: true,
2278 },
2279 olds: undefined,
2280 output: {
2281 appId: "service-1",
2282 deploymentId: undefined,
2283 projectId: "project-1",
2284 appName: "api",
2285 regionId: "us-east-1",
2286 deploymentEndpointDomain: undefined,
2287 deploymentUrl: undefined,
2288 appEndpointDomain: "api.prisma.build",
2289 url: "https://api.prisma.build",
2290 promoted: false,
2291 previousDeploymentId: undefined,
2292 previousDeploymentAction: undefined,
2293 artifactHash: undefined,
2294 local: false,
2295 },
2296 session: undefined as never,
2297 bindings: [],
2298 })
2299 .pipe(Effect.flip);
2300
2301 expect(error).toBeInstanceOf(Error);
2302 expect(error.message).toContain("artifact upload failed");
2303 expect(calls).toContainEqual(["deleteDeployment", "version-1"]);
2304 }).pipe(
2305 Effect.provide(computeProviderLive()),
2306 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
2307 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
2308 Effect.provide(Layer.succeed(HttpClient.HttpClient, http)),
2309 Effect.provide(PlatformServices),
2310 );
2311 },
2312 { tags: ["provider:prisma:branch"] },
2313 );
2314
2315 it.effect(
2316 "deletes created deployment when start fails",
2317 () => {
2318 const calls: Array<[string, unknown?]> = [];
2319 const client = {
2320 getApp: (id: string) => {
2321 calls.push(["getApp", id]);
2322 return Effect.succeed({
2323 id,
2324 type: "app" as const,
2325 url: `https://api.prisma.test/v1/services/${id}`,
2326 name: "api",
2327 region: { id: "us-east-1", name: "US East" },
2328 projectId: "project-1",
2329 branchId: "branch-main",
2330 latestDeploymentId: "version-old",
2331 appEndpointDomain: "api.prisma.build",
2332 createdAt: "2026-01-01T00:00:00Z",
2333 });
2334 },
2335 createAppDeployment: (appId: string, input: unknown) => {
2336 calls.push(["createAppDeployment", { appId, input }]);
2337 return Effect.succeed({
2338 id: "version-1",
2339 type: "deployment" as const,
2340 url: "https://api.prisma.test/v1/deployments/version-1",
2341 foundryVersionId: "foundry-1",
2342 uploadUrl: "https://upload.prisma.test/app.tar.gz",
2343 });
2344 },
2345 getDeployment: (id: string) => {
2346 calls.push(["getDeployment", id]);
2347 return Effect.succeed({
2348 id,
2349 type: "deployment" as const,
2350 serviceId: "service-1",
2351 url: `https://api.prisma.test/v1/deployments/${id}`,
2352 foundryVersionId: "foundry-1",
2353 status: "new",
2354 previewDomain: null,
2355 createdAt: "2026-01-01T00:00:00Z",
2356 });
2357 },
2358 startDeployment: (id: string) => {
2359 calls.push(["startDeployment", id]);
2360 return Effect.fail(
2361 new PrismaApiError({
2362 method: "POST",
2363 path: `/v1/deployments/${id}/start`,
2364 status: 400,
2365 message: "start failed",
2366 }),
2367 );
2368 },
2369 deleteDeployment: (id: string) => {
2370 calls.push(["deleteDeployment", id]);
2371 return Effect.void;
2372 },
2373 } as unknown as PrismaManagementClient;
2374 const http = HttpClient.make((request) =>
2375 readHttpBodyBytes(request.body as HttpBody.HttpBody).pipe(
2376 Effect.as(HttpClientResponse.fromWeb(request, new Response(null))),
2377 ),
2378 );
2379
2380 return Effect.gen(function* () {
2381 const provider = yield* Compute.Provider;
2382 const error = yield* provider
2383 .reconcile({
2384 id: "App",
2385 fqn: "App",
2386 instanceId: "00000000000000000000000000000000",
2387 news: {
2388 project: "project-1",
2389 appName: "api",
2390 artifactPath: fixtureArtifactPath,
2391 branchId: "branch-main",
2392 },
2393 olds: undefined,
2394 output: {
2395 appId: "service-1",
2396 deploymentId: undefined,
2397 projectId: "project-1",
2398 appName: "api",
2399 regionId: "us-east-1",
2400 deploymentEndpointDomain: undefined,
2401 deploymentUrl: undefined,
2402 appEndpointDomain: "api.prisma.build",
2403 url: "https://api.prisma.build",
2404 promoted: false,
2405 previousDeploymentId: undefined,
2406 previousDeploymentAction: undefined,
2407 artifactHash: undefined,
2408 local: false,
2409 },
2410 session: undefined as never,
2411 bindings: [],
2412 })
2413 .pipe(Effect.flip);
2414
2415 // Over the wire the injected failure decodes into the typed error.
2416 expect(error._tag).toBe("BadRequest");
2417 expect(error.message).toBe("start failed");
2418 expect(calls).toContainEqual(["deleteDeployment", "version-1"]);
2419 }).pipe(
2420 Effect.provide(computeProviderLive()),
2421 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
2422 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
2423 Effect.provide(Layer.succeed(HttpClient.HttpClient, http)),
2424 Effect.provide(PlatformServices),
2425 );
2426 },
2427 { tags: ["provider:prisma:branch"] },
2428 );
2429
2430 it.live(
2431 "blocks promotion and deletes a new deployment when preview health fails",
2432 () => {
2433 const fixture = makeHealthLifecycleFixture({ previewStatus: 503 });
2434
2435 return Effect.gen(function* () {
2436 const provider = yield* Compute.Provider;
2437 const error = yield* provider
2438 .reconcile({
2439 id: "App",
2440 fqn: "App",
2441 instanceId: "00000000000000000000000000000000",
2442 news: {
2443 project: "project-1",
2444 appName: "api",
2445 artifactPath: fixtureArtifactV2Path,
2446 branchId: "branch-main",
2447 healthCheck: { path: "/health" },
2448 pollIntervalMs: 1,
2449 timeoutSeconds: 0.05,
2450 urlReadinessTimeoutSeconds: 0.02,
2451 },
2452 olds: {
2453 project: "project-1",
2454 appName: "api",
2455 artifactPath: fixtureArtifactV1Path,
2456 branchId: "branch-main",
2457 },
2458 output: {
2459 appId: "service-1",
2460 deploymentId: "version-old",
2461 projectId: "project-1",
2462 appName: "api",
2463 regionId: "us-east-1",
2464 deploymentEndpointDomain: "version-old.preview.prisma.build",
2465 deploymentUrl: "https://version-old.preview.prisma.build",
2466 appEndpointDomain: "api.prisma.build",
2467 url: "https://api.prisma.build",
2468 promoted: true,
2469 previousDeploymentId: undefined,
2470 previousDeploymentAction: undefined,
2471 artifactHash: Redacted.make("old-hash"),
2472 local: false,
2473 },
2474 session: undefined as never,
2475 bindings: [],
2476 })
2477 .pipe(Effect.flip);
2478
2479 expect(error.message).toContain("https://version-new.preview.prisma.build/health");
2480 expect(error.message).toContain("HTTP 503");
2481 expect(fixture.calls.filter(([operation]) => operation === "promoteApp")).toEqual([]);
2482 expect(fixture.calls).toContainEqual(["stopDeployment", "version-new"]);
2483 expect(fixture.calls).toContainEqual(["deleteDeployment", "version-new"]);
2484 expect(fixture.hasDeployment("version-new")).toBe(false);
2485 expect(fixture.hasDeployment("version-old")).toBe(true);
2486 expect(fixture.latestDeploymentId()).toBe("version-old");
2487 }).pipe(
2488 Effect.provide(computeProviderLive()),
2489 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(fixture.client))),
2490 Effect.provide(apiRoutedHttp(withDefaultBranch(fixture.client))),
2491 Effect.provideService(HttpClient.HttpClient, fixture.http),
2492 Effect.provide(PlatformServices),
2493 );
2494 },
2495 { tags: ["provider:prisma:branch"] },
2496 );
2497
2498 it.live(
2499 "rolls back promotion and deletes the new deployment when stable health fails",
2500 () => {
2501 const fixture = makeHealthLifecycleFixture({ previewStatus: 204, stableStatus: 503 });
2502
2503 return Effect.gen(function* () {
2504 const provider = yield* Compute.Provider;
2505 const error = yield* provider
2506 .reconcile({
2507 id: "App",
2508 fqn: "App",
2509 instanceId: "00000000000000000000000000000000",
2510 news: {
2511 project: "project-1",
2512 appName: "api",
2513 artifactPath: fixtureArtifactV2Path,
2514 branchId: "branch-main",
2515 healthCheck: { path: "/health" },
2516 pollIntervalMs: 1,
2517 timeoutSeconds: 0.05,
2518 urlReadinessTimeoutSeconds: 0.02,
2519 },
2520 olds: {
2521 project: "project-1",
2522 appName: "api",
2523 artifactPath: fixtureArtifactV1Path,
2524 branchId: "branch-main",
2525 },
2526 output: {
2527 appId: "service-1",
2528 deploymentId: "version-old",
2529 projectId: "project-1",
2530 appName: "api",
2531 regionId: "us-east-1",
2532 deploymentEndpointDomain: "version-old.preview.prisma.build",
2533 deploymentUrl: "https://version-old.preview.prisma.build",
2534 appEndpointDomain: "api.prisma.build",
2535 url: "https://api.prisma.build",
2536 promoted: true,
2537 previousDeploymentId: undefined,
2538 previousDeploymentAction: undefined,
2539 artifactHash: Redacted.make("old-hash"),
2540 local: false,
2541 },
2542 session: undefined as never,
2543 bindings: [],
2544 })
2545 .pipe(Effect.flip);
2546
2547 expect(error.message).toContain("https://api.prisma.build/health");
2548 expect(error.message).toContain("HTTP 503");
2549 expect(fixture.calls).toContainEqual([
2550 "promoteApp",
2551 { appId: "service-1", deploymentId: "version-new" },
2552 ]);
2553 expect(fixture.calls).toContainEqual([
2554 "rollbackApp",
2555 { appId: "service-1", deploymentId: "version-old" },
2556 ]);
2557 expect(fixture.calls).toContainEqual(["deleteDeployment", "version-new"]);
2558 const promotionIndex = fixture.calls.findIndex(
2559 ([operation]) => operation === "promoteApp",
2560 );
2561 const rollbackIndex = fixture.calls.findIndex(
2562 ([operation]) => operation === "rollbackApp",
2563 );
2564 const deletionIndex = fixture.calls.findIndex(
2565 ([operation]) => operation === "deleteDeployment",
2566 );
2567 expect(promotionIndex).toBeLessThan(rollbackIndex);
2568 expect(rollbackIndex).toBeLessThan(deletionIndex);
2569 expect(fixture.hasDeployment("version-new")).toBe(false);
2570 expect(fixture.hasDeployment("version-old")).toBe(true);
2571 expect(fixture.latestDeploymentId()).toBe("version-old");
2572 }).pipe(
2573 Effect.provide(computeProviderLive()),
2574 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(fixture.client))),
2575 Effect.provide(apiRoutedHttp(withDefaultBranch(fixture.client))),
2576 Effect.provideService(HttpClient.HttpClient, fixture.http),
2577 Effect.provide(PlatformServices),
2578 );
2579 },
2580 { tags: ["provider:prisma:branch"] },
2581 );
2582
2583 it.live(
2584 "does not probe stable health after a successful promotion response that does not converge",
2585 () => {
2586 const fixture = makeHealthLifecycleFixture({
2587 previewStatus: 204,
2588 stableStatus: 204,
2589 promoteUpdatesLatest: false,
2590 });
2591
2592 return Effect.gen(function* () {
2593 const provider = yield* Compute.Provider;
2594 const error = yield* provider
2595 .reconcile({
2596 id: "App",
2597 fqn: "App",
2598 instanceId: "00000000000000000000000000000000",
2599 news: {
2600 project: "project-1",
2601 appName: "api",
2602 artifactPath: fixtureArtifactV2Path,
2603 branchId: "branch-main",
2604 healthCheck: { path: "/health" },
2605 pollIntervalMs: 1,
2606 timeoutSeconds: 0.02,
2607 urlReadinessTimeoutSeconds: 0.02,
2608 },
2609 olds: {
2610 project: "project-1",
2611 appName: "api",
2612 artifactPath: fixtureArtifactV1Path,
2613 branchId: "branch-main",
2614 },
2615 output: {
2616 appId: "service-1",
2617 deploymentId: "version-old",
2618 projectId: "project-1",
2619 appName: "api",
2620 regionId: "us-east-1",
2621 deploymentEndpointDomain: "version-old.preview.prisma.build",
2622 deploymentUrl: "https://version-old.preview.prisma.build",
2623 appEndpointDomain: "api.prisma.build",
2624 url: "https://api.prisma.build",
2625 promoted: true,
2626 previousDeploymentId: undefined,
2627 previousDeploymentAction: undefined,
2628 artifactHash: Redacted.make("old-hash"),
2629 local: false,
2630 },
2631 session: undefined as never,
2632 bindings: [],
2633 })
2634 .pipe(Effect.flip);
2635
2636 expect(error).toBeInstanceOf(AggregateError);
2637 expect((error as AggregateError).message).toContain("promotion returned success");
2638 expect((error as AggregateError).message).toContain("did not converge");
2639 expect(fixture.latestDeploymentId()).toBe("version-old");
2640 expect(fixture.hasDeployment("version-new")).toBe(true);
2641 expect(
2642 fixture.calls.filter(
2643 ([operation, value]) =>
2644 operation === "healthRequest" && value === "https://api.prisma.build/health",
2645 ),
2646 ).toEqual([]);
2647 expect(fixture.calls.filter(([operation]) => operation === "deleteDeployment")).toEqual(
2648 [],
2649 );
2650 }).pipe(
2651 Effect.provide(computeProviderLive()),
2652 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(fixture.client))),
2653 Effect.provide(apiRoutedHttp(withDefaultBranch(fixture.client))),
2654 Effect.provideService(HttpClient.HttpClient, fixture.http),
2655 Effect.provide(PlatformServices),
2656 );
2657 },
2658 { tags: ["provider:prisma:branch"] },
2659 );
2660
2661 it.live(
2662 "does not delete a promoted deployment after a successful rollback response that does not converge",
2663 () => {
2664 const fixture = makeHealthLifecycleFixture({
2665 previewStatus: 204,
2666 stableStatus: 503,
2667 rollbackUpdatesLatest: false,
2668 });
2669
2670 return Effect.gen(function* () {
2671 const provider = yield* Compute.Provider;
2672 const error = yield* provider
2673 .reconcile({
2674 id: "App",
2675 fqn: "App",
2676 instanceId: "00000000000000000000000000000000",
2677 news: {
2678 project: "project-1",
2679 appName: "api",
2680 artifactPath: fixtureArtifactV2Path,
2681 branchId: "branch-main",
2682 healthCheck: { path: "/health" },
2683 pollIntervalMs: 1,
2684 timeoutSeconds: 0.02,
2685 urlReadinessTimeoutSeconds: 0.02,
2686 },
2687 olds: {
2688 project: "project-1",
2689 appName: "api",
2690 artifactPath: fixtureArtifactV1Path,
2691 branchId: "branch-main",
2692 },
2693 output: {
2694 appId: "service-1",
2695 deploymentId: "version-old",
2696 projectId: "project-1",
2697 appName: "api",
2698 regionId: "us-east-1",
2699 deploymentEndpointDomain: "version-old.preview.prisma.build",
2700 deploymentUrl: "https://version-old.preview.prisma.build",
2701 appEndpointDomain: "api.prisma.build",
2702 url: "https://api.prisma.build",
2703 promoted: true,
2704 previousDeploymentId: undefined,
2705 previousDeploymentAction: undefined,
2706 artifactHash: Redacted.make("old-hash"),
2707 local: false,
2708 },
2709 session: undefined as never,
2710 bindings: [],
2711 })
2712 .pipe(Effect.flip);
2713
2714 expect(error).toBeInstanceOf(AggregateError);
2715 expect((error as AggregateError).message).toContain(
2716 "rollback to deployment 'version-old' did not converge",
2717 );
2718 expect(fixture.latestDeploymentId()).toBe("version-new");
2719 expect(fixture.hasDeployment("version-new")).toBe(true);
2720 expect(fixture.hasDeployment("version-old")).toBe(true);
2721 expect(fixture.calls.filter(([operation]) => operation === "deleteDeployment")).toEqual(
2722 [],
2723 );
2724 }).pipe(
2725 Effect.provide(computeProviderLive()),
2726 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(fixture.client))),
2727 Effect.provide(apiRoutedHttp(withDefaultBranch(fixture.client))),
2728 Effect.provideService(HttpClient.HttpClient, fixture.http),
2729 Effect.provide(PlatformServices),
2730 );
2731 },
2732 { tags: ["provider:prisma:branch"] },
2733 );
2734
2735 it.live(
2736 "replaces a hash-matching terminal failed deployment before cleaning it",
2737 () => {
2738 const fixture = makeHealthLifecycleFixture({
2739 latestDeploymentId: null,
2740 previewStatus: 204,
2741 stableStatus: 204,
2742 });
2743 const news = {
2744 project: "project-1",
2745 appName: "api",
2746 artifactPath: fixtureArtifactV1Path,
2747 branchId: "branch-main",
2748 healthCheck: { path: "/health" },
2749 pollIntervalMs: 1,
2750 timeoutSeconds: 0.02,
2751 urlReadinessTimeoutSeconds: 0.02,
2752 } as const;
2753
2754 return Effect.gen(function* () {
2755 const provider = yield* Compute.Provider;
2756 const first = yield* provider.reconcile({
2757 id: "App",
2758 fqn: "App",
2759 instanceId: "00000000000000000000000000000000",
2760 news,
2761 olds: undefined,
2762 output: {
2763 appId: "service-1",
2764 deploymentId: undefined,
2765 projectId: "project-1",
2766 appName: "api",
2767 regionId: "us-east-1",
2768 deploymentEndpointDomain: undefined,
2769 deploymentUrl: undefined,
2770 appEndpointDomain: "api.prisma.build",
2771 url: undefined,
2772 promoted: false,
2773 previousDeploymentId: undefined,
2774 previousDeploymentAction: undefined,
2775 artifactHash: undefined,
2776 local: false,
2777 },
2778 session: undefined as never,
2779 bindings: [],
2780 });
2781
2782 fixture.setDeploymentStatus("version-new", "failed");
2783 fixture.calls.splice(0);
2784 const recovered = yield* provider.reconcile({
2785 id: "App",
2786 fqn: "App",
2787 instanceId: "00000000000000000000000000000000",
2788 news,
2789 olds: news,
2790 output: first,
2791 session: undefined as never,
2792 bindings: [],
2793 });
2794
2795 const replacementCreationIndex = fixture.calls.findIndex(
2796 ([operation]) => operation === "createAppDeployment",
2797 );
2798 const stableHealthIndex = fixture.calls.findIndex(
2799 ([operation, value]) =>
2800 operation === "healthRequest" && value === "https://api.prisma.build/health",
2801 );
2802 const failedDeletionIndex = fixture.calls.findIndex(
2803 ([operation, value]) => operation === "deleteDeployment" && value === "version-new",
2804 );
2805
2806 expect(recovered.deploymentId).toBe("version-new-2");
2807 expect(recovered.promoted).toBe(true);
2808 expect(recovered.readinessStatus).toBe("ready");
2809 expect(recovered.previousDeploymentId).toBe("version-new");
2810 expect(recovered.previousDeploymentAction).toBe("destroyed");
2811 expect(replacementCreationIndex).toBeGreaterThanOrEqual(0);
2812 expect(stableHealthIndex).toBeGreaterThan(replacementCreationIndex);
2813 expect(failedDeletionIndex).toBeGreaterThan(stableHealthIndex);
2814 expect(fixture.hasDeployment("version-new")).toBe(false);
2815 expect(fixture.hasDeployment("version-new-2")).toBe(true);
2816 expect(
2817 fixture.calls.filter(
2818 ([operation, value]) => operation === "startDeployment" && value === "version-new",
2819 ),
2820 ).toEqual([]);
2821 }).pipe(
2822 Effect.provide(computeProviderLive()),
2823 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(fixture.client))),
2824 Effect.provide(apiRoutedHttp(withDefaultBranch(fixture.client))),
2825 Effect.provideService(HttpClient.HttpClient, fixture.http),
2826 Effect.provide(PlatformServices),
2827 );
2828 },
2829 { tags: ["provider:prisma:branch"] },
2830 );
2831
2832 it.live(
2833 "destroys a changed-hash terminal failed deployment only after replacement convergence",
2834 () => {
2835 const fixture = makeHealthLifecycleFixture({ previewStatus: 204, stableStatus: 204 });
2836 fixture.setDeploymentStatus("version-old", "failed");
2837
2838 return Effect.gen(function* () {
2839 const provider = yield* Compute.Provider;
2840 const output = yield* provider.reconcile({
2841 id: "App",
2842 fqn: "App",
2843 instanceId: "00000000000000000000000000000000",
2844 news: {
2845 project: "project-1",
2846 appName: "api",
2847 artifactPath: fixtureArtifactV2Path,
2848 branchId: "branch-main",
2849 healthCheck: { path: "/health" },
2850 pollIntervalMs: 1,
2851 timeoutSeconds: 0.02,
2852 urlReadinessTimeoutSeconds: 0.02,
2853 },
2854 olds: {
2855 project: "project-1",
2856 appName: "api",
2857 artifactPath: fixtureArtifactV1Path,
2858 branchId: "branch-main",
2859 },
2860 output: {
2861 appId: "service-1",
2862 deploymentId: "version-old",
2863 projectId: "project-1",
2864 appName: "api",
2865 regionId: "us-east-1",
2866 deploymentEndpointDomain: "version-old.preview.prisma.build",
2867 deploymentUrl: "https://version-old.preview.prisma.build",
2868 appEndpointDomain: "api.prisma.build",
2869 url: "https://api.prisma.build",
2870 promoted: true,
2871 previousDeploymentId: undefined,
2872 previousDeploymentAction: undefined,
2873 artifactHash: Redacted.make("old-hash"),
2874 local: false,
2875 },
2876 session: undefined as never,
2877 bindings: [],
2878 });
2879
2880 const stableHealthIndex = fixture.calls.findIndex(
2881 ([operation, value]) =>
2882 operation === "healthRequest" && value === "https://api.prisma.build/health",
2883 );
2884 const failedDeletionIndex = fixture.calls.findIndex(
2885 ([operation, value]) => operation === "deleteDeployment" && value === "version-old",
2886 );
2887
2888 expect(output.deploymentId).toBe("version-new");
2889 expect(output.previousDeploymentId).toBe("version-old");
2890 expect(output.previousDeploymentAction).toBe("destroyed");
2891 expect(stableHealthIndex).toBeGreaterThanOrEqual(0);
2892 expect(failedDeletionIndex).toBeGreaterThan(stableHealthIndex);
2893 expect(fixture.hasDeployment("version-old")).toBe(false);
2894 expect(fixture.hasDeployment("version-new")).toBe(true);
2895 expect(
2896 fixture.calls.filter(
2897 ([operation, value]) => operation === "stopDeployment" && value === "version-old",
2898 ),
2899 ).toEqual([]);
2900 }).pipe(
2901 Effect.provide(computeProviderLive()),
2902 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(fixture.client))),
2903 Effect.provide(apiRoutedHttp(withDefaultBranch(fixture.client))),
2904 Effect.provideService(HttpClient.HttpClient, fixture.http),
2905 Effect.provide(PlatformServices),
2906 );
2907 },
2908 { tags: ["provider:prisma:branch"] },
2909 );
2910
2911 it.live(
2912 "never rolls back to a changed-hash terminal failed deployment and blocks duplicate retry creation",
2913 () => {
2914 const fixture = makeHealthLifecycleFixture({ previewStatus: 204, stableStatus: 503 });
2915 fixture.setDeploymentStatus("version-old", "failed");
2916 const news = {
2917 project: "project-1",
2918 appName: "api",
2919 artifactPath: fixtureArtifactV2Path,
2920 branchId: "branch-main",
2921 healthCheck: { path: "/health" },
2922 pollIntervalMs: 1,
2923 timeoutSeconds: 0.02,
2924 urlReadinessTimeoutSeconds: 0.02,
2925 } as const;
2926 const olds = {
2927 project: "project-1",
2928 appName: "api",
2929 artifactPath: fixtureArtifactV1Path,
2930 branchId: "branch-main",
2931 } as const;
2932 const output = {
2933 appId: "service-1",
2934 deploymentId: "version-old",
2935 projectId: "project-1",
2936 appName: "api",
2937 regionId: "us-east-1",
2938 deploymentEndpointDomain: "version-old.preview.prisma.build",
2939 deploymentUrl: "https://version-old.preview.prisma.build",
2940 appEndpointDomain: "api.prisma.build",
2941 url: "https://api.prisma.build",
2942 promoted: true,
2943 previousDeploymentId: undefined,
2944 previousDeploymentAction: undefined,
2945 artifactHash: Redacted.make("old-hash"),
2946 local: false,
2947 } as const;
2948
2949 return Effect.gen(function* () {
2950 const provider = yield* Compute.Provider;
2951 const firstError = yield* provider
2952 .reconcile({
2953 id: "App",
2954 fqn: "App",
2955 instanceId: "00000000000000000000000000000000",
2956 news,
2957 olds,
2958 output,
2959 session: undefined as never,
2960 bindings: [],
2961 })
2962 .pipe(Effect.flip);
2963
2964 expect(firstError).toBeInstanceOf(AggregateError);
2965 expect((firstError as AggregateError).message).toContain(
2966 "no safe rollback target exists",
2967 );
2968 expect(fixture.calls.filter(([operation]) => operation === "rollbackApp")).toEqual([]);
2969 expect(fixture.latestDeploymentId()).toBe("version-new");
2970 expect(fixture.hasDeployment("version-old")).toBe(true);
2971 expect(fixture.hasDeployment("version-new")).toBe(true);
2972
2973 fixture.setStableStatus(204);
2974 const callsBeforeRetry = fixture.calls.length;
2975 const retryError = yield* provider
2976 .reconcile({
2977 id: "App",
2978 fqn: "App",
2979 instanceId: "00000000000000000000000000000000",
2980 news,
2981 olds,
2982 output,
2983 session: undefined as never,
2984 bindings: [],
2985 })
2986 .pipe(Effect.flip);
2987 const retryCalls = fixture.calls.slice(callsBeforeRetry);
2988
2989 expect(retryError).toBeInstanceOf(AggregateError);
2990 expect((retryError as AggregateError).message).toContain(
2991 "cannot prove that the live deployment is the interrupted replacement",
2992 );
2993 expect(retryCalls.filter(([operation]) => operation === "createAppDeployment")).toEqual(
2994 [],
2995 );
2996 expect(retryCalls.filter(([operation]) => operation === "rollbackApp")).toEqual([]);
2997 expect(retryCalls.filter(([operation]) => operation === "deleteDeployment")).toEqual([]);
2998 expect(fixture.latestDeploymentId()).toBe("version-new");
2999 expect(fixture.hasDeployment("version-old")).toBe(true);
3000 expect(fixture.hasDeployment("version-new")).toBe(true);
3001 }).pipe(
3002 Effect.provide(computeProviderLive()),
3003 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(fixture.client))),
3004 Effect.provide(apiRoutedHttp(withDefaultBranch(fixture.client))),
3005 Effect.provideService(HttpClient.HttpClient, fixture.http),
3006 Effect.provide(PlatformServices),
3007 );
3008 },
3009 { tags: ["provider:prisma:branch"] },
3010 );
3011
3012 it.live(
3013 "does not create another generation after failed terminal replacement loses a safe rollback target",
3014 () => {
3015 const fixture = makeHealthLifecycleFixture({
3016 latestDeploymentId: null,
3017 previewStatus: 204,
3018 stableStatus: 204,
3019 });
3020 const news = {
3021 project: "project-1",
3022 appName: "api",
3023 artifactPath: fixtureArtifactV1Path,
3024 branchId: "branch-main",
3025 healthCheck: { path: "/health" },
3026 pollIntervalMs: 1,
3027 timeoutSeconds: 0.02,
3028 urlReadinessTimeoutSeconds: 0.02,
3029 } as const;
3030
3031 return Effect.gen(function* () {
3032 const provider = yield* Compute.Provider;
3033 const first = yield* provider.reconcile({
3034 id: "App",
3035 fqn: "App",
3036 instanceId: "00000000000000000000000000000000",
3037 news,
3038 olds: undefined,
3039 output: {
3040 appId: "service-1",
3041 deploymentId: undefined,
3042 projectId: "project-1",
3043 appName: "api",
3044 regionId: "us-east-1",
3045 deploymentEndpointDomain: undefined,
3046 deploymentUrl: undefined,
3047 appEndpointDomain: "api.prisma.build",
3048 url: undefined,
3049 promoted: false,
3050 previousDeploymentId: undefined,
3051 previousDeploymentAction: undefined,
3052 artifactHash: undefined,
3053 local: false,
3054 },
3055 session: undefined as never,
3056 bindings: [],
3057 });
3058
3059 fixture.setDeploymentStatus("version-new", "failed");
3060 fixture.setStableStatus(503);
3061 fixture.calls.splice(0);
3062 const replacementError = yield* provider
3063 .reconcile({
3064 id: "App",
3065 fqn: "App",
3066 instanceId: "00000000000000000000000000000000",
3067 news,
3068 olds: news,
3069 output: first,
3070 session: undefined as never,
3071 bindings: [],
3072 })
3073 .pipe(Effect.flip);
3074
3075 expect(replacementError).toBeInstanceOf(AggregateError);
3076 expect((replacementError as AggregateError).message).toContain(
3077 "no safe rollback target exists",
3078 );
3079 expect(fixture.latestDeploymentId()).toBe("version-new-2");
3080 expect(fixture.hasDeployment("version-new")).toBe(true);
3081 expect(fixture.hasDeployment("version-new-2")).toBe(true);
3082 expect(fixture.calls.filter(([operation]) => operation === "deleteDeployment")).toEqual(
3083 [],
3084 );
3085
3086 fixture.setStableStatus(204);
3087 const callsBeforeRetry = fixture.calls.length;
3088 const retryError = yield* provider
3089 .reconcile({
3090 id: "App",
3091 fqn: "App",
3092 instanceId: "00000000000000000000000000000000",
3093 news,
3094 olds: news,
3095 output: first,
3096 session: undefined as never,
3097 bindings: [],
3098 })
3099 .pipe(Effect.flip);
3100 const retryCalls = fixture.calls.slice(callsBeforeRetry);
3101
3102 expect(retryError).toBeInstanceOf(AggregateError);
3103 expect((retryError as AggregateError).message).toContain(
3104 "cannot prove that the live deployment is the interrupted replacement",
3105 );
3106 expect(retryCalls.filter(([operation]) => operation === "createAppDeployment")).toEqual(
3107 [],
3108 );
3109 expect(retryCalls.filter(([operation]) => operation === "deleteDeployment")).toEqual([]);
3110 expect(fixture.latestDeploymentId()).toBe("version-new-2");
3111 expect(fixture.hasDeployment("version-new")).toBe(true);
3112 expect(fixture.hasDeployment("version-new-2")).toBe(true);
3113 }).pipe(
3114 Effect.provide(computeProviderLive()),
3115 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(fixture.client))),
3116 Effect.provide(apiRoutedHttp(withDefaultBranch(fixture.client))),
3117 Effect.provideService(HttpClient.HttpClient, fixture.http),
3118 Effect.provide(PlatformServices),
3119 );
3120 },
3121 { tags: ["provider:prisma:branch"] },
3122 );
3123
3124 it.live(
3125 "fails closed on rollback failure and recovers from persisted state before retrying",
3126 () => {
3127 const fixture = makeHealthLifecycleFixture({
3128 previewStatus: 204,
3129 stableStatus: 503,
3130 rollbackFailures: 2,
3131 });
3132 const news = {
3133 project: "project-1",
3134 appName: "api",
3135 artifactPath: fixtureArtifactV2Path,
3136 branchId: "branch-main",
3137 healthCheck: { path: "/health" },
3138 pollIntervalMs: 1,
3139 timeoutSeconds: 0.05,
3140 urlReadinessTimeoutSeconds: 0.02,
3141 } as const;
3142 const olds = {
3143 project: "project-1",
3144 appName: "api",
3145 artifactPath: fixtureArtifactV1Path,
3146 branchId: "branch-main",
3147 } as const;
3148 const output = {
3149 appId: "service-1",
3150 deploymentId: "version-old",
3151 projectId: "project-1",
3152 appName: "api",
3153 regionId: "us-east-1",
3154 deploymentEndpointDomain: "version-old.preview.prisma.build",
3155 deploymentUrl: "https://version-old.preview.prisma.build",
3156 appEndpointDomain: "api.prisma.build",
3157 url: "https://api.prisma.build",
3158 promoted: true,
3159 previousDeploymentId: undefined,
3160 previousDeploymentAction: undefined,
3161 artifactHash: Redacted.make("old-hash"),
3162 local: false,
3163 } as const;
3164 const reconcile = Effect.gen(function* () {
3165 const provider = yield* Compute.Provider;
3166 return yield* provider.reconcile({
3167 id: "App",
3168 fqn: "App",
3169 instanceId: "00000000000000000000000000000000",
3170 news,
3171 olds,
3172 output,
3173 session: undefined as never,
3174 bindings: [],
3175 });
3176 });
3177
3178 return Effect.gen(function* () {
3179 const firstError = yield* reconcile.pipe(Effect.flip);
3180
3181 expect(firstError).toBeInstanceOf(AggregateError);
3182 expect((firstError as AggregateError).message).toContain(
3183 "promoted deployment 'version-new'",
3184 );
3185 expect((firstError as AggregateError).message).toContain(
3186 "rollback to deployment 'version-old' did not converge",
3187 );
3188 expect((firstError as AggregateError).message).toContain(
3189 "next reconcile will retry recovery",
3190 );
3191 expect(fixture.latestDeploymentId()).toBe("version-new");
3192 expect(fixture.hasDeployment("version-new")).toBe(true);
3193 expect(fixture.hasDeployment("version-old")).toBe(true);
3194 expect(fixture.calls.filter(([operation]) => operation === "deleteDeployment")).toEqual(
3195 [],
3196 );
3197
3198 fixture.setStableStatus(204);
3199 const callsBeforeBlockedRetry = fixture.calls.length;
3200 const retryError = yield* reconcile.pipe(Effect.flip);
3201 const blockedRetryCalls = fixture.calls.slice(callsBeforeBlockedRetry);
3202
3203 expect(retryError).toBeInstanceOf(AggregateError);
3204 expect((retryError as AggregateError).message).toContain(
3205 "no environment variables or new deployment were changed",
3206 );
3207 expect(
3208 (retryError as AggregateError).errors.some(
3209 (error) => error instanceof Error && error.message === "rollback unavailable",
3210 ),
3211 ).toBe(true);
3212 expect(
3213 blockedRetryCalls.filter(([operation]) => operation === "createAppDeployment"),
3214 ).toEqual([]);
3215 expect(
3216 fixture.calls.filter(([operation]) => operation === "createAppDeployment"),
3217 ).toHaveLength(1);
3218 expect(fixture.latestDeploymentId()).toBe("version-new");
3219 expect(fixture.hasDeployment("version-new")).toBe(true);
3220
3221 const callsBeforeRecovery = fixture.calls.length;
3222 const recovered = yield* reconcile;
3223 const recoveryCalls = fixture.calls.slice(callsBeforeRecovery);
3224 const rollbackIndex = recoveryCalls.findIndex(
3225 ([operation]) => operation === "rollbackApp",
3226 );
3227 const failedDeletionIndex = recoveryCalls.findIndex(
3228 ([operation, value]) => operation === "deleteDeployment" && value === "version-new",
3229 );
3230 const replacementCreationIndex = recoveryCalls.findIndex(
3231 ([operation]) => operation === "createAppDeployment",
3232 );
3233
3234 expect(recovered.deploymentId).toBe("version-new-2");
3235 expect(recovered.promoted).toBe(true);
3236 expect(recovered.readinessStatus).toBe("ready");
3237 expect(rollbackIndex).toBeGreaterThanOrEqual(0);
3238 expect(rollbackIndex).toBeLessThan(failedDeletionIndex);
3239 expect(failedDeletionIndex).toBeLessThan(replacementCreationIndex);
3240 expect(fixture.hasDeployment("version-new")).toBe(false);
3241 expect(fixture.hasDeployment("version-new-2")).toBe(true);
3242 expect(fixture.latestDeploymentId()).toBe("version-new-2");
3243 expect(
3244 fixture.calls.filter(([operation]) => operation === "createAppDeployment"),
3245 ).toHaveLength(2);
3246 }).pipe(
3247 Effect.provide(computeProviderLive()),
3248 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(fixture.client))),
3249 Effect.provide(apiRoutedHttp(withDefaultBranch(fixture.client))),
3250 Effect.provideService(HttpClient.HttpClient, fixture.http),
3251 Effect.provide(PlatformServices),
3252 );
3253 },
3254 { tags: ["provider:prisma:branch"] },
3255 );
3256
3257 it.effect(
3258 "honors custom accepted health statuses before and after promotion",
3259 () => {
3260 const fixture = makeHealthLifecycleFixture({
3261 latestDeploymentId: null,
3262 previewStatus: 302,
3263 stableStatus: 302,
3264 });
3265
3266 return Effect.gen(function* () {
3267 const provider = yield* Compute.Provider;
3268 const output = yield* provider.reconcile({
3269 id: "App",
3270 fqn: "App",
3271 instanceId: "00000000000000000000000000000000",
3272 news: {
3273 project: "project-1",
3274 appName: "api",
3275 artifactPath: fixtureArtifactV2Path,
3276 branchId: "branch-main",
3277 healthCheck: { path: "/ready", statusCodes: [302] },
3278 pollIntervalMs: 1,
3279 timeoutSeconds: 0.05,
3280 urlReadinessTimeoutSeconds: 0.02,
3281 },
3282 olds: undefined,
3283 output: {
3284 appId: "service-1",
3285 deploymentId: undefined,
3286 projectId: "project-1",
3287 appName: "api",
3288 regionId: "us-east-1",
3289 deploymentEndpointDomain: undefined,
3290 deploymentUrl: undefined,
3291 appEndpointDomain: "api.prisma.build",
3292 url: undefined,
3293 promoted: false,
3294 previousDeploymentId: undefined,
3295 previousDeploymentAction: undefined,
3296 artifactHash: undefined,
3297 local: false,
3298 },
3299 session: undefined as never,
3300 bindings: [],
3301 });
3302
3303 expect(output.deploymentId).toBe("version-new");
3304 expect(output.promoted).toBe(true);
3305 expect(output.readinessStatus).toBe("ready");
3306 expect(fixture.calls.filter(([operation]) => operation === "healthRequest")).toEqual([
3307 ["healthRequest", "https://version-new.preview.prisma.build/ready"],
3308 ["healthRequest", "https://api.prisma.build/ready"],
3309 ]);
3310 expect(fixture.calls.filter(([operation]) => operation === "rollbackApp")).toEqual([]);
3311 expect(fixture.calls.filter(([operation]) => operation === "deleteDeployment")).toEqual(
3312 [],
3313 );
3314 }).pipe(
3315 Effect.provide(computeProviderLive()),
3316 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(fixture.client))),
3317 Effect.provide(apiRoutedHttp(withDefaultBranch(fixture.client))),
3318 Effect.provideService(HttpClient.HttpClient, fixture.http),
3319 Effect.provide(PlatformServices),
3320 );
3321 },
3322 { tags: ["provider:prisma:branch"] },
3323 );
3324
3325 it.effect(
3326 "uploads a pre-created artifact from artifactPath",
3327 () => {
3328 let uploaded:
3329 | { url: string; contentType: string | undefined; bytes: Uint8Array }
3330 | undefined;
3331 const client = {
3332 getApp: () =>
3333 Effect.succeed({
3334 id: "service-1",
3335 type: "app" as const,
3336 url: "https://api.prisma.test/v1/services/service-1",
3337 name: "api",
3338 region: { id: "us-east-1", name: "US East" },
3339 projectId: "project-1",
3340 branchId: "branch-main",
3341 latestDeploymentId: "version-old",
3342 appEndpointDomain: "api.prisma.build",
3343 createdAt: "2026-01-01T00:00:00Z",
3344 }),
3345 listEnvironmentVariables: () => Effect.succeed([]),
3346 createAppDeployment: () =>
3347 Effect.succeed({
3348 id: "version-1",
3349 type: "deployment" as const,
3350 url: "https://api.prisma.test/v1/deployments/version-1",
3351 foundryVersionId: "foundry-1",
3352 uploadUrl: "https://upload.prisma.test/app.tar.gz",
3353 }),
3354 getDeployment: (id: string) =>
3355 Effect.succeed({
3356 id,
3357 type: "deployment" as const,
3358 serviceId: "service-1",
3359 url: "https://api.prisma.test/v1/deployments/version-1",
3360 foundryVersionId: "foundry-1",
3361 status: "new",
3362 previewDomain: "version-1.preview.prisma.build",
3363 createdAt: "2026-01-01T00:00:00Z",
3364 }),
3365 } as unknown as PrismaManagementClient;
3366 const http = HttpClient.make((request) =>
3367 Effect.gen(function* () {
3368 const body = request.body as HttpBody.HttpBody;
3369 uploaded = {
3370 url: request.url,
3371 contentType: httpBodyContentType(body),
3372 bytes: yield* readHttpBodyBytes(body),
3373 };
3374 return HttpClientResponse.fromWeb(request, new Response(null));
3375 }),
3376 );
3377
3378 return Effect.gen(function* () {
3379 const fs = yield* FileSystem.FileSystem;
3380 const path = yield* Path.Path;
3381 const root = yield* fs.makeTempDirectory({ prefix: "alchemy-prisma-artifact-" });
3382 const artifactPath = path.join(root, "app.tar.gz");
3383 yield* fs.writeFileString(artifactPath, "prebuilt-archive");
3384
3385 const provider = yield* Compute.Provider;
3386 const output = yield* provider.reconcile({
3387 id: "App",
3388 fqn: "App",
3389 instanceId: "00000000000000000000000000000000",
3390 news: {
3391 project: "project-1",
3392 appName: "api",
3393 artifactPath,
3394 branchId: "branch-main",
3395 start: false,
3396 skipPromote: true,
3397 },
3398 olds: undefined,
3399 output: {
3400 appId: "service-1",
3401 deploymentId: undefined,
3402 projectId: "project-1",
3403 appName: "api",
3404 regionId: "us-east-1",
3405 deploymentEndpointDomain: undefined,
3406 deploymentUrl: undefined,
3407 appEndpointDomain: "api.prisma.build",
3408 url: "https://api.prisma.build",
3409 promoted: false,
3410 previousDeploymentId: undefined,
3411 previousDeploymentAction: undefined,
3412 artifactHash: undefined,
3413 local: false,
3414 },
3415 session: undefined as never,
3416 bindings: [],
3417 });
3418
3419 expect(output.deploymentId).toBe("version-1");
3420 expect(uploaded?.url).toBe("https://upload.prisma.test/app.tar.gz");
3421 expect(uploaded?.contentType).toBe("application/gzip");
3422 expect(new TextDecoder().decode(uploaded?.bytes)).toBe("prebuilt-archive");
3423 }).pipe(
3424 Effect.provide(computeProviderLive()),
3425 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
3426 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
3427 Effect.provide(Layer.succeed(HttpClient.HttpClient, http)),
3428 Effect.provide(PlatformServices),
3429 );
3430 },
3431 { tags: ["provider:prisma:branch"] },
3432 );
3433
3434 it.effect(
3435 "bundles effect-native Compute apps into an upload artifact",
3436 () => {
3437 const calls: Array<[string, unknown]> = [];
3438 let uploaded:
3439 | { url: string; contentType: string | undefined; bytes: Uint8Array }
3440 | undefined;
3441 const client = {
3442 listApps: (projectId: string, query: unknown) => {
3443 calls.push(["listApps", { projectId, query }]);
3444 return Effect.succeed([]);
3445 },
3446 createApp: (projectId: string, input: unknown) => {
3447 calls.push(["createApp", { projectId, input }]);
3448 return Effect.succeed({
3449 id: "service-1",
3450 type: "app" as const,
3451 url: "https://api.prisma.test/v1/services/service-1",
3452 name: "api",
3453 region: { id: "us-east-1", name: "US East" },
3454 projectId,
3455 branchId: "branch-main",
3456 latestDeploymentId: "version-old",
3457 appEndpointDomain: "api.prisma.build",
3458 createdAt: "2026-01-01T00:00:00Z",
3459 });
3460 },
3461 listEnvironmentVariables: () => Effect.succeed([]),
3462 createAppDeployment: (appId: string, input: unknown) => {
3463 calls.push(["createAppDeployment", { appId, input }]);
3464 return Effect.succeed({
3465 id: "version-1",
3466 type: "deployment" as const,
3467 url: "https://api.prisma.test/v1/deployments/version-1",
3468 foundryVersionId: "foundry-1",
3469 uploadUrl: "https://upload.prisma.test/effect.tar.gz",
3470 });
3471 },
3472 getDeployment: (id: string) => {
3473 calls.push(["getDeployment", id]);
3474 return Effect.succeed({
3475 id,
3476 type: "deployment" as const,
3477 serviceId: "service-1",
3478 url: "https://api.prisma.test/v1/deployments/version-1",
3479 foundryVersionId: "foundry-1",
3480 status: "new",
3481 previewDomain: "version-1.preview.prisma.build",
3482 createdAt: "2026-01-01T00:00:00Z",
3483 });
3484 },
3485 } as unknown as PrismaManagementClient;
3486 const http = HttpClient.make((request) =>
3487 Effect.gen(function* () {
3488 const body = request.body as HttpBody.HttpBody;
3489 uploaded = {
3490 url: request.url,
3491 contentType: httpBodyContentType(body),
3492 bytes: yield* readHttpBodyBytes(body),
3493 };
3494 return HttpClientResponse.fromWeb(request, new Response(null));
3495 }),
3496 );
3497
3498 return Effect.gen(function* () {
3499 const fs = yield* FileSystem.FileSystem;
3500 const path = yield* Path.Path;
3501 const root = yield* fs.makeTempDirectory({ prefix: "alchemy-prisma-compute-effect-" });
3502 const main = path.join(root, "app.ts");
3503 yield* fs.writeFileString(
3504 main,
3505 [
3506 'import * as Prisma from "@alchemy.run/prisma";',
3507 'import * as Effect from "effect/Effect";',
3508 'import * as HttpServerResponse from "effect/http/HttpServerResponse";',
3509 "",
3510 "export default Prisma.Compute(",
3511 ' "App",',
3512 " {",
3513 ' project: "project-1",',
3514 ' appName: "api",',
3515 " main: import.meta.filename,",
3516 " port: 4555,",
3517 " },",
3518 " Effect.gen(function* () {",
3519 " return {",
3520 ' fetch: HttpServerResponse.text("effect-native-ok"),',
3521 " };",
3522 " }),",
3523 ");",
3524 "",
3525 ].join("\n"),
3526 );
3527
3528 const provider = yield* Compute.Provider;
3529 const output = yield* provider.reconcile({
3530 id: "App",
3531 fqn: "App",
3532 instanceId: "00000000000000000000000000000000",
3533 news: {
3534 project: "project-1",
3535 appName: "api",
3536 branchId: "branch-main",
3537 main,
3538 port: 4555,
3539 start: false,
3540 skipPromote: true,
3541 },
3542 olds: undefined,
3543 output: undefined,
3544 session: undefined as never,
3545 bindings: [],
3546 });
3547
3548 expect(output.deploymentId).toBe("version-1");
3549 expect(uploaded?.url).toBe("https://upload.prisma.test/effect.tar.gz");
3550 expect(uploaded?.contentType).toBe("application/gzip");
3551 const tar = yield* Effect.sync(() => gunzipSync(uploaded!.bytes));
3552 const manifest = readTarFile(tar, "compute.manifest.json");
3553 const bundle = readTarFile(tar, "bundle/index.js");
3554 expect(JSON.parse(manifest)).toMatchObject({ entrypoint: "bundle/index.js" });
3555 // The generated entry is a shim over @alchemy.run/prisma/Bootstrap;
3556 // its label and the shared "bootstrap starting" message are separate
3557 // literals joined at runtime (see Runtime/Bootstrap.ts).
3558 expect(bundle).toContain("Prisma Compute");
3559 expect(bundle).toContain("bootstrap starting");
3560 expect(bundle).toMatch(/hostname\s*:\s*["'`]0\.0\.0\.0["'`]/);
3561 // The deploy-time stack identity is baked into the artifact (the shim
3562 // passes it to the bootstrap once; the module fans it out to `Stack`
3563 // and `Stage`).
3564 expect(bundle).toContain("prisma-runtime-stack-sentinel");
3565 expect(bundle).toContain("prisma-runtime-stage-sentinel");
3566 expect(bundle).toContain("ALCHEMY_PHASE");
3567 expect(bundle).toContain("runtime");
3568 expect(bundle).toContain("effect-native-ok");
3569 expect(calls).toContainEqual([
3570 "createAppDeployment",
3571 {
3572 appId: "service-1",
3573 input: { portMapping: { http: 4555 }, skipCodeUpload: undefined },
3574 },
3575 ]);
3576 }).pipe(
3577 Effect.provideService(Stack, {
3578 name: "prisma-runtime-stack-sentinel",
3579 stage: "prisma-runtime-stage-sentinel",
3580 bindings: {},
3581 resources: {},
3582 actions: {},
3583 }),
3584 Effect.provide(computeProviderLive()),
3585 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
3586 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
3587 Effect.provide(Layer.succeed(HttpClient.HttpClient, http)),
3588 Effect.provide(PlatformServices),
3589 );
3590 },
3591 { tags: ["provider:prisma:branch"] },
3592 );
3593
3594 it.effect(
3595 "bundles effect-native Compute apps from a named export",
3596 () => {
3597 let uploaded: Uint8Array | undefined;
3598 const client = {
3599 listApps: () => Effect.succeed([]),
3600 createApp: ({ projectId }: { projectId: string }) =>
3601 Effect.succeed({
3602 id: "service-1",
3603 type: "app" as const,
3604 url: "https://api.prisma.test/v1/services/service-1",
3605 name: "api",
3606 region: { id: "us-east-1", name: "US East" },
3607 projectId,
3608 branchId: "branch-main",
3609 latestDeploymentId: "version-old",
3610 appEndpointDomain: "api.prisma.build",
3611 createdAt: "2026-01-01T00:00:00Z",
3612 }),
3613 listEnvironmentVariables: () => Effect.succeed([]),
3614 createAppDeployment: () =>
3615 Effect.succeed({
3616 id: "version-1",
3617 type: "deployment" as const,
3618 url: "https://api.prisma.test/v1/deployments/version-1",
3619 foundryVersionId: "foundry-1",
3620 uploadUrl: "https://upload.prisma.test/effect.tar.gz",
3621 }),
3622 getDeployment: (id: string) =>
3623 Effect.succeed({
3624 id,
3625 type: "deployment" as const,
3626 serviceId: "service-1",
3627 url: "https://api.prisma.test/v1/deployments/version-1",
3628 foundryVersionId: "foundry-1",
3629 status: "new",
3630 previewDomain: "version-1.preview.prisma.build",
3631 createdAt: "2026-01-01T00:00:00Z",
3632 }),
3633 } as unknown as PrismaManagementClient;
3634 const http = HttpClient.make((request) =>
3635 Effect.gen(function* () {
3636 const body = request.body as HttpBody.HttpBody;
3637 uploaded = yield* readHttpBodyBytes(body);
3638 return HttpClientResponse.fromWeb(request, new Response(null));
3639 }),
3640 );
3641
3642 return Effect.gen(function* () {
3643 const fs = yield* FileSystem.FileSystem;
3644 const path = yield* Path.Path;
3645 const root = yield* fs.makeTempDirectory({
3646 prefix: "alchemy-prisma-compute-named-effect-",
3647 });
3648 const main = path.join(root, "app.ts");
3649 yield* fs.writeFileString(
3650 main,
3651 [
3652 'import * as Prisma from "@alchemy.run/prisma";',
3653 'import * as Effect from "effect/Effect";',
3654 'import * as HttpServerResponse from "effect/http/HttpServerResponse";',
3655 "",
3656 "export const Api = Prisma.Compute(",
3657 ' "App",',
3658 " {",
3659 ' project: "project-1",',
3660 ' appName: "api",',
3661 " main: import.meta.filename,",
3662 ' handler: "Api",',
3663 " },",
3664 " Effect.gen(function* () {",
3665 " return {",
3666 ' fetch: HttpServerResponse.text("named-handler-ok"),',
3667 " };",
3668 " }),",
3669 ");",
3670 "",
3671 ].join("\n"),
3672 );
3673
3674 const provider = yield* Compute.Provider;
3675 const output = yield* provider.reconcile({
3676 id: "App",
3677 fqn: "App",
3678 instanceId: "00000000000000000000000000000000",
3679 news: {
3680 project: "project-1",
3681 appName: "api",
3682 branchId: "branch-main",
3683 main,
3684 handler: "Api",
3685 start: false,
3686 skipPromote: true,
3687 },
3688 olds: undefined,
3689 output: undefined,
3690 session: undefined as never,
3691 bindings: [],
3692 });
3693
3694 expect(output.deploymentId).toBe("version-1");
3695 const tarText = new TextDecoder().decode(yield* Effect.sync(() => gunzipSync(uploaded!)));
3696 expect(tarText).toContain("compute.manifest.json");
3697 expect(tarText).toContain("named-handler-ok");
3698 }).pipe(
3699 Effect.provide(computeProviderLive()),
3700 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
3701 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
3702 Effect.provide(Layer.succeed(HttpClient.HttpClient, http)),
3703 Effect.provide(PlatformServices),
3704 );
3705 },
3706 { tags: ["provider:prisma:branch"] },
3707 );
3708
3709 it.effect("syncs env vars through the environment variable API", () => {
3710 const calls: Array<[string, unknown]> = [];
3711 const projectToken = {
3712 id: "env-token",
3713 type: "environment-variable" as const,
3714 url: "https://api.prisma.test/v1/environment-variables/env-token",
3715 projectId: "project-1",
3716 branchId: null,
3717 class: "production" as const,
3718 key: "TOKEN",
3719 valueKid: "kid-1",
3720 isManagedBySystem: false,
3721 createdAt: "2026-01-01T00:00:00Z",
3722 updatedAt: "2026-01-01T00:00:00Z",
3723 };
3724 const projectRemove = {
3725 id: "env-remove",
3726 type: "environment-variable" as const,
3727 url: "https://api.prisma.test/v1/environment-variables/env-remove",
3728 projectId: "project-1",
3729 branchId: null,
3730 class: "production" as const,
3731 key: "REMOVE_ME",
3732 valueKid: "kid-1",
3733 isManagedBySystem: false,
3734 createdAt: "2026-01-01T00:00:00Z",
3735 updatedAt: "2026-01-01T00:00:00Z",
3736 };
3737 const byKey = new Map([
3738 [
3739 "TOKEN",
3740 [
3741 { ...projectToken, id: "env-token-branch", branchId: "branch-1" },
3742 { ...projectToken, id: "env-token-branch-2", branchId: "branch-2" },
3743 projectToken,
3744 ],
3745 ],
3746 [
3747 "REMOVE_ME",
3748 [{ ...projectRemove, id: "env-remove-branch", branchId: "branch-1" }, projectRemove],
3749 ],
3750 ]);
3751
3752 const client = {
3753 listEnvironmentVariables: (query: { key: string }) => {
3754 calls.push(["list", query]);
3755 return Effect.succeed(byKey.get(query.key) ?? []);
3756 },
3757 createEnvironmentVariable: (input: unknown) => {
3758 calls.push(["create", input]);
3759 return Effect.succeed({
3760 id: "env-created",
3761 type: "environment-variable" as const,
3762 url: "https://api.prisma.test/v1/environment-variables/env-created",
3763 projectId: "project-1",
3764 branchId: "branch-main",
3765 class: "production" as const,
3766 key: "API_URL",
3767 valueKid: "kid-2",
3768 isManagedBySystem: false,
3769 createdAt: "2026-01-01T00:00:00Z",
3770 updatedAt: "2026-01-01T00:00:00Z",
3771 });
3772 },
3773 updateEnvironmentVariable: (id: string, input: unknown) => {
3774 calls.push(["update", { id, input }]);
3775 return Effect.succeed(projectToken);
3776 },
3777 deleteEnvironmentVariable: (id: string) => {
3778 calls.push(["delete", id]);
3779 return Effect.void;
3780 },
3781 } as unknown as PrismaManagementClient;
3782
3783 return Effect.gen(function* () {
3784 const result = yield* syncComputeEnvironment(
3785 "project-1",
3786 "production",
3787 {
3788 API_URL: "https://example.test",
3789 TOKEN: Redacted.make("secret"),
3790 REMOVE_ME: null,
3791 SKIP_ME: undefined,
3792 },
3793 undefined,
3794 { TOKEN: "env-token", REMOVE_ME: "env-remove" },
3795 );
3796
3797 expect(result).toEqual({
3798 synced: ["API_URL", "TOKEN"],
3799 deleted: ["REMOVE_ME"],
3800 ownedIds: { API_URL: "env-created", TOKEN: "env-token" },
3801 });
3802 expect(calls).toEqual([
3803 ["list", { projectId: "project-1", class: "production", key: "API_URL", limit: "100" }],
3804 ["list", { projectId: "project-1", class: "production", key: "TOKEN", limit: "100" }],
3805 ["list", { projectId: "project-1", class: "production", key: "REMOVE_ME", limit: "100" }],
3806 [
3807 "create",
3808 {
3809 projectId: "project-1",
3810 class: "production",
3811 key: "API_URL",
3812 value: "https://example.test",
3813 },
3814 ],
3815 ["update", { id: "env-token", input: { value: "secret" } }],
3816 ["delete", "env-remove"],
3817 ]);
3818 }).pipe(Effect.provide(apiRoutedHttp(client)));
3819 });
3820
3821 it.effect("rolls back variables created by a partially failed env sync", () => {
3822 const calls: Array<[string, unknown]> = [];
3823 const createError = new Error("second create failed");
3824 const client = {
3825 listEnvironmentVariables: (query: unknown) => {
3826 calls.push(["list", query]);
3827 return Effect.succeed([]);
3828 },
3829 createEnvironmentVariable: (input: { key: string }) => {
3830 calls.push(["create", input]);
3831 return input.key === "A"
3832 ? Effect.succeed({
3833 id: "env-a",
3834 type: "environment-variable" as const,
3835 url: "https://api.prisma.test/v1/environment-variables/env-a",
3836 projectId: "project-1",
3837 branchId: null,
3838 class: "production" as const,
3839 key: "A",
3840 valueKid: "kid-a",
3841 isManagedBySystem: false,
3842 createdAt: "2026-01-01T00:00:00Z",
3843 updatedAt: "2026-01-01T00:00:00Z",
3844 })
3845 : Effect.fail(createError);
3846 },
3847 deleteEnvironmentVariable: (id: string) => {
3848 calls.push(["delete", id]);
3849 return Effect.void;
3850 },
3851 } as unknown as PrismaManagementClient;
3852
3853 return Effect.gen(function* () {
3854 const error = yield* syncComputeEnvironment("project-1", "production", {
3855 A: "one",
3856 B: "two",
3857 }).pipe(Effect.flip);
3858
3859 expect((error as Error).message).toContain("second create failed");
3860 expect(calls.map(([name]) => name)).toEqual(["list", "list", "create", "create", "delete"]);
3861 expect(calls).toContainEqual(["delete", "env-a"]);
3862 }).pipe(Effect.provide(apiRoutedHttp(client)));
3863 });
3864
3865 it.effect("surfaces env rollback failures with manual cleanup routes", () => {
3866 const createError = new Error("second create failed");
3867 const cleanupError = new Error("rollback delete failed");
3868 const client = {
3869 listEnvironmentVariables: () => Effect.succeed([]),
3870 createEnvironmentVariable: (input: { key: string }) =>
3871 input.key === "A"
3872 ? Effect.succeed({
3873 id: "env-a",
3874 type: "environment-variable" as const,
3875 url: "https://api.prisma.test/v1/environment-variables/env-a",
3876 projectId: "project-1",
3877 branchId: null,
3878 class: "production" as const,
3879 key: "A",
3880 valueKid: "kid-a",
3881 isManagedBySystem: false,
3882 createdAt: "2026-01-01T00:00:00Z",
3883 updatedAt: "2026-01-01T00:00:00Z",
3884 })
3885 : Effect.fail(createError),
3886 deleteEnvironmentVariable: () => Effect.fail(cleanupError),
3887 } as unknown as PrismaManagementClient;
3888
3889 return Effect.gen(function* () {
3890 const error = yield* syncComputeEnvironment("project-1", "production", {
3891 A: "one",
3892 B: "two",
3893 }).pipe(Effect.flip);
3894
3895 expect(error).toBeInstanceOf(AggregateError);
3896 expect(((error as AggregateError).errors[0] as Error).message).toContain(
3897 "second create failed",
3898 );
3899 expect(((error as AggregateError).errors[1] as Error).message).toContain(
3900 "rollback delete failed",
3901 );
3902 expect((error as AggregateError).message).toContain(
3903 "DELETE /v1/environment-variables/env-a",
3904 );
3905 }).pipe(Effect.provide(apiRoutedHttp(client)));
3906 });
3907
3908 it.effect("preflights foreign env ownership before any write", () => {
3909 const calls: string[] = [];
3910 const foreign = {
3911 id: "env-foreign",
3912 type: "environment-variable" as const,
3913 url: "https://api.prisma.test/v1/environment-variables/env-foreign",
3914 projectId: "project-1",
3915 branchId: null,
3916 class: "production" as const,
3917 key: "B",
3918 valueKid: "kid-foreign",
3919 isManagedBySystem: false,
3920 createdAt: "2026-01-01T00:00:00Z",
3921 updatedAt: "2026-01-01T00:00:00Z",
3922 };
3923 const client = {
3924 listEnvironmentVariables: (query: { key: string }) => {
3925 calls.push(`list:${query.key}`);
3926 return Effect.succeed(query.key === "B" ? [foreign] : []);
3927 },
3928 createEnvironmentVariable: () => {
3929 calls.push("create");
3930 return Effect.die("ownership preflight must happen first");
3931 },
3932 } as unknown as PrismaManagementClient;
3933
3934 return Effect.gen(function* () {
3935 const error = yield* syncComputeEnvironment("project-1", "production", {
3936 A: "one",
3937 B: "two",
3938 }).pipe(Effect.flip);
3939
3940 expect((error as Error).message).toContain("is not owned");
3941 expect(calls).toEqual(["list:A", "list:B"]);
3942 }).pipe(Effect.provide(apiRoutedHttp(client)));
3943 });
3944
3945 it.effect(
3946 "preserves old owned env variables when new-scope validation fails",
3947 () => {
3948 const calls: Array<[string, unknown?]> = [];
3949 const client = {
3950 getApp: () =>
3951 Effect.succeed({
3952 id: "service-1",
3953 type: "app" as const,
3954 url: "https://api.prisma.test/v1/services/service-1",
3955 name: "api",
3956 region: { id: "us-east-1", name: "US East" },
3957 projectId: "project-1",
3958 branchId: "branch-main",
3959 latestDeploymentId: "version-old",
3960 appEndpointDomain: "api.prisma.build",
3961 createdAt: "2026-01-01T00:00:00Z",
3962 }),
3963 getBranch: () => Effect.succeed(testBranch("branch-main")),
3964 getDeployment: (id: string) =>
3965 Effect.succeed({
3966 id,
3967 type: "deployment" as const,
3968 serviceId: "service-1",
3969 url: `https://api.prisma.test/v1/deployments/${id}`,
3970 foundryVersionId: `foundry-${id}`,
3971 status: "running",
3972 previewDomain: `${id}.preview.prisma.build`,
3973 createdAt: "2026-01-01T00:00:00Z",
3974 }),
3975 listEnvironmentVariables: (query: { key: string }) => {
3976 calls.push(["listEnvironmentVariables", query]);
3977 return Effect.succeed([
3978 {
3979 id: query.key === "OLD" ? "env-old" : "env-foreign",
3980 type: "environment-variable" as const,
3981 url: `https://api.prisma.test/v1/environment-variables/${query.key}`,
3982 projectId: "project-1",
3983 branchId: null,
3984 class: "production" as const,
3985 key: query.key,
3986 valueKid: "kid-1",
3987 isManagedBySystem: false,
3988 createdAt: "2026-01-01T00:00:00Z",
3989 updatedAt: "2026-01-01T00:00:00Z",
3990 },
3991 ]);
3992 },
3993 deleteEnvironmentVariable: (id: string) => {
3994 calls.push(["deleteEnvironmentVariable", id]);
3995 return Effect.void;
3996 },
3997 } as unknown as PrismaManagementClient;
3998
3999 return Effect.gen(function* () {
4000 const provider = yield* Compute.Provider;
4001 const error = yield* provider
4002 .reconcile({
4003 id: "App",
4004 fqn: "App",
4005 instanceId: "00000000000000000000000000000000",
4006 news: {
4007 project: "project-1",
4008 appName: "api",
4009 artifactPath: fixtureArtifactPath,
4010 branchId: "branch-main",
4011 env: { FOREIGN: "new" },
4012 start: false,
4013 skipPromote: true,
4014 },
4015 olds: {
4016 project: "project-1",
4017 appName: "api",
4018 artifactPath: fixtureArtifactV1Path,
4019 branchId: "branch-main",
4020 env: { OLD: "old" },
4021 },
4022 output: {
4023 appId: "service-1",
4024 deploymentId: "version-old",
4025 projectId: "project-1",
4026 appName: "api",
4027 regionId: "us-east-1",
4028 deploymentEndpointDomain: "version-old.preview.prisma.build",
4029 deploymentUrl: "https://version-old.preview.prisma.build",
4030 appEndpointDomain: "api.prisma.build",
4031 url: "https://api.prisma.build",
4032 promoted: true,
4033 previousDeploymentId: undefined,
4034 previousDeploymentAction: undefined,
4035 environmentVariableIds: { OLD: "env-old" },
4036 environmentClass: "production",
4037 environmentBranchId: null,
4038 artifactHash: Redacted.make("old-hash"),
4039 local: false,
4040 },
4041 session: undefined as never,
4042 bindings: [],
4043 })
4044 .pipe(Effect.flip);
4045
4046 expect(error.message).toContain("is not owned");
4047 expect(calls).toEqual([
4048 [
4049 "listEnvironmentVariables",
4050 { projectId: "project-1", class: "production", key: "FOREIGN", limit: "100" },
4051 ],
4052 ]);
4053 }).pipe(
4054 Effect.provide(computeProviderLive()),
4055 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
4056 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
4057 Effect.provide(FetchHttpClient.layer),
4058 Effect.provide(PlatformServices),
4059 );
4060 },
4061 { tags: ["provider:prisma:branch"] },
4062 );
4063
4064 it.effect("refuses to sync system-managed Compute env vars", () => {
4065 const calls: Array<[string, unknown]> = [];
4066 const systemVariable = {
4067 id: "env-system",
4068 type: "environment-variable" as const,
4069 url: "https://api.prisma.test/v1/environment-variables/env-system",
4070 projectId: "project-1",
4071 branchId: null,
4072 class: "production" as const,
4073 key: "PRISMA_INTERNAL_URL",
4074 valueKid: "kid-system",
4075 isManagedBySystem: true,
4076 createdAt: "2026-01-01T00:00:00Z",
4077 updatedAt: "2026-01-01T00:00:00Z",
4078 };
4079 const client = {
4080 listEnvironmentVariables: (query: unknown) => {
4081 calls.push(["list", query]);
4082 return Effect.succeed([systemVariable]);
4083 },
4084 updateEnvironmentVariable: (id: string, input: unknown) => {
4085 calls.push(["update", { id, input }]);
4086 return Effect.succeed(systemVariable);
4087 },
4088 } as unknown as PrismaManagementClient;
4089
4090 return Effect.gen(function* () {
4091 const error = yield* syncComputeEnvironment("project-1", "production", {
4092 PRISMA_INTERNAL_URL: "secret",
4093 }).pipe(Effect.flip);
4094
4095 expect(error).toBeInstanceOf(Error);
4096 expect((error as Error).message).toContain(
4097 "is managed by Prisma and cannot be managed by Alchemy",
4098 );
4099 expect(calls).toEqual([
4100 [
4101 "list",
4102 {
4103 projectId: "project-1",
4104 class: "production",
4105 key: "PRISMA_INTERNAL_URL",
4106 limit: "100",
4107 },
4108 ],
4109 ]);
4110 }).pipe(Effect.provide(apiRoutedHttp(client)));
4111 });
4112
4113 it.effect(
4114 "validates Compute env vars before remote writes",
4115 () => {
4116 const calls: Array<[string, unknown]> = [];
4117 const client = {
4118 getApp: (id: string) =>
4119 Effect.sync(() => {
4120 calls.push(["getApp", id]);
4121 return {
4122 id,
4123 type: "app" as const,
4124 url: "https://api.prisma.test/v1/services/service-1",
4125 name: "api",
4126 region: { id: "us-east-1", name: "US East" },
4127 projectId: "project-1",
4128 branchId: "branch-main",
4129 latestDeploymentId: "version-old",
4130 appEndpointDomain: "api.prisma.build",
4131 createdAt: "2026-01-01T00:00:00Z",
4132 };
4133 }),
4134 } as unknown as PrismaManagementClient;
4135
4136 return Effect.gen(function* () {
4137 const provider = yield* Compute.Provider;
4138 const error = yield* provider
4139 .reconcile({
4140 id: "App",
4141 fqn: "App",
4142 instanceId: "00000000000000000000000000000000",
4143 news: {
4144 project: "project-1",
4145 appName: "api",
4146 artifactPath: fixtureArtifactV1Path,
4147 env: { "bad-key": "secret" },
4148 },
4149 olds: undefined,
4150 output: undefined,
4151 session: undefined as never,
4152 bindings: [],
4153 })
4154 .pipe(Effect.flip);
4155
4156 expect(error).toBeInstanceOf(Error);
4157 expect(error.message).toContain("must match POSIX env-var key shape");
4158 expect(calls).toEqual([]);
4159 }).pipe(
4160 Effect.provide(computeProviderLive()),
4161 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
4162 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
4163 Effect.provide(PlatformServices),
4164 );
4165 },
4166 { tags: ["provider:prisma:branch"] },
4167 );
4168
4169 it.effect(
4170 "merges binding env into Compute deployment env",
4171 () => {
4172 const calls: Array<[string, unknown]> = [];
4173 const client = {
4174 getApp: (id: string) => {
4175 calls.push(["getApp", id]);
4176 return Effect.succeed({
4177 id,
4178 type: "app" as const,
4179 url: "https://api.prisma.test/v1/services/service-1",
4180 name: "api",
4181 region: { id: "us-east-1", name: "US East" },
4182 projectId: "project-1",
4183 branchId: "branch-main",
4184 latestDeploymentId: "version-old",
4185 appEndpointDomain: "api.prisma.build",
4186 createdAt: "2026-01-01T00:00:00Z",
4187 });
4188 },
4189 listEnvironmentVariables: (query: unknown) => {
4190 calls.push(["listEnvironmentVariables", query]);
4191 return Effect.succeed([]);
4192 },
4193 createEnvironmentVariable: (input: unknown) => {
4194 calls.push(["createEnvironmentVariable", input]);
4195 return Effect.succeed({
4196 id: "env-created",
4197 type: "environment-variable" as const,
4198 url: "https://api.prisma.test/v1/environment-variables/env-created",
4199 projectId: "project-1",
4200 branchId: "branch-main",
4201 class: "production" as const,
4202 key: "DATABASE_URL",
4203 valueKid: "kid-created",
4204 isManagedBySystem: false,
4205 createdAt: "2026-01-01T00:00:00Z",
4206 updatedAt: "2026-01-01T00:00:00Z",
4207 });
4208 },
4209 createAppDeployment: (appId: string, input: unknown) => {
4210 calls.push(["createAppDeployment", { appId, input }]);
4211 return Effect.succeed({
4212 id: "version-1",
4213 type: "deployment" as const,
4214 url: "https://api.prisma.test/v1/deployments/version-1",
4215 foundryVersionId: "foundry-1",
4216 uploadUrl: null,
4217 });
4218 },
4219 getDeployment: (id: string) => {
4220 calls.push(["getDeployment", id]);
4221 return Effect.succeed({
4222 id,
4223 type: "deployment" as const,
4224 serviceId: "service-1",
4225 url: "https://api.prisma.test/v1/deployments/version-1",
4226 foundryVersionId: "foundry-1",
4227 status: "new",
4228 previewDomain: "version-1.preview.prisma.build",
4229 createdAt: "2026-01-01T00:00:00Z",
4230 });
4231 },
4232 } as unknown as PrismaManagementClient;
4233
4234 return Effect.gen(function* () {
4235 const provider = yield* Compute.Provider;
4236 const output = yield* provider.reconcile({
4237 id: "App",
4238 fqn: "App",
4239 instanceId: "00000000000000000000000000000000",
4240 news: {
4241 project: "project-1",
4242 appName: "api",
4243 branchId: "branch-main",
4244 skipCodeUpload: true,
4245 start: false,
4246 skipPromote: true,
4247 envClass: "preview",
4248 },
4249 olds: undefined,
4250 output: {
4251 appId: "service-1",
4252 deploymentId: undefined,
4253 projectId: "project-1",
4254 appName: "api",
4255 regionId: "us-east-1",
4256 deploymentEndpointDomain: undefined,
4257 deploymentUrl: undefined,
4258 appEndpointDomain: "api.prisma.build",
4259 url: "https://api.prisma.build",
4260 promoted: false,
4261 previousDeploymentId: undefined,
4262 previousDeploymentAction: undefined,
4263 artifactHash: undefined,
4264 local: false,
4265 },
4266 session: undefined as never,
4267 bindings: [
4268 {
4269 sid: "Connection",
4270 data: {
4271 env: {
4272 DATABASE_URL: Redacted.make("postgres://bound"),
4273 SHARED_FLAG: "from-binding",
4274 },
4275 },
4276 },
4277 ],
4278 });
4279
4280 expect(output.deploymentId).toBe("version-1");
4281 expect(output.environmentKeys).toEqual(["DATABASE_URL", "SHARED_FLAG"]);
4282 expect(output.environmentClass).toBe("preview");
4283 expect(calls).toContainEqual([
4284 "createEnvironmentVariable",
4285 {
4286 projectId: "project-1",
4287 branchId: "branch-main",
4288 class: "preview",
4289 key: "DATABASE_URL",
4290 value: "postgres://bound",
4291 },
4292 ]);
4293 expect(calls).toContainEqual([
4294 "createEnvironmentVariable",
4295 {
4296 projectId: "project-1",
4297 branchId: "branch-main",
4298 class: "preview",
4299 key: "SHARED_FLAG",
4300 value: "from-binding",
4301 },
4302 ]);
4303 }).pipe(
4304 Effect.provide(computeProviderLive()),
4305 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client, "preview"))),
4306 Effect.provide(apiRoutedHttp(withDefaultBranch(client, "preview"))),
4307 Effect.provide(FetchHttpClient.layer),
4308 Effect.provide(PlatformServices),
4309 );
4310 },
4311 { tags: ["provider:prisma:branch"] },
4312 );
4313
4314 it.effect(
4315 "lets explicit Compute env override bindings and ignores deleted bindings",
4316 () => {
4317 const calls: Array<[string, unknown]> = [];
4318 const client = {
4319 getApp: (id: string) => {
4320 calls.push(["getApp", id]);
4321 return Effect.succeed({
4322 id,
4323 type: "app" as const,
4324 url: "https://api.prisma.test/v1/services/service-1",
4325 name: "api",
4326 region: { id: "us-east-1", name: "US East" },
4327 projectId: "project-1",
4328 branchId: "branch-main",
4329 latestDeploymentId: "version-old",
4330 appEndpointDomain: "api.prisma.build",
4331 createdAt: "2026-01-01T00:00:00Z",
4332 });
4333 },
4334 listEnvironmentVariables: (query: unknown) => {
4335 calls.push(["listEnvironmentVariables", query]);
4336 return Effect.succeed([]);
4337 },
4338 createEnvironmentVariable: (input: {
4339 key: string;
4340 projectId: string;
4341 class: "production" | "preview";
4342 }) => {
4343 calls.push(["createEnvironmentVariable", input]);
4344 return Effect.succeed({
4345 id: `env-${input.key.toLowerCase()}`,
4346 type: "environment-variable" as const,
4347 url: `https://api.prisma.test/v1/environment-variables/env-${input.key.toLowerCase()}`,
4348 projectId: input.projectId,
4349 branchId: null,
4350 class: input.class,
4351 key: input.key,
4352 valueKid: `kid-${input.key.toLowerCase()}`,
4353 isManagedBySystem: false,
4354 createdAt: "2026-01-01T00:00:00Z",
4355 updatedAt: "2026-01-01T00:00:00Z",
4356 });
4357 },
4358 createAppDeployment: (appId: string, input: unknown) => {
4359 calls.push(["createAppDeployment", { appId, input }]);
4360 return Effect.succeed({
4361 id: "version-1",
4362 type: "deployment" as const,
4363 url: "https://api.prisma.test/v1/deployments/version-1",
4364 foundryVersionId: "foundry-1",
4365 uploadUrl: "https://upload.prisma.test/version-1.tar.gz",
4366 });
4367 },
4368 getDeployment: (id: string) => {
4369 calls.push(["getDeployment", id]);
4370 return Effect.succeed({
4371 id,
4372 type: "deployment" as const,
4373 serviceId: "service-1",
4374 url: "https://api.prisma.test/v1/deployments/version-1",
4375 foundryVersionId: "foundry-1",
4376 status: "new",
4377 previewDomain: "version-1.preview.prisma.build",
4378 createdAt: "2026-01-01T00:00:00Z",
4379 });
4380 },
4381 } as unknown as PrismaManagementClient;
4382 return Effect.gen(function* () {
4383 const provider = yield* Compute.Provider;
4384 const deletedBinding = {
4385 sid: "RemovedConnection",
4386 action: "delete",
4387 data: { env: { DELETED_BINDING: "must-not-sync" } },
4388 } as ResourceBinding<Compute["Binding"]> & { action: "delete" };
4389 const output = yield* provider.reconcile({
4390 id: "App",
4391 fqn: "App",
4392 instanceId: "00000000000000000000000000000000",
4393 news: {
4394 project: "project-1",
4395 appName: "api",
4396 branchId: "branch-main",
4397 skipCodeUpload: true,
4398 start: false,
4399 skipPromote: true,
4400 env: { DATABASE_URL: Redacted.make("postgres://explicit"), BOUND_ONLY: null },
4401 },
4402 olds: undefined,
4403 output: {
4404 appId: "service-1",
4405 deploymentId: undefined,
4406 projectId: "project-1",
4407 appName: "api",
4408 regionId: "us-east-1",
4409 deploymentEndpointDomain: undefined,
4410 deploymentUrl: undefined,
4411 appEndpointDomain: "api.prisma.build",
4412 url: "https://api.prisma.build",
4413 promoted: false,
4414 previousDeploymentId: undefined,
4415 previousDeploymentAction: undefined,
4416 artifactHash: undefined,
4417 local: false,
4418 },
4419 session: undefined as never,
4420 bindings: [
4421 {
4422 sid: "Connection",
4423 data: {
4424 env: {
4425 DATABASE_URL: Redacted.make("postgres://bound"),
4426 BOUND_ONLY: "from-binding",
4427 ACTIVE_BINDING: "from-active-binding",
4428 },
4429 },
4430 },
4431 deletedBinding,
4432 ],
4433 });
4434
4435 expect(output.environmentKeys).toEqual(["ACTIVE_BINDING", "DATABASE_URL"]);
4436 expect(calls).toContainEqual([
4437 "createEnvironmentVariable",
4438 {
4439 projectId: "project-1",
4440 class: "production",
4441 key: "DATABASE_URL",
4442 value: "postgres://explicit",
4443 },
4444 ]);
4445 expect(calls).toContainEqual([
4446 "createEnvironmentVariable",
4447 {
4448 projectId: "project-1",
4449 class: "production",
4450 key: "ACTIVE_BINDING",
4451 value: "from-active-binding",
4452 },
4453 ]);
4454 expect(calls).not.toContainEqual([
4455 "createEnvironmentVariable",
4456 {
4457 projectId: "project-1",
4458 class: "production",
4459 key: "DELETED_BINDING",
4460 value: "must-not-sync",
4461 },
4462 ]);
4463 expect(calls).not.toContainEqual([
4464 "createEnvironmentVariable",
4465 {
4466 projectId: "project-1",
4467 class: "production",
4468 key: "BOUND_ONLY",
4469 value: "from-binding",
4470 },
4471 ]);
4472 }).pipe(
4473 Effect.provide(computeProviderLive()),
4474 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
4475 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
4476 Effect.provide(FetchHttpClient.layer),
4477 Effect.provide(PlatformServices),
4478 );
4479 },
4480 { tags: ["provider:prisma:branch"] },
4481 );
4482
4483 it.effect(
4484 "removes env vars from previously managed bindings",
4485 () => {
4486 const calls: Array<[string, unknown]> = [];
4487 const byKey = new Map([
4488 [
4489 "OLD_BOUND_FLAG",
4490 {
4491 id: "env-old-bound-flag",
4492 type: "environment-variable" as const,
4493 url: "https://api.prisma.test/v1/environment-variables/env-old-bound-flag",
4494 projectId: "project-1",
4495 branchId: null,
4496 class: "production" as const,
4497 key: "OLD_BOUND_FLAG",
4498 valueKid: "kid-old",
4499 isManagedBySystem: false,
4500 createdAt: "2026-01-01T00:00:00Z",
4501 updatedAt: "2026-01-01T00:00:00Z",
4502 },
4503 ],
4504 ]);
4505 const client = {
4506 getApp: (id: string) => {
4507 calls.push(["getApp", id]);
4508 return Effect.succeed({
4509 id,
4510 type: "app" as const,
4511 url: "https://api.prisma.test/v1/services/service-1",
4512 name: "api",
4513 region: { id: "us-east-1", name: "US East" },
4514 projectId: "project-1",
4515 branchId: "branch-main",
4516 latestDeploymentId: "version-old",
4517 appEndpointDomain: "api.prisma.build",
4518 createdAt: "2026-01-01T00:00:00Z",
4519 });
4520 },
4521 listEnvironmentVariables: (query: { key: string }) => {
4522 calls.push(["listEnvironmentVariables", query]);
4523 return Effect.succeed(byKey.get(query.key) ? [byKey.get(query.key)] : []);
4524 },
4525 createEnvironmentVariable: (input: unknown) => {
4526 calls.push(["createEnvironmentVariable", input]);
4527 return Effect.succeed({
4528 id: "env-created",
4529 type: "environment-variable" as const,
4530 url: "https://api.prisma.test/v1/environment-variables/env-created",
4531 projectId: "project-1",
4532 branchId: null,
4533 class: "production" as const,
4534 key: "DATABASE_URL",
4535 valueKid: "kid-created",
4536 isManagedBySystem: false,
4537 createdAt: "2026-01-01T00:00:00Z",
4538 updatedAt: "2026-01-01T00:00:00Z",
4539 });
4540 },
4541 deleteEnvironmentVariable: (id: string) => {
4542 calls.push(["deleteEnvironmentVariable", id]);
4543 return Effect.void;
4544 },
4545 createAppDeployment: (appId: string, input: unknown) => {
4546 calls.push(["createAppDeployment", { appId, input }]);
4547 return Effect.succeed({
4548 id: "version-1",
4549 type: "deployment" as const,
4550 url: "https://api.prisma.test/v1/deployments/version-1",
4551 foundryVersionId: "foundry-1",
4552 uploadUrl: null,
4553 });
4554 },
4555 getDeployment: (id: string) => {
4556 calls.push(["getDeployment", id]);
4557 return Effect.succeed({
4558 id,
4559 type: "deployment" as const,
4560 serviceId: "service-1",
4561 url: "https://api.prisma.test/v1/deployments/version-1",
4562 foundryVersionId: "foundry-1",
4563 status: "new",
4564 previewDomain: "version-1.preview.prisma.build",
4565 createdAt: "2026-01-01T00:00:00Z",
4566 });
4567 },
4568 } as unknown as PrismaManagementClient;
4569
4570 return Effect.gen(function* () {
4571 const provider = yield* Compute.Provider;
4572 const output = yield* provider.reconcile({
4573 id: "App",
4574 fqn: "App",
4575 instanceId: "00000000000000000000000000000000",
4576 news: {
4577 project: "project-1",
4578 appName: "api",
4579 branchId: "branch-main",
4580 skipCodeUpload: true,
4581 start: false,
4582 skipPromote: true,
4583 },
4584 olds: undefined,
4585 output: {
4586 appId: "service-1",
4587 deploymentId: undefined,
4588 projectId: "project-1",
4589 appName: "api",
4590 regionId: "us-east-1",
4591 deploymentEndpointDomain: undefined,
4592 deploymentUrl: undefined,
4593 appEndpointDomain: "api.prisma.build",
4594 url: "https://api.prisma.build",
4595 promoted: false,
4596 previousDeploymentId: undefined,
4597 previousDeploymentAction: undefined,
4598 environmentKeys: ["DATABASE_URL", "OLD_BOUND_FLAG"],
4599 environmentVariableIds: { OLD_BOUND_FLAG: "env-old-bound-flag" },
4600 artifactHash: undefined,
4601 local: false,
4602 },
4603 session: undefined as never,
4604 bindings: [
4605 {
4606 sid: "Connection",
4607 data: { env: { DATABASE_URL: Redacted.make("postgres://still-bound") } },
4608 },
4609 ],
4610 });
4611
4612 expect(output.environmentKeys).toEqual(["DATABASE_URL"]);
4613 expect(calls).toContainEqual(["deleteEnvironmentVariable", "env-old-bound-flag"]);
4614 }).pipe(
4615 Effect.provide(computeProviderLive()),
4616 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
4617 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
4618 Effect.provide(FetchHttpClient.layer),
4619 Effect.provide(PlatformServices),
4620 );
4621 },
4622 { tags: ["provider:prisma:branch"] },
4623 );
4624
4625 it.effect(
4626 "deletes persisted env keys even when old props contain null tombstones",
4627 () => {
4628 const calls: Array<[string, unknown?]> = [];
4629 const staleVariable = {
4630 id: "env-stale-flag",
4631 type: "environment-variable" as const,
4632 url: "https://api.prisma.test/v1/environment-variables/env-stale-flag",
4633 projectId: "project-1",
4634 branchId: null,
4635 class: "production" as const,
4636 key: "STALE_FLAG",
4637 valueKid: "kid-stale",
4638 isManagedBySystem: false,
4639 createdAt: "2026-01-01T00:00:00Z",
4640 updatedAt: "2026-01-01T00:00:00Z",
4641 };
4642 const client = {
4643 listEnvironmentVariables: (query: { key: string }) => {
4644 calls.push(["listEnvironmentVariables", query]);
4645 return Effect.succeed(query.key === "STALE_FLAG" ? [staleVariable] : []);
4646 },
4647 deleteEnvironmentVariable: (id: string) => {
4648 calls.push(["deleteEnvironmentVariable", id]);
4649 return Effect.void;
4650 },
4651 listAppDeployments: (appId: string, query: unknown) => {
4652 calls.push(["listAppDeployments", { appId, query }]);
4653 return Effect.succeed([]);
4654 },
4655 deleteApp: (id: string) => {
4656 calls.push(["deleteApp", id]);
4657 return Effect.void;
4658 },
4659 } as unknown as PrismaManagementClient;
4660
4661 return Effect.gen(function* () {
4662 const provider = yield* Compute.Provider;
4663 yield* provider.delete({
4664 id: "App",
4665 fqn: "App",
4666 instanceId: "00000000000000000000000000000000",
4667 olds: { project: "project-1", appName: "api", env: { STALE_FLAG: null } },
4668 output: {
4669 appId: "service-1",
4670 deploymentId: undefined,
4671 projectId: "project-1",
4672 appName: "api",
4673 regionId: "us-east-1",
4674 deploymentEndpointDomain: undefined,
4675 deploymentUrl: undefined,
4676 appEndpointDomain: "api.prisma.build",
4677 url: "https://api.prisma.build",
4678 promoted: false,
4679 previousDeploymentId: undefined,
4680 previousDeploymentAction: undefined,
4681 environmentKeys: ["STALE_FLAG"],
4682 environmentVariableIds: { STALE_FLAG: "env-stale-flag" },
4683 environmentClass: "production",
4684 artifactHash: undefined,
4685 local: false,
4686 },
4687 session: undefined as never,
4688 bindings: [],
4689 });
4690
4691 expect(calls).toEqual([
4692 [
4693 "listEnvironmentVariables",
4694 { projectId: "project-1", class: "production", key: "STALE_FLAG", limit: "100" },
4695 ],
4696 ["deleteEnvironmentVariable", "env-stale-flag"],
4697 ["deleteApp", "service-1"],
4698 ]);
4699 }).pipe(
4700 Effect.provide(computeProviderLive()),
4701 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
4702 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
4703 );
4704 },
4705 { tags: ["provider:prisma:branch"] },
4706 );
4707
4708 it.effect(
4709 "does not expose redacted env values in Compute outputs",
4710 () => {
4711 const calls: Array<[string, unknown]> = [];
4712 const client = {
4713 getApp: (id: string) => {
4714 calls.push(["getApp", id]);
4715 return Effect.succeed({
4716 id,
4717 type: "app" as const,
4718 url: "https://api.prisma.test/v1/services/service-1",
4719 name: "api",
4720 region: { id: "us-east-1", name: "US East" },
4721 projectId: "project-1",
4722 branchId: "branch-main",
4723 latestDeploymentId: "version-old",
4724 appEndpointDomain: "api.prisma.build",
4725 createdAt: "2026-01-01T00:00:00Z",
4726 });
4727 },
4728 listEnvironmentVariables: (query: unknown) => {
4729 calls.push(["listEnvironmentVariables", query]);
4730 return Effect.succeed([]);
4731 },
4732 createEnvironmentVariable: (input: unknown) => {
4733 calls.push(["createEnvironmentVariable", input]);
4734 return Effect.succeed({
4735 id: "env-secret",
4736 type: "environment-variable" as const,
4737 url: "https://api.prisma.test/v1/environment-variables/env-secret",
4738 projectId: "project-1",
4739 branchId: null,
4740 class: "production" as const,
4741 key: "SECRET",
4742 valueKid: "kid-secret",
4743 isManagedBySystem: false,
4744 createdAt: "2026-01-01T00:00:00Z",
4745 updatedAt: "2026-01-01T00:00:00Z",
4746 });
4747 },
4748 createAppDeployment: (appId: string, input: unknown) => {
4749 calls.push(["createAppDeployment", { appId, input }]);
4750 return Effect.succeed({
4751 id: "version-new",
4752 type: "deployment" as const,
4753 url: "https://api.prisma.test/v1/deployments/version-new",
4754 foundryVersionId: "foundry-new",
4755 uploadUrl: null,
4756 });
4757 },
4758 getDeployment: (id: string) => {
4759 calls.push(["getDeployment", id]);
4760 return Effect.succeed({
4761 id,
4762 type: "deployment" as const,
4763 serviceId: "service-1",
4764 url: `https://api.prisma.test/v1/deployments/${id}`,
4765 foundryVersionId: "foundry-new",
4766 status: "new",
4767 previewDomain: "version-new.preview.prisma.build",
4768 createdAt: "2026-01-01T00:00:00Z",
4769 });
4770 },
4771 } as unknown as PrismaManagementClient;
4772
4773 return Effect.gen(function* () {
4774 const provider = yield* Compute.Provider;
4775 const output = yield* provider.reconcile({
4776 id: "App",
4777 fqn: "App",
4778 instanceId: "00000000000000000000000000000000",
4779 news: {
4780 project: "project-1",
4781 appName: "api",
4782 branchId: "branch-main",
4783 skipCodeUpload: true,
4784 start: false,
4785 skipPromote: true,
4786 env: { SECRET: Redacted.make("super-secret") },
4787 },
4788 olds: undefined,
4789 output: {
4790 appId: "service-1",
4791 deploymentId: "version-old",
4792 projectId: "project-1",
4793 appName: "api",
4794 regionId: "us-east-1",
4795 deploymentEndpointDomain: "version-old.preview.prisma.build",
4796 deploymentUrl: "https://version-old.preview.prisma.build",
4797 appEndpointDomain: "api.prisma.build",
4798 url: "https://api.prisma.build",
4799 promoted: true,
4800 previousDeploymentId: undefined,
4801 previousDeploymentAction: undefined,
4802 artifactHash: Redacted.make("old-hash"),
4803 local: false,
4804 },
4805 session: undefined as never,
4806 bindings: [],
4807 });
4808
4809 expect(output.deploymentId).toBe("version-new");
4810 expect(Redacted.value(output.artifactHash!)).toMatch(/^[a-f0-9]{64}$/);
4811 expect(JSON.stringify(output)).not.toContain("super-secret");
4812 expect(calls).toContainEqual([
4813 "createEnvironmentVariable",
4814 { projectId: "project-1", class: "production", key: "SECRET", value: "super-secret" },
4815 ]);
4816 }).pipe(
4817 Effect.provide(computeProviderLive()),
4818 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
4819 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
4820 Effect.provide(FetchHttpClient.layer),
4821 Effect.provide(PlatformServices),
4822 );
4823 },
4824 { tags: ["provider:prisma:branch"] },
4825 );
4826
4827 it.effect(
4828 "runs a build command and uploads the built archive",
4829 () => {
4830 const calls: Array<[string, unknown]> = [];
4831 let latestDeploymentId: string | null = null;
4832 let uploaded:
4833 | { url: string; contentType: string | undefined; bytes: Uint8Array }
4834 | undefined;
4835 const client = {
4836 listApps: (projectId: string, query: unknown) => {
4837 calls.push(["listApps", { projectId, query }]);
4838 return Effect.succeed([]);
4839 },
4840 createApp: (projectId: string, input: unknown) => {
4841 calls.push(["createApp", { projectId, input }]);
4842 return Effect.succeed({
4843 id: "service-1",
4844 type: "app" as const,
4845 url: "https://api.prisma.test/v1/services/service-1",
4846 name: "api",
4847 region: { id: "us-east-1", name: "US East" },
4848 projectId,
4849 branchId: "branch-main",
4850 latestDeploymentId,
4851 appEndpointDomain: "api.prisma.build",
4852 createdAt: "2026-01-01T00:00:00Z",
4853 });
4854 },
4855 updateApp: (id: string, input: unknown) => {
4856 calls.push(["updateApp", { id, input }]);
4857 return Effect.succeed({
4858 id,
4859 type: "app" as const,
4860 url: "https://api.prisma.test/v1/services/service-1",
4861 name: "api",
4862 region: { id: "us-east-1", name: "US East" },
4863 projectId: "project-1",
4864 branchId: "branch-main",
4865 latestDeploymentId,
4866 appEndpointDomain: "api.prisma.build",
4867 createdAt: "2026-01-01T00:00:00Z",
4868 });
4869 },
4870 getApp: (id: string) =>
4871 Effect.succeed({
4872 id,
4873 type: "app" as const,
4874 url: "https://api.prisma.test/v1/services/service-1",
4875 name: "api",
4876 region: { id: "us-east-1", name: "US East" },
4877 projectId: "project-1",
4878 branchId: "branch-main",
4879 latestDeploymentId,
4880 appEndpointDomain: "api.prisma.build",
4881 createdAt: "2026-01-01T00:00:00Z",
4882 }),
4883 listEnvironmentVariables: () => Effect.succeed([]),
4884 createAppDeployment: (appId: string, input: unknown) => {
4885 calls.push(["createAppDeployment", { appId, input }]);
4886 return Effect.succeed({
4887 id: "version-1",
4888 type: "deployment" as const,
4889 url: "https://api.prisma.test/v1/deployments/version-1",
4890 foundryVersionId: "foundry-1",
4891 uploadUrl: "https://upload.prisma.test/artifact.tar.gz",
4892 });
4893 },
4894 getDeployment: (id: string) => {
4895 calls.push(["getDeployment", id]);
4896 return Effect.succeed({
4897 id,
4898 type: "deployment" as const,
4899 serviceId: "service-1",
4900 url: "https://api.prisma.test/v1/deployments/version-1",
4901 foundryVersionId: "foundry-1",
4902 status: "running",
4903 previewDomain: "version-1.preview.prisma.build",
4904 createdAt: "2026-01-01T00:00:00Z",
4905 });
4906 },
4907 promoteApp: (appId: string, { deploymentId }: { deploymentId: string }) => {
4908 calls.push(["promoteApp", { appId, deploymentId }]);
4909 latestDeploymentId = deploymentId;
4910 return Effect.succeed({ appEndpointDomain: "api.prisma.build", reassignedDomains: 0 });
4911 },
4912 } as unknown as PrismaManagementClient;
4913 const http = HttpClient.make((request) =>
4914 Effect.gen(function* () {
4915 const body = request.body as HttpBody.HttpBody;
4916 uploaded = {
4917 url: request.url,
4918 contentType: httpBodyContentType(body),
4919 bytes: yield* readHttpBodyBytes(body),
4920 };
4921 return HttpClientResponse.fromWeb(request, new Response(null));
4922 }),
4923 );
4924
4925 return Effect.gen(function* () {
4926 const fs = yield* FileSystem.FileSystem;
4927 const path = yield* Path.Path;
4928 const root = yield* fs.makeTempDirectory({ prefix: "alchemy-prisma-compute-build-" });
4929 yield* fs.writeFileString(
4930 path.join(root, "build.sh"),
4931 [
4932 "mkdir -p dist",
4933 'printf \'console.log("%s");\' "$BUILD_GREETING" > dist/server.js',
4934 "",
4935 ].join("\n"),
4936 );
4937
4938 const provider = yield* Compute.Provider;
4939 const output = yield* provider.reconcile({
4940 id: "App",
4941 fqn: "App",
4942 instanceId: "00000000000000000000000000000000",
4943 news: {
4944 project: "project-1",
4945 appName: "api",
4946 path: root,
4947 port: 4567,
4948 verifyUrl: false,
4949 build: {
4950 command: "sh build.sh",
4951 cwd: root,
4952 outdir: "dist",
4953 entrypoint: "server.js",
4954 env: { BUILD_GREETING: "hello-build" },
4955 },
4956 },
4957 olds: undefined,
4958 output: undefined,
4959 session: undefined as never,
4960 bindings: [],
4961 });
4962
4963 expect(output.deploymentId).toBe("version-1");
4964 expect(uploaded?.url).toBe("https://upload.prisma.test/artifact.tar.gz");
4965 expect(uploaded?.contentType).toBe("application/gzip");
4966 const tarText = new TextDecoder().decode(
4967 yield* Effect.sync(() => gunzipSync(uploaded!.bytes)),
4968 );
4969 expect(tarText).toContain("compute.manifest.json");
4970 expect(tarText).toContain("bundle/server.js");
4971 expect(tarText).toContain("hello-build");
4972 expect(calls).toContainEqual([
4973 "createAppDeployment",
4974 {
4975 appId: "service-1",
4976 input: { portMapping: { http: 4567 }, skipCodeUpload: undefined },
4977 },
4978 ]);
4979 }).pipe(
4980 Effect.provide(computeProviderLive()),
4981 Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
4982 Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
4983 Effect.provide(Layer.succeed(HttpClient.HttpClient, http)),
4984 Effect.provide(PlatformServices),
4985 );
4986 },
4987 { tags: ["provider:prisma:branch"] },
4988 );
4989
4990 it.effect(
4991 "auto-builds a Bun app before uploading",
4992 () => {
4993 const calls: Array<[string, unknown]> = [];
4994 let uploaded:
4995 | { url: string; contentType: string | undefined; bytes: Uint8Array }
4996 | undefined;
4997 const client = {
4998 listApps: (projectId: string, query: unknown) => {
4999 calls.push(["listApps", { projectId, query }]);
5000 return Effect.succeed([]);
Showing first 5,000 of 6,936 lines. View raw