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

main
ts 2,796 lines 99.5 KB
Raw
1 import { Retry } from "@distilled.cloud/prisma";
2 import {
3 type GetServicesResponse,
4 type GetEnvironmentVariablesResponse,
5 type GetProjectBranchesResponse,
6 deleteEnvironmentVariable,
7 getServices,
8 getService,
9 getBranch,
10 getEnvironmentVariables,
11 getProjectBranches,
12 updateService,
13 updateEnvironmentVariable,
14 createService,
15 createServiceDeployment,
16 createServiceRollback,
17 createEnvironmentVariable,
18 } from "@distilled.cloud/prisma/management";
19 import { Unowned } from "alchemy/AdoptPolicy";
20 import { AlchemyContext } from "alchemy/AlchemyContext";
21 import * as Bundle from "alchemy/Bundle/Bundle";
22 import { findCwdForBundle } from "alchemy/Bundle/TempRoot";
23 import { isResolved } from "alchemy/Diff";
24 import { HttpServer, type HttpEffect } from "alchemy/Http";
25 import type { InputProps } from "alchemy/Input";
26 import * as ProviderLayer from "alchemy/Local/ProviderLayer";
27 import * as Output from "alchemy/Output";
28 import { createPhysicalName } from "alchemy/PhysicalName";
29 import { Platform, type Main, type PlatformProps } from "alchemy/Platform";
30 import * as Provider from "alchemy/Provider";
31 import { Resource, type ResourceBinding } from "alchemy/Resource";
32 import type { ProcessContext, ProcessServices } from "alchemy/Runtime/Process";
33 import { RuntimeContext } from "alchemy/RuntimeContext";
34 import { Stack } from "alchemy/Stack";
35 import { logChildLine } from "alchemy/Util/LogRecord";
36 import { sha256Object } from "alchemy/Util/sha256";
37 import * as Data from "effect/Data";
38 import * as Duration from "effect/Duration";
39 import * as Effect from "effect/Effect";
40 import * as Exit from "effect/Exit";
41 import * as FileSystem from "effect/FileSystem";
42 import * as FetchHttpClient from "effect/http/FetchHttpClient";
43 import * as HttpClient from "effect/http/HttpClient";
44 import * as HttpClientRequest from "effect/http/HttpClientRequest";
45 import type { HttpClientResponse } from "effect/http/HttpClientResponse";
46 import * as Option from "effect/Option";
47 import * as Path from "effect/Path";
48 import * as ChildProcess from "effect/process/ChildProcess";
49 import type { ChildProcessHandle } from "effect/process/ChildProcessSpawner";
50 import * as Redacted from "effect/Redacted";
51 import * as Result from "effect/Result";
52 import * as Schedule from "effect/Schedule";
53 import * as Stream from "effect/Stream";
54 import type * as rolldown from "rolldown";
55 import { createComputeArchive, normalizeEntrypoint } from "./ComputeArchive.ts";
56 import {
57 runBuildCommand,
58 runComputeAutoBuild,
59 runComputeStaticBuild,
60 type ComputeAutoBuildFramework,
61 } from "./ComputeBuild.ts";
62 import {
63 destroyApp,
64 destroyDeployment,
65 toDeploymentUrl,
66 waitForDeploymentStatus,
67 } from "./ComputeLifecycle.ts";
68 import { readUploadArtifact, uploadArtifact } from "./Deployment.ts";
69 import { ensureAppImmutableIdentity } from "./internal/AppIdentity.ts";
70 import { promoteAppObserved, waitForAppDeploymentTarget } from "./internal/AppPromotion.ts";
71 import { normalizeBundleFilePath } from "./internal/BundlePaths.ts";
72 import { aggregateCleanupFailure } from "./internal/CleanupFailure.ts";
73 import {
74 startDeploymentIdempotent,
75 stopDeploymentIdempotent,
76 } from "./internal/DeploymentActions.ts";
77 import { ensureDeploymentMembership } from "./internal/DeploymentIdentity.ts";
78 import { observeDeployment } from "./internal/DeploymentObserve.ts";
79 import type {
80 ObservedApp,
81 ObservedDeployment,
82 ObservedEnvironmentVariable,
83 } from "./internal/Observed.ts";
84 import { PrismaPaginationError } from "./internal/Pagination.ts";
85 import {
86 concreteIdsChanged,
87 isInputObject,
88 isPrismaDevId,
89 resolveProjectId,
90 unresolvedProjectIdOf,
91 } from "./internal/Refs.ts";
92 import { tailDeploymentLogs } from "./PrismaLogs.ts";
93 import type { Project } from "./Project.ts";
94 import type { Providers } from "./Providers.ts";
95 import type { PrismaRegionId } from "./Types.ts";
96
97 export class ComputeConflict extends Data.TaggedError("ComputeConflict")<{
98 readonly message: string;
99 readonly cause?: unknown;
100 }> {}
101
102 export class ComputeInvalidProps extends Data.TaggedError("ComputeInvalidProps")<{
103 readonly message: string;
104 readonly cause?: unknown;
105 }> {}
106
107 export class ComputeNotReady extends Data.TaggedError("ComputeNotReady")<{
108 readonly message: string;
109 readonly cause?: unknown;
110 }> {}
111
112 export class ComputeOperationFailed extends Data.TaggedError("ComputeOperationFailed")<{
113 readonly message: string;
114 readonly cause?: unknown;
115 }> {}
116
117 export class ComputeUnexpectedResponse extends Data.TaggedError("ComputeUnexpectedResponse")<{
118 readonly message: string;
119 readonly cause?: unknown;
120 }> {}
121
122 const ComputeTypeId = "Prisma.Compute" as const;
123 type ComputeTypeId = typeof ComputeTypeId;
124
125 export interface ComputeCommandBuild {
126 /**
127 * Shell command that creates the deployable output directory.
128 */
129 command: string;
130 /**
131 * Working directory for the build command.
132 *
133 * @default path
134 */
135 cwd?: string;
136 /**
137 * Build output directory, relative to `cwd`.
138 */
139 outdir: string;
140 /**
141 * Entrypoint inside `outdir`.
142 */
143 entrypoint?: string;
144 /**
145 * Environment variables supplied to the build command.
146 * Ambient `PRISMA_SERVICE_TOKEN` and `PRISMA_API_TOKEN` credentials are not
147 * inherited; include one here explicitly only when the application build
148 * genuinely needs Prisma Management API access.
149 *
150 * Plain strings are persisted in Alchemy state. Wrap secrets with
151 * `Redacted.make(secret)`; Prisma-side encryption does not protect a value
152 * already stored in Alchemy state.
153 *
154 * ```typescript
155 * env: { NPM_TOKEN: Redacted.make(process.env.NPM_TOKEN!) }
156 * ```
157 */
158 env?: Record<string, string | Redacted.Redacted<string> | undefined>;
159 /**
160 * Maximum bytes retained from each build output stream.
161 *
162 * @default 1048576 (1 MiB)
163 */
164 outputLimitBytes?: number;
165 /**
166 * Maximum wall-clock time for the build command.
167 *
168 * @default 900 (15 minutes)
169 */
170 timeoutSeconds?: number;
171 }
172
173 export interface ComputeAutoBuild {
174 /**
175 * Auto-detect a Prisma Compute build strategy, or force one framework.
176 */
177 type: "auto";
178 /**
179 * Framework build strategy.
180 *
181 * @default "auto"
182 */
183 framework?: ComputeAutoBuildFramework;
184 /**
185 * Environment variables supplied to the build command.
186 * Ambient `PRISMA_SERVICE_TOKEN` and `PRISMA_API_TOKEN` credentials are not
187 * inherited; include one here explicitly only when the application build
188 * genuinely needs Prisma Management API access.
189 *
190 * Plain strings are persisted in Alchemy state. Wrap secrets with
191 * `Redacted.make(secret)`.
192 *
193 * ```typescript
194 * env: { NPM_TOKEN: Redacted.make(process.env.NPM_TOKEN!) }
195 * ```
196 */
197 env?: Record<string, string | Redacted.Redacted<string> | undefined>;
198 /**
199 * Maximum bytes retained from each framework build output stream.
200 *
201 * @default 1048576 (1 MiB)
202 */
203 outputLimitBytes?: number;
204 /**
205 * Maximum wall-clock time for the framework build command.
206 *
207 * @default 900 (15 minutes)
208 */
209 timeoutSeconds?: number;
210 }
211
212 export interface ComputeStaticBuild {
213 /**
214 * Build a static site and package it with a production HTTP server.
215 */
216 type: "static";
217 /**
218 * Static output directory, relative to `cwd`.
219 */
220 outdir: string;
221 /**
222 * Optional shell command that creates the static output directory. Omit it
223 * when `outdir` already contains the files to deploy.
224 */
225 command?: string;
226 /**
227 * Working directory for the build command and `outdir`.
228 *
229 * @default path
230 */
231 cwd?: string;
232 /**
233 * HTML file served at the root and for SPA fallbacks.
234 *
235 * @default "index.html"
236 */
237 indexPage?: string;
238 /**
239 * Serve the index page when no static file matches the request.
240 *
241 * @default false
242 */
243 spa?: boolean;
244 /**
245 * Environment variables supplied to the build command.
246 * Ambient `PRISMA_SERVICE_TOKEN` and `PRISMA_API_TOKEN` credentials are not
247 * inherited; include one here explicitly only when the application build
248 * genuinely needs Prisma Management API access.
249 *
250 * Plain strings are persisted in Alchemy state. Wrap secrets with
251 * `Redacted.make(secret)`.
252 *
253 * ```typescript
254 * env: { NPM_TOKEN: Redacted.make(process.env.NPM_TOKEN!) }
255 * ```
256 */
257 env?: Record<string, string | Redacted.Redacted<string> | undefined>;
258 /**
259 * Maximum bytes retained from each build output stream.
260 *
261 * @default 1048576 (1 MiB)
262 */
263 outputLimitBytes?: number;
264 /**
265 * Maximum wall-clock time for the build command.
266 *
267 * @default 900 (15 minutes)
268 */
269 timeoutSeconds?: number;
270 }
271
272 export type ComputeBuild = ComputeCommandBuild | ComputeAutoBuild | ComputeStaticBuild;
273
274 export interface ComputeBundleOptions {
275 /**
276 * Rolldown input options for effect-native Compute bundles.
277 */
278 input?: Partial<rolldown.InputOptions>;
279 /**
280 * Rolldown output options for effect-native Compute bundles.
281 */
282 output?: Partial<rolldown.OutputOptions>;
283 /**
284 * Additional Alchemy bundle options for effect-native Compute bundles.
285 */
286 extra?: Bundle.BundleExtraOptions;
287 }
288
289 export interface ComputeDev {
290 /**
291 * Local command to run during `alchemy dev`.
292 */
293 command?: string;
294 /**
295 * Working directory for the dev command.
296 *
297 * @default path
298 */
299 cwd?: string;
300 /**
301 * Local development port.
302 */
303 port?: number;
304 /**
305 * Explicit local URL to expose in the resource output.
306 */
307 url?: string;
308 /**
309 * Extra environment variables for the dev command.
310 * Plain strings are persisted in Alchemy state. Wrap secrets with
311 * `Redacted.make(secret)`.
312 */
313 env?: Record<string, string | Redacted.Redacted<string> | undefined>;
314 }
315
316 export interface ComputeHealthCheck {
317 /**
318 * Absolute application path to probe after the deployment starts and after
319 * promotion.
320 *
321 * @example "/api/health"
322 */
323 path: string;
324 /**
325 * Exact HTTP status codes that indicate readiness. When omitted, any 2xx
326 * response is healthy.
327 *
328 * @default Any status from 200 through 299
329 */
330 statusCodes?: readonly number[];
331 }
332
333 export interface ComputeProps extends PlatformProps {
334 /**
335 * Project ID or `project.projectId` output that owns the App.
336 */
337 project: string | Project;
338 /**
339 * App display name. If omitted, Alchemy generates a stable physical name.
340 */
341 appName?: string;
342 /**
343 * Region where the App is placed.
344 *
345 * @default The project's default region, falling back to "us-east-1"
346 */
347 regionId?: PrismaRegionId;
348 /**
349 * Branch ID to attach the App to. Mutually exclusive with branchGitName.
350 * If both branch fields are omitted, Alchemy attaches to the project's
351 * current default branch.
352 */
353 branchId?: string;
354 /**
355 * Branch git name to attach the App to. Mutually exclusive with branchId.
356 *
357 * @default The project's current default branch
358 */
359 branchGitName?: string;
360 /**
361 * Application directory used for pre-built artifacts and build commands.
362 *
363 * @default "."
364 */
365 path?: string;
366 /**
367 * Additional files or directories to exclude from path deployments. Static
368 * build patterns are relative to the configured output directory; other
369 * patterns are artifact-relative. `*` and `**` wildcards are supported;
370 * absolute paths, parent segments, and negated patterns are rejected.
371 * `.env*`, `.git`, and `.alchemy` are always excluded. Static index pages
372 * must remain present after exclusions.
373 */
374 archiveIgnore?: readonly string[];
375 /**
376 * Entrypoint relative to the deployed artifact directory.
377 * If omitted, Alchemy reads `package.json#main`.
378 */
379 entrypoint?: string;
380 /**
381 * Entry module for an effect-native Compute app.
382 *
383 * This is required when you pass an inline Effect implementation to
384 * `Prisma.Compute`, and ignored for external path deployments.
385 */
386 main?: string;
387 /**
388 * Exported symbol inside `main` for effect-native Compute apps.
389 *
390 * @default "default"
391 */
392 handler?: string;
393 /**
394 * Bundler options for effect-native Compute apps.
395 */
396 bundle?: ComputeBundleOptions;
397 /**
398 * Effect-native runtime exports populated by the Platform constructor.
399 *
400 * @internal
401 */
402 exports?: string[] | Record<string, unknown>;
403 /**
404 * Build command and output directory. Set to `"auto"` or `{ type: "auto" }`
405 * to use Prisma Compute-style framework detection for Next.js, Nuxt, Astro,
406 * TanStack Start, Vite, or Bun. Set to `false` to upload `path` as a
407 * pre-built artifact.
408 */
409 build?: ComputeBuild | false | "auto";
410 /**
411 * Path to a pre-created `tar.gz` artifact file. When supplied, Alchemy reads
412 * and uploads it directly.
413 */
414 artifactPath?: string;
415 /**
416 * HTTP port exposed by the application.
417 *
418 * @default 8080
419 */
420 port?: number;
421 /**
422 * Runtime environment variables to sync through Prisma's environment
423 * variable API before creating a new deployment. Set a value to `null`
424 * to delete that variable.
425 *
426 * Plain strings are persisted in Alchemy state. For secrets, use
427 * `Redacted.make(secret)`; encryption in the Prisma Management API does not
428 * protect a plain value already recorded in Alchemy state.
429 *
430 * The Management API exposes neither an idempotency key nor ownership
431 * metadata for environment variables, and reads return redacted values. If
432 * a process crashes after Prisma commits a create but before Alchemy saves
433 * its returned ID, the next deploy safely refuses to claim that natural-key
434 * match. Use standalone `Prisma.EnvironmentVariable` resources for critical
435 * keys that need independent lifecycle management and explicit adoption.
436 *
437 * ```typescript
438 * env: {
439 * LOG_LEVEL: "info",
440 * API_TOKEN: Redacted.make(process.env.API_TOKEN!),
441 * }
442 * ```
443 */
444 env?: Record<string, string | Redacted.Redacted<string> | null | undefined>;
445 /**
446 * Prisma environment variable class used by the `env` convenience property.
447 *
448 * @default "production"
449 */
450 envClass?: "production" | "preview";
451 /**
452 * Create the next deployment by reusing the previous code artifact.
453 *
454 * @default false
455 */
456 skipCodeUpload?: boolean;
457 /**
458 * Start the created/reused deployment.
459 * Set `skipPromote: true` when disabling start.
460 *
461 * @default true
462 */
463 start?: boolean;
464 /**
465 * Do not promote the deployment to the stable App endpoint.
466 *
467 * @default false
468 */
469 skipPromote?: boolean;
470 /**
471 * Delete the previously promoted deployment after the new one is promoted.
472 *
473 * @default false
474 */
475 destroyOldDeployment?: boolean;
476 /**
477 * Poll timeout while waiting for start/stop.
478 *
479 * @default 120
480 */
481 timeoutSeconds?: number;
482 /**
483 * Poll interval while waiting for start/stop.
484 *
485 * @default 1000
486 */
487 pollIntervalMs?: number;
488 /**
489 * Verify that Prisma's public preview/App URL has reached the edge after
490 * the Management API reports the deployment as running.
491 *
492 * @default true
493 */
494 verifyUrl?: boolean;
495 /**
496 * Optional application-level health check. Without this option, URL
497 * verification only waits for Prisma edge routing to stop returning its
498 * platform-level service-not-found response. With this option, Alchemy also
499 * sends a public GET to the preview URL before promotion and to the stable
500 * App URL afterward. Redirects are not followed. Each probe phase gets the
501 * full `urlReadinessTimeoutSeconds` budget.
502 *
503 * Health checks run only during cloud deployment, not `alchemy dev`, and
504 * cannot be combined with `verifyUrl: false` or `start: false`.
505 */
506 healthCheck?: ComputeHealthCheck;
507 /**
508 * Maximum time to wait for Prisma's public URL to stop returning the
509 * platform-level "Service not found" page.
510 *
511 * @default 60
512 */
513 urlReadinessTimeoutSeconds?: number;
514 /**
515 * Local development behavior for `alchemy dev`.
516 */
517 dev?: ComputeDev;
518 }
519
520 export interface Compute extends Resource<
521 ComputeTypeId,
522 ComputeProps,
523 {
524 /**
525 * Prisma App ID.
526 */
527 appId: string;
528 /**
529 * Prisma deployment ID created for the current deployment.
530 */
531 deploymentId: string | undefined;
532 /**
533 * Project ID that owns the app.
534 */
535 projectId: string;
536 /**
537 * App display name.
538 */
539 appName: string;
540 /**
541 * Region ID where the App is placed.
542 */
543 regionId: string;
544 /**
545 * Preview endpoint domain for the deployment.
546 */
547 deploymentEndpointDomain: string | undefined;
548 /**
549 * HTTPS URL for the deployment endpoint.
550 */
551 deploymentUrl: string | undefined;
552 /**
553 * Stable App endpoint domain after promotion.
554 */
555 appEndpointDomain: string | undefined;
556 /**
557 * Preferred URL for the app, local in dev or stable/preview in deploys.
558 */
559 url: string | undefined;
560 /**
561 * Whether the current deployment was promoted to the stable endpoint.
562 */
563 promoted: boolean;
564 /**
565 * Previously promoted deployment ID observed before deploy.
566 */
567 previousDeploymentId: string | null | undefined;
568 /**
569 * Action taken for the previous deployment.
570 */
571 previousDeploymentAction: "stopped" | "destroyed" | "still-active" | null | undefined;
572 /** Stable App endpoint readiness observed after promotion. */
573 readinessStatus?: "ready" | "pending" | "skipped";
574 /** Old deployment cleanup that will be retried before another generation. */
575 pendingDeploymentCleanup?: {
576 deploymentId: string;
577 action: "stop" | "destroy";
578 };
579 /**
580 * Environment variable keys managed by this Compute resource.
581 *
582 * This includes explicit `env` props and env vars added by bindings.
583 */
584 environmentKeys?: string[];
585 /**
586 * Environment variable IDs created by this Compute resource, keyed by
587 * variable name. IDs are the ownership boundary for shared branch/project
588 * environment-variable namespaces.
589 */
590 environmentVariableIds?: Record<string, string>;
591 /**
592 * Prisma environment class used for the managed environment variable keys.
593 */
594 environmentClass?: "production" | "preview";
595 /**
596 * Branch ID used for managed preview branch environment overrides, or null
597 * for project-level environment templates.
598 */
599 environmentBranchId?: string | null;
600 /**
601 * Fingerprint of the uploaded artifact/reused artifact inputs and the
602 * branch attachment that Prisma resolves environment variables from.
603 */
604 artifactHash: Redacted.Redacted<string> | undefined;
605 /**
606 * Whether the app output represents a local dev process.
607 */
608 local: boolean;
609 },
610 {
611 env?: Record<string, string | Redacted.Redacted<string> | null | undefined>;
612 },
613 Providers
614 > {}
615
616 export type ComputeRuntimeServices = ProcessServices;
617
618 export type ComputeShape = Main<ComputeRuntimeServices>;
619
620 export interface ComputeRuntimeContext extends ProcessContext {
621 readonly Type: ComputeTypeId;
622 }
623
624 export const isCompute = (value: unknown): value is Compute =>
625 typeof value === "object" && value !== null && "Type" in value && value.Type === ComputeTypeId;
626
627 const hasEffectNativeComputeInput = (props: ComputeProps) =>
628 props.isExternal !== true && (props.main !== undefined || props.exports !== undefined);
629
630 const isEffectNativeCompute = (props: ComputeProps) => hasEffectNativeComputeInput(props);
631
632 /**
633 * Build and deploy an application to Prisma Compute.
634 *
635 * Prisma's create-deployment API exposes neither an idempotency key nor a
636 * caller-defined recovery key. If the API commits a deployment but its create
637 * response is lost before Alchemy persists the returned ID, that deployment
638 * can remain orphaned and a later deploy may create another one. Alchemy does
639 * not guess that the App's latest deployment is owned, because it could belong
640 * to another actor. Use a durable, locked state backend and inspect the App's
641 * deployment history after an interrupted create.
642 *
643 * ### Deploying an App
644 * **Example:** Deploy a directory with an entrypoint
645 * ```typescript
646 * const app = yield* Prisma.Compute("api", {
647 * project: project.projectId,
648 * path: "./apps/api",
649 * entrypoint: "server.ts",
650 * port: 3000,
651 * });
652 * ```
653 *
654 * **Example:** Deploy an Effect-native HTTP app
655 * ```typescript
656 * export default Prisma.Compute(
657 * "api",
658 * {
659 * project,
660 * appName: "api",
661 * main: import.meta.filename,
662 * port: 8080,
663 * },
664 * Effect.gen(function* () {
665 * return {
666 * fetch: Effect.succeed(HttpServerResponse.text("ok")),
667 * };
668 * }),
669 * );
670 * ```
671 *
672 * ### Bundling & Tree-shaking
673 * `main` is bundled with rolldown at deploy time. Unused code is
674 * tree-shaken. `effect`, alchemy, and `@distilled.cloud` are marked
675 * pure so unused parts prune more aggressively. Your app is not
676 * marked pure.
677 *
678 * **Example:** Mark additional packages as pure
679 * Only list packages with no top-level side effects.
680 * ```typescript
681 * {
682 * main: "./src/app.ts",
683 * bundle: {
684 * extra: { pure: { packages: ["my-lib", "@my-scope/*"] } },
685 * },
686 * }
687 * ```
688 *
689 * **Example:** Turn it off
690 * ```typescript
691 * {
692 * main: "./src/app.ts",
693 * bundle: { extra: { pure: false } },
694 * }
695 * ```
696 *
697 * ### Runtime Bindings
698 * **Example:** Bind a Prisma Connection
699 * ```typescript
700 * export default Prisma.Compute(
701 * "api",
702 * {
703 * project,
704 * appName: "api",
705 * main: import.meta.filename,
706 * },
707 * Effect.gen(function* () {
708 * const db = yield* Prisma.Connect(connection);
709 * const sql = yield* SQL.Postgres({ url: db.databaseUrl });
710 *
711 * return {
712 * fetch: Effect.gen(function* () {
713 * const users = yield* sql`SELECT * FROM users`;
714 * return yield* HttpServerResponse.json(users);
715 * }),
716 * };
717 * }).pipe(Effect.provide(Prisma.ConnectBinding)),
718 * );
719 * ```
720 *
721 * **Example:** Build before upload and replace old versions
722 * ```typescript
723 * const app = yield* Prisma.Compute("api", {
724 * project: project.projectId,
725 * path: "./apps/api",
726 * build: {
727 * command: "bun build src/server.ts --target bun --outdir dist",
728 * outdir: "dist",
729 * entrypoint: "server.js",
730 * },
731 * port: 8080,
732 * env: {
733 * // Use this for a standalone Connection. A project's default database
734 * // is injected by Prisma without an explicit DATABASE_URL entry.
735 * DATABASE_URL: connection.databaseUrl,
736 * },
737 * destroyOldDeployment: true,
738 * });
739 * ```
740 *
741 * **Example:** Auto-build a framework app
742 * ```typescript
743 * const app = yield* Prisma.Compute("api", {
744 * project: project.projectId,
745 * path: "./apps/web",
746 * build: "auto",
747 * destroyOldDeployment: true,
748 * });
749 * ```
750 *
751 * **Example:** Deploy a static site
752 * ```typescript
753 * const web = yield* Prisma.Compute("web", {
754 * project,
755 * path: "./site",
756 * build: {
757 * type: "static",
758 * outdir: ".",
759 * },
760 * });
761 * ```
762 *
763 * **Example:** Deploy a prebuilt tar.gz artifact
764 * ```typescript
765 * const app = yield* Prisma.Compute("api", {
766 * project: project.projectId,
767 * artifactPath: "./dist/app.tar.gz",
768 * port: 8080,
769 * });
770 * ```
771 *
772 * ### Deployment Health
773 * **Example:** Require application readiness before promotion
774 * ```typescript
775 * const app = yield* Prisma.Compute("api", {
776 * project,
777 * path: "./apps/api",
778 * entrypoint: "server.ts",
779 * healthCheck: {
780 * path: "/api/health",
781 * // Defaults to any 2xx response when omitted.
782 * statusCodes: [200, 204],
783 * },
784 * });
785 * ```
786 *
787 * ### Local Development
788 * **Example:** Run locally during alchemy dev
789 * ```typescript
790 * const app = yield* Prisma.Compute("api", {
791 * project: project.projectId,
792 * path: "./apps/api",
793 * entrypoint: "server.ts",
794 * dev: {
795 * command: "bun run dev",
796 * port: 3000,
797 * },
798 * });
799 * ```
800 *
801 * @resource
802 * @product Compute
803 */
804 export const Compute: Platform<
805 Compute,
806 ComputeRuntimeServices,
807 ComputeShape,
808 ComputeRuntimeContext
809 > & {
810 <PropsReq = never>(
811 id: string,
812 props: InputProps<ComputeProps> | Effect.Effect<InputProps<ComputeProps>, never, PropsReq>,
813 ): Effect.Effect<Compute, never, Providers | PropsReq>;
814 } = Platform(ComputeTypeId, {
815 createRuntimeContext: (id): ComputeRuntimeContext => {
816 const runners: Effect.Effect<void, never, unknown>[] = [];
817 const env: Record<string, unknown> = {};
818 let runtimeContext: ComputeRuntimeContext;
819 const run: ProcessContext["run"] = (effect) =>
820 Effect.sync(() => {
821 runners.push(effect);
822 });
823
824 const serve = <Req = never>(handler: HttpEffect<Req>) =>
825 Effect.sync(() => {
826 runners.push(
827 Effect.gen(function* () {
828 const httpServer = yield* Effect.serviceOption(HttpServer).pipe(
829 Effect.map(Option.getOrUndefined),
830 );
831 if (httpServer) {
832 yield* httpServer.serve(
833 handler.pipe(Effect.provideService(RuntimeContext, runtimeContext)),
834 );
835 return yield* Effect.never;
836 }
837 }),
838 );
839 });
840
841 runtimeContext = {
842 Type: ComputeTypeId,
843 id,
844 env,
845 set: (bindingId: string, output: Output.Output) =>
846 Effect.sync(() => {
847 // Prisma env keys are validated to the uppercase POSIX shape
848 // ([A-Z_][A-Z0-9_]*), so the storage key is uppercased here. The
849 // runtime `get` receives the key this returns, so both halves
850 // agree without a second mapping.
851 const key = bindingId.replaceAll(/[^a-zA-Z0-9]/g, "_").toUpperCase();
852 env[key] = output.pipe(
853 Output.map((value) =>
854 Redacted.isRedacted(value)
855 ? Redacted.make(
856 JSON.stringify({
857 _tag: "Redacted",
858 value: Redacted.value(value),
859 }),
860 )
861 : JSON.stringify(value),
862 ),
863 );
864 return key;
865 }),
866 get: <T>(key: string) =>
867 // Runtime ConfigProvider lookups call back into RuntimeContext.get.
868 // Read the process env directly here to avoid re-entering that path.
869 Effect.sync(() => {
870 const value = process.env[key];
871 if (value === undefined) {
872 return undefined;
873 }
874 try {
875 const parsed = JSON.parse(value);
876 if (
877 parsed !== null &&
878 typeof parsed === "object" &&
879 (parsed as { _tag?: unknown })._tag === "Redacted" &&
880 "value" in (parsed as object)
881 ) {
882 return Redacted.make((parsed as { value: string }).value) as T;
883 }
884 return parsed as T;
885 } catch {
886 return value as T;
887 }
888 }),
889 run,
890 serve,
891 exports: Effect.sync(() => ({
892 default: Effect.forEach(
893 [...runners],
894 (effect) =>
895 Effect.forever(
896 effect.pipe(
897 Effect.tapError((error) => Effect.logError(error)),
898 Effect.ignore,
899 ),
900 ),
901 { concurrency: "unbounded" },
902 ),
903 })),
904 };
905 return runtimeContext;
906 },
907 });
908
909 const devProcesses = new Map<string, ChildProcessHandle>();
910
911 const stopTrackedDevProcess = Effect.fn(function* (processKey: string) {
912 const existing = devProcesses.get(processKey);
913 if (!existing) return;
914
915 const running = yield* existing.isRunning;
916 if (running) {
917 // Keep the handle tracked when termination fails so a later reconcile or
918 // destroy can retry instead of losing the only reference to the process.
919 yield* existing.kill();
920 }
921 devProcesses.delete(processKey);
922 });
923
924 const projectConsistencySchedule = Schedule.max([
925 Schedule.exponential(Duration.millis(500)),
926 Schedule.recurs(6),
927 ]);
928
929 // Only project/branch/app reads and the app create flow through the
930 // provisioning-consistency retries, so a NotFound there is exactly the
931 // post-create lag the schedule exists to absorb.
932 // The retried effects mix distilled's tagged operation errors with plain
933 // `Error` failures of their own (an unresolvable branch, a foreign App), so
934 // narrow before reading the tag.
935 const isAppProvisioningNotFound = (error: Error | { readonly _tag: string }) =>
936 "_tag" in error && error._tag === "NotFound";
937
938 // Distilled emits the cursor-paginated list operations as plain ops, so
939 // callers walk `pagination` themselves (see `src/Neon/Project.ts`).
940 const listBranches = (projectId: string, gitName?: string) =>
941 Effect.gen(function* () {
942 const branches: GetProjectBranchesResponse["data"][number][] = [];
943 let cursor: string | undefined;
944 while (true) {
945 const page = yield* getProjectBranches({
946 projectId,
947 limit: 100,
948 ...(gitName === undefined ? {} : { gitName }),
949 ...(cursor === undefined ? {} : { cursor }),
950 });
951 branches.push(...page.data);
952 const nextCursor = page.pagination.nextCursor;
953 if (!page.pagination.hasMore) break;
954 if (nextCursor === null) {
955 return yield* new PrismaPaginationError({
956 message:
957 "Invalid Prisma Management API pagination response from getProjectBranches: hasMore was true without a non-empty nextCursor",
958 });
959 }
960 cursor = nextCursor;
961 }
962 return branches;
963 });
964
965 const listApps = (projectId: string) =>
966 Effect.gen(function* () {
967 const apps: GetServicesResponse["data"][number][] = [];
968 let cursor: string | undefined;
969 while (true) {
970 const page = yield* getServices(
971 cursor === undefined ? { projectId, limit: 100 } : { projectId, limit: 100, cursor },
972 );
973 apps.push(...page.data);
974 const nextCursor = page.pagination.nextCursor;
975 if (!page.pagination.hasMore) break;
976 if (nextCursor === null) {
977 return yield* new PrismaPaginationError({
978 message:
979 "Invalid Prisma Management API pagination response from getServices: hasMore was true without a non-empty nextCursor",
980 });
981 }
982 cursor = nextCursor;
983 }
984 return apps;
985 });
986
987 const desiredComputeBranchId = Effect.fn(function* (
988 projectId: string,
989 props: Pick<ComputeProps, "branchId" | "branchGitName">,
990 ) {
991 if (props.branchId !== undefined && !isPrismaDevId(props.branchId)) {
992 return { resolved: true as const, id: props.branchId };
993 }
994 const branches = yield* listBranches(projectId, props.branchGitName);
995 const matchingBranches =
996 props.branchGitName === undefined ? branches.filter((branch) => branch.isDefault) : branches;
997 if (matchingBranches.length > 1) {
998 return yield* new ComputeConflict({
999 message:
1000 props.branchGitName === undefined
1001 ? `Prisma returned multiple default branches for project '${projectId}'; refusing an ambiguous Compute App match.`
1002 : `Prisma returned multiple branches named '${props.branchGitName}' in project '${projectId}'; refusing an ambiguous Compute App match.`,
1003 });
1004 }
1005 const branch = matchingBranches[0];
1006 return branch ? { resolved: true as const, id: branch.id } : { resolved: false as const };
1007 });
1008
1009 const createAppName = (id: string, appName: string | undefined) =>
1010 appName === undefined ? createPhysicalName({ id }) : Effect.succeed(appName);
1011
1012 const findApp = Effect.fn(function* (
1013 projectId: string,
1014 appName: string,
1015 props: Pick<ComputeProps, "branchId" | "branchGitName">,
1016 ) {
1017 const candidates = (yield* listApps(projectId)).filter((app) => app.name === appName);
1018 if (candidates.length === 0) return undefined;
1019 const branch = yield* desiredComputeBranchId(projectId, props);
1020 if (!branch.resolved) return undefined;
1021 const matches = candidates.filter((app) => app.branchId === branch.id);
1022 if (matches.length > 1) {
1023 return yield* new ComputeConflict({
1024 message: `Prisma returned multiple Apps named '${appName}' on branch '${branch.id}' in project '${projectId}'; refusing an ambiguous ownership match.`,
1025 });
1026 }
1027 return matches[0];
1028 });
1029
1030 const createApp = (
1031 projectId: string,
1032 props: ComputeProps & { appName: string },
1033 branchId: string,
1034 ) =>
1035 createService({
1036 projectId,
1037 displayName: props.appName,
1038 branchId,
1039 ...(props.regionId === undefined ? {} : { regionId: props.regionId }),
1040 }).pipe(
1041 // A replayed create would make a second App; the retry policy cannot
1042 // see the request, so opt out explicitly.
1043 Retry.none,
1044 Effect.map((response) => response.data),
1045 );
1046
1047 const plainEnv = (
1048 env: Record<string, string | Redacted.Redacted<string> | null | undefined> = {},
1049 ) =>
1050 Object.fromEntries(
1051 Object.entries(env).flatMap(([key, value]) =>
1052 value === undefined
1053 ? []
1054 : [[key, Redacted.isRedacted(value) ? Redacted.value(value) : value]],
1055 ),
1056 ) as Record<string, string | null>;
1057
1058 const persistedArtifactHashValue = (value: Redacted.Redacted<string> | string | undefined) =>
1059 Redacted.isRedacted(value) ? Redacted.value(value) : value;
1060
1061 const managedEnvKeys = (
1062 env: Record<string, string | Redacted.Redacted<string> | null | undefined> = {},
1063 ) =>
1064 Object.entries(plainEnv(env))
1065 .flatMap(([key, value]) => (value === null ? [] : [key]))
1066 .sort();
1067
1068 const ENV_KEY_PATTERN = /^[A-Z_][A-Z0-9_]*$/;
1069 const ENV_VALUE_MAX_BYTES = 8 * 1024;
1070 const EXPORT_IDENTIFIER_PATTERN = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
1071
1072 const computeEnvValue = (value: string | Redacted.Redacted<string>) =>
1073 Redacted.isRedacted(value) ? Redacted.value(value) : value;
1074
1075 const validateComputeEnvironmentKey = (key: string) =>
1076 Effect.gen(function* () {
1077 if (key.length < 1 || key.length > 256 || !ENV_KEY_PATTERN.test(key)) {
1078 return yield* new ComputeInvalidProps({
1079 message: `Prisma environment variable key '${key}' must match POSIX env-var key shape: [A-Z_][A-Z0-9_]* and be at most 256 characters.`,
1080 });
1081 }
1082 });
1083
1084 const validateComputeEnvironmentWrite = (key: string, value: string | Redacted.Redacted<string>) =>
1085 Effect.gen(function* () {
1086 yield* validateComputeEnvironmentKey(key);
1087 const raw = computeEnvValue(value);
1088 if (raw.length === 0) {
1089 return yield* new ComputeInvalidProps({
1090 message: `Prisma environment variable '${key}' value must be non-empty.`,
1091 });
1092 }
1093 const byteLength = yield* Effect.sync(() => new TextEncoder().encode(raw).byteLength);
1094 if (byteLength > ENV_VALUE_MAX_BYTES) {
1095 return yield* new ComputeInvalidProps({
1096 message: `Prisma environment variable '${key}' value exceeds ${ENV_VALUE_MAX_BYTES} bytes.`,
1097 });
1098 }
1099 });
1100
1101 const validateComputeHealthCheck = (healthCheck: ComputeHealthCheck | undefined) =>
1102 Effect.gen(function* () {
1103 if (healthCheck === undefined) return;
1104 if (
1105 !healthCheck.path.startsWith("/") ||
1106 healthCheck.path.startsWith("//") ||
1107 healthCheck.path.includes("\\") ||
1108 /\s/.test(healthCheck.path)
1109 ) {
1110 return yield* new ComputeInvalidProps({
1111 message: "healthCheck.path must be an absolute application path beginning with one '/'.",
1112 });
1113 }
1114 if (healthCheck.statusCodes !== undefined && healthCheck.statusCodes.length === 0) {
1115 return yield* new ComputeInvalidProps({
1116 message: "healthCheck.statusCodes must contain at least one status.",
1117 });
1118 }
1119 for (const status of healthCheck.statusCodes ?? []) {
1120 if (!Number.isInteger(status) || status < 100 || status > 599) {
1121 return yield* new ComputeInvalidProps({
1122 message:
1123 "healthCheck.statusCodes must contain HTTP status integers from 100 through 599.",
1124 });
1125 }
1126 }
1127 });
1128
1129 const validateComputeProps = (props: ComputeProps) =>
1130 Effect.gen(function* () {
1131 yield* validateComputeHealthCheck(props.healthCheck);
1132 if (props.healthCheck !== undefined && props.verifyUrl === false) {
1133 return yield* new ComputeInvalidProps({
1134 message: "healthCheck cannot be combined with verifyUrl: false.",
1135 });
1136 }
1137 if (props.healthCheck !== undefined && props.start === false) {
1138 return yield* new ComputeInvalidProps({
1139 message: "healthCheck requires start to be enabled.",
1140 });
1141 }
1142 for (const [name, value] of [
1143 ["timeoutSeconds", props.timeoutSeconds],
1144 ["pollIntervalMs", props.pollIntervalMs],
1145 ["urlReadinessTimeoutSeconds", props.urlReadinessTimeoutSeconds],
1146 ] as const) {
1147 if (value !== undefined && (!Number.isFinite(value) || value <= 0)) {
1148 return yield* new ComputeInvalidProps({
1149 message: `${name} must be a positive finite number.`,
1150 });
1151 }
1152 }
1153 for (const [name, value] of [
1154 ["port", props.port],
1155 ["dev.port", props.dev?.port],
1156 ] as const) {
1157 if (value !== undefined && (!Number.isInteger(value) || value < 1 || value > 65_535)) {
1158 return yield* new ComputeInvalidProps({
1159 message: `${name} must be an integer between 1 and 65535.`,
1160 });
1161 }
1162 }
1163 for (const [key, value] of Object.entries(props.env ?? {})) {
1164 if (value === undefined) continue;
1165 if (value === null) {
1166 yield* validateComputeEnvironmentKey(key);
1167 } else {
1168 yield* validateComputeEnvironmentWrite(key, value);
1169 }
1170 }
1171 if ((props.skipPromote ?? false) && (props.destroyOldDeployment ?? false)) {
1172 return yield* new ComputeInvalidProps({
1173 message:
1174 "destroyOldDeployment cannot be combined with skipPromote because the previous deployment stays active when promotion is skipped.",
1175 });
1176 }
1177 if (props.start === false && !(props.skipPromote ?? false)) {
1178 return yield* new ComputeInvalidProps({
1179 message:
1180 "start: false requires skipPromote: true because Prisma Compute promotion requires a running deployment.",
1181 });
1182 }
1183 if (props.branchId !== undefined && props.branchGitName !== undefined) {
1184 return yield* new ComputeInvalidProps({
1185 message: "branchId and branchGitName are mutually exclusive.",
1186 });
1187 }
1188 if (props.branchId === null || props.branchGitName === null) {
1189 return yield* new ComputeInvalidProps({
1190 message:
1191 "Prisma.Compute requires an attached branch because deployment creation resolves environment variables from the App branch. Omit branchGitName to use the project's default branch, or set branchId/branchGitName.",
1192 });
1193 }
1194 if ((props.skipCodeUpload ?? false) && props.artifactPath !== undefined) {
1195 return yield* new ComputeInvalidProps({
1196 message: "skipCodeUpload cannot be combined with artifactPath.",
1197 });
1198 }
1199 if ((props.skipCodeUpload ?? false) && props.build !== undefined) {
1200 return yield* new ComputeInvalidProps({
1201 message: "skipCodeUpload cannot be combined with build.",
1202 });
1203 }
1204 if (hasEffectNativeComputeInput(props)) {
1205 const handler = props.handler ?? "default";
1206 if (handler !== "default" && !EXPORT_IDENTIFIER_PATTERN.test(handler)) {
1207 return yield* new ComputeInvalidProps({
1208 message:
1209 "Effect-native Prisma Compute handler must be `default` or a valid JavaScript export identifier.",
1210 });
1211 }
1212 if (props.main === undefined) {
1213 return yield* new ComputeInvalidProps({
1214 message:
1215 "Effect-native Prisma Compute apps require `main`. Set `main: import.meta.filename`.",
1216 });
1217 }
1218 if (props.artifactPath !== undefined) {
1219 return yield* new ComputeInvalidProps({
1220 message: "Effect-native Prisma Compute apps cannot use artifactPath.",
1221 });
1222 }
1223 if (props.build !== undefined) {
1224 return yield* new ComputeInvalidProps({
1225 message: "Effect-native Prisma Compute apps cannot use build.",
1226 });
1227 }
1228 if (props.skipCodeUpload) {
1229 return yield* new ComputeInvalidProps({
1230 message: "Effect-native Prisma Compute apps cannot skip code upload.",
1231 });
1232 }
1233 }
1234 });
1235
1236 const processEnv = (
1237 env: Record<string, string | Redacted.Redacted<string> | null | undefined> = {},
1238 ) =>
1239 Object.fromEntries(
1240 Object.entries(env).flatMap(([key, value]) =>
1241 value === undefined || value === null
1242 ? []
1243 : [[key, Redacted.isRedacted(value) ? Redacted.value(value) : value]],
1244 ),
1245 ) as Record<string, string>;
1246
1247 const isPrismaEdgeServiceNotFound = (status: number, body: string) =>
1248 status === 404 &&
1249 (body.includes("There is no service on this URL") ||
1250 body.includes("<title>Service not found</title>"));
1251
1252 const URL_READINESS_BODY_PREFIX_BYTES = 64 * 1024;
1253
1254 const readResponseBodyPrefix = (response: HttpClientResponse) =>
1255 Effect.gen(function* () {
1256 const chunks: Uint8Array[] = [];
1257 let bytes = 0;
1258 yield* Stream.runForEachWhile(response.stream, (chunk) =>
1259 Effect.sync(() => {
1260 const remaining = URL_READINESS_BODY_PREFIX_BYTES - bytes;
1261 if (remaining <= 0) return false;
1262 const kept = chunk.byteLength > remaining ? chunk.slice(0, remaining) : chunk;
1263 chunks.push(kept);
1264 bytes += kept.byteLength;
1265 return bytes < URL_READINESS_BODY_PREFIX_BYTES;
1266 }),
1267 );
1268 const prefix = new Uint8Array(bytes);
1269 let offset = 0;
1270 for (const chunk of chunks) {
1271 prefix.set(chunk, offset);
1272 offset += chunk.byteLength;
1273 }
1274 return new TextDecoder().decode(prefix);
1275 });
1276
1277 export const waitForDeploymentUrl = Effect.fn(function* (
1278 url: string | undefined,
1279 props: ComputeProps,
1280 ) {
1281 yield* validateComputeHealthCheck(props.healthCheck);
1282 if (props.healthCheck !== undefined && props.verifyUrl === false) {
1283 return yield* new ComputeInvalidProps({
1284 message: "healthCheck cannot be combined with verifyUrl: false.",
1285 });
1286 }
1287 if (props.verifyUrl === false) return;
1288 if (!url) {
1289 return yield* new ComputeUnexpectedResponse({
1290 message:
1291 props.healthCheck === undefined
1292 ? "Prisma Compute did not return a public URL for readiness verification."
1293 : "Prisma Compute did not return a public URL for the configured healthCheck.",
1294 });
1295 }
1296 const httpOption = yield* Effect.serviceOption(HttpClient.HttpClient);
1297 if (Option.isNone(httpOption)) {
1298 return props.healthCheck === undefined
1299 ? undefined
1300 : yield* new ComputeOperationFailed({
1301 message: "Prisma Compute healthCheck requires an HTTP client service.",
1302 });
1303 }
1304
1305 const http = httpOption.value;
1306 const probeUrl =
1307 props.healthCheck === undefined ? url : new URL(props.healthCheck.path, url).toString();
1308 const acceptsStatus = (status: number) =>
1309 props.healthCheck === undefined ||
1310 (props.healthCheck.statusCodes === undefined
1311 ? status >= 200 && status <= 299
1312 : props.healthCheck.statusCodes.includes(status));
1313 const timeoutSeconds = props.urlReadinessTimeoutSeconds ?? 60;
1314 const intervalMs = props.pollIntervalMs ?? 1_000;
1315 if (!Number.isFinite(timeoutSeconds) || timeoutSeconds <= 0) {
1316 return yield* new ComputeInvalidProps({
1317 message: "urlReadinessTimeoutSeconds must be a positive finite number.",
1318 });
1319 }
1320 if (!Number.isFinite(intervalMs) || intervalMs <= 0) {
1321 return yield* new ComputeInvalidProps({
1322 message: "pollIntervalMs must be a positive finite number.",
1323 });
1324 }
1325 const timeoutMs = timeoutSeconds * 1_000;
1326 const startedAt = yield* Effect.sync(() => Date.now());
1327 let lastStatus: number | undefined;
1328 let lastBody = "";
1329
1330 while (true) {
1331 const beforeRequest = yield* Effect.sync(() => Date.now());
1332 const remainingBeforeRequest = timeoutMs - (beforeRequest - startedAt);
1333 if (remainingBeforeRequest <= 0) {
1334 return yield* Effect.fail(deploymentUrlTimeoutError(probeUrl, lastStatus, lastBody));
1335 }
1336 const requestTimeoutMs = Math.min(5_000, remainingBeforeRequest);
1337 const response = yield* http.execute(HttpClientRequest.get(probeUrl)).pipe(
1338 Effect.provideService(FetchHttpClient.RequestInit, {
1339 redirect: "manual",
1340 }),
1341 Effect.timeoutOption(Duration.millis(requestTimeoutMs)),
1342 Effect.map(Option.getOrUndefined),
1343 Effect.orElseSucceed(() => undefined),
1344 );
1345 if (response) {
1346 lastStatus = response.status;
1347 // Without an application health check, any non-404 response proves that
1348 // edge routing is live. A configured health check must also match its
1349 // status contract. Do not consume non-404 bodies: application responses
1350 // may intentionally stream.
1351 if (response.status !== 404 && acceptsStatus(response.status)) {
1352 return;
1353 }
1354 const beforeBody = yield* Effect.sync(() => Date.now());
1355 const remainingBeforeBody = timeoutMs - (beforeBody - startedAt);
1356 if (remainingBeforeBody > 0) {
1357 const bodyPrefix = yield* readResponseBodyPrefix(response).pipe(
1358 Effect.timeoutOption(Duration.millis(Math.min(2_000, remainingBeforeBody))),
1359 Effect.orElseSucceed(() => Option.none<string>()),
1360 );
1361 if (Option.isSome(bodyPrefix)) {
1362 lastBody = bodyPrefix.value;
1363 if (
1364 !isPrismaEdgeServiceNotFound(response.status, lastBody) &&
1365 acceptsStatus(response.status)
1366 ) {
1367 return;
1368 }
1369 }
1370 }
1371 }
1372
1373 const elapsed = yield* Effect.sync(() => Date.now() - startedAt);
1374 if (elapsed >= timeoutMs) {
1375 return yield* Effect.fail(deploymentUrlTimeoutError(probeUrl, lastStatus, lastBody));
1376 }
1377
1378 yield* Effect.sleep(Duration.millis(Math.min(intervalMs, timeoutMs - elapsed)));
1379 }
1380 });
1381
1382 const deploymentUrlTimeoutError = (url: string, lastStatus: number | undefined, lastBody: string) =>
1383 new Error(
1384 [
1385 `Timed out waiting for Prisma Compute URL '${url}' to become reachable.`,
1386 lastStatus ? `Last response: HTTP ${lastStatus}.` : "No HTTP response was received.",
1387 lastBody.includes("There is no service on this URL")
1388 ? "The Prisma edge returned: There is no service on this URL."
1389 : undefined,
1390 ]
1391 .filter((line): line is string => line !== undefined)
1392 .join(" "),
1393 );
1394
1395 const isAutoBuild = (build: ComputeProps["build"]): build is "auto" | ComputeAutoBuild =>
1396 build === "auto" ||
1397 (typeof build === "object" && build !== null && "type" in build && build.type === "auto");
1398
1399 const isStaticBuild = (build: ComputeProps["build"]): build is ComputeStaticBuild =>
1400 typeof build === "object" && build !== null && "type" in build && build.type === "static";
1401
1402 export class ComputePackageJsonError extends Data.TaggedError("ComputePackageJsonError")<{
1403 readonly message: string;
1404 readonly cause?: unknown;
1405 }> {}
1406
1407 const readPackageMain = Effect.fn(function* (directory: string) {
1408 const fs = yield* FileSystem.FileSystem;
1409 const path = yield* Path.Path;
1410 const text = yield* fs.readFileString(path.join(directory, "package.json")).pipe(
1411 Effect.catchIf(
1412 (error) => error._tag === "PlatformError" && error.reason._tag === "NotFound",
1413 () => Effect.undefined,
1414 ),
1415 );
1416 if (!text) return undefined;
1417 return yield* Effect.try({
1418 try: () => {
1419 const parsed = JSON.parse(text) as { main?: unknown };
1420 return typeof parsed.main === "string" ? parsed.main : undefined;
1421 },
1422 catch: (cause) =>
1423 new ComputePackageJsonError({
1424 message: `Failed to parse package.json in ${directory}: ${cause instanceof Error ? cause.message : String(cause)}`,
1425 cause,
1426 }),
1427 });
1428 });
1429
1430 const writeBundleDirectory = Effect.fn(function* (bundle: Bundle.BundleOutput) {
1431 const fs = yield* FileSystem.FileSystem;
1432 const path = yield* Path.Path;
1433 if (bundle.files.length === 0) {
1434 return yield* new ComputeOperationFailed({
1435 message: "Effect-native Compute bundler produced no output files.",
1436 });
1437 }
1438 const normalizedFiles = yield* Effect.forEach(bundle.files, (file) =>
1439 normalizeBundleFilePath(file.path).pipe(
1440 Effect.map((normalizedPath) => ({ file, normalizedPath })),
1441 ),
1442 );
1443 const seen = new Set<string>();
1444 for (const { normalizedPath } of normalizedFiles) {
1445 if (seen.has(normalizedPath)) {
1446 return yield* new ComputeOperationFailed({
1447 message: `Effect-native Compute bundler produced duplicate output path '${normalizedPath}'.`,
1448 });
1449 }
1450 seen.add(normalizedPath);
1451 }
1452 const directory = yield* fs.makeTempDirectory({
1453 prefix: "alchemy-prisma-compute-",
1454 });
1455
1456 return yield* Effect.gen(function* () {
1457 for (const { file, normalizedPath } of normalizedFiles) {
1458 const target = path.join(directory, normalizedPath);
1459 yield* fs.makeDirectory(path.dirname(target), { recursive: true });
1460 if (typeof file.content === "string") {
1461 yield* fs.writeFileString(target, file.content);
1462 } else {
1463 yield* fs.writeFile(target, file.content);
1464 }
1465 }
1466
1467 return {
1468 directory,
1469 entrypoint: normalizedFiles[0].normalizedPath,
1470 cleanup: fs.remove(directory, { recursive: true }).pipe(Effect.ignore),
1471 };
1472 }).pipe(Effect.onError(() => fs.remove(directory, { recursive: true }).pipe(Effect.ignore)));
1473 });
1474
1475 const bundleEffectCompute = Effect.fn(function* (props: ComputeProps) {
1476 if (!props.main) {
1477 return yield* new ComputeInvalidProps({
1478 message:
1479 "Effect-native Prisma Compute apps require `main`. Set `main: import.meta.filename`.",
1480 });
1481 }
1482
1483 const fs = yield* FileSystem.FileSystem;
1484 const stack = yield* Effect.serviceOption(Stack).pipe(
1485 Effect.map(
1486 Option.getOrElse(() => ({
1487 name: "alchemy",
1488 stage: "dev",
1489 bindings: {},
1490 resources: {},
1491 })),
1492 ),
1493 );
1494 const virtualEntryPlugin = yield* Bundle.virtualEntryPlugin;
1495 const realMain = yield* fs.realPath(props.main);
1496 const cwd = yield* findCwdForBundle(realMain);
1497 const handler = props.handler ?? "default";
1498 const defaultPort = props.port ?? 8080;
1499
1500 const importEntrypoint =
1501 handler === "default" ? "import entrypoint" : `import { ${handler} as entrypoint }`;
1502
1503 const bundle = yield* Bundle.build(
1504 {
1505 ...props.bundle?.input,
1506 input: realMain,
1507 cwd,
1508 platform: "node",
1509 // Prisma Compute runs the bundle on bun.
1510 resolve: {
1511 conditionNames: [...Bundle.BUN_CONDITION_NAMES],
1512 ...props.bundle?.input?.resolve,
1513 },
1514 plugins: [
1515 props.bundle?.input?.plugins,
1516 virtualEntryPlugin(
1517 (importPath) => `
1518 import { bootstrap } from "@alchemy.run/prisma/Bootstrap";
1519 ${importEntrypoint} from ${JSON.stringify(importPath)};
1520
1521 await bootstrap(entrypoint, ${JSON.stringify({
1522 port: defaultPort,
1523 stack: { name: stack.name, stage: stack.stage },
1524 })});
1525 `,
1526 ),
1527 ],
1528 checks: {
1529 unresolvedImport: false,
1530 ineffectiveDynamicImport: false,
1531 },
1532 },
1533 {
1534 ...props.bundle?.output,
1535 format: "esm",
1536 sourcemap: props.bundle?.output?.sourcemap ?? "hidden",
1537 minify: props.bundle?.output?.minify ?? true,
1538 entryFileNames: "index.js",
1539 },
1540 props.bundle?.extra,
1541 );
1542
1543 const artifact = yield* writeBundleDirectory(bundle);
1544 const file = yield* createComputeArchive({
1545 directory: artifact.directory,
1546 entrypoint: artifact.entrypoint,
1547 ignore: props.archiveIgnore,
1548 output: "file",
1549 }).pipe(Effect.ensuring(artifact.cleanup));
1550
1551 return {
1552 file,
1553 bundleHash: bundle.hash,
1554 };
1555 });
1556
1557 const resolveArtifact = Effect.fn(function* (props: ComputeProps) {
1558 const env = plainEnv(props.env);
1559 const envClass = props.envClass ?? "production";
1560 const defaultPort = props.port ?? 8080;
1561 if (isEffectNativeCompute(props)) {
1562 if (props.artifactPath !== undefined) {
1563 return yield* new ComputeInvalidProps({
1564 message: "Effect-native Prisma Compute apps cannot use artifactPath.",
1565 });
1566 }
1567 if (props.skipCodeUpload) {
1568 return yield* new ComputeInvalidProps({
1569 message: "Effect-native Prisma Compute apps cannot skip code upload.",
1570 });
1571 }
1572 if (props.build !== undefined) {
1573 return yield* new ComputeInvalidProps({
1574 message: "Effect-native Prisma Compute apps cannot use build.",
1575 });
1576 }
1577 const artifact = yield* bundleEffectCompute(props);
1578 return {
1579 file: artifact.file,
1580 hash: yield* sha256Object({
1581 bundle: artifact.bundleHash,
1582 env,
1583 envClass,
1584 port: defaultPort,
1585 }),
1586 port: defaultPort,
1587 };
1588 }
1589
1590 if (props.skipCodeUpload) {
1591 return {
1592 file: undefined,
1593 hash: yield* sha256Object({
1594 skipCodeUpload: true,
1595 env,
1596 envClass,
1597 port: defaultPort,
1598 }),
1599 port: defaultPort,
1600 };
1601 }
1602
1603 if (props.artifactPath !== undefined) {
1604 const file = yield* readUploadArtifact({
1605 artifactPath: props.artifactPath,
1606 output: "file",
1607 });
1608 return {
1609 file: file!,
1610 hash: yield* sha256Object({
1611 artifact: file!.sha256,
1612 env,
1613 envClass,
1614 port: defaultPort,
1615 }),
1616 port: defaultPort,
1617 };
1618 }
1619
1620 const path = yield* Path.Path;
1621 const appPath = path.resolve(props.path ?? ".");
1622 let directory = appPath;
1623 let entrypoint = props.entrypoint;
1624 let port = defaultPort;
1625
1626 if (isAutoBuild(props.build)) {
1627 const auto = props.build === "auto" ? undefined : props.build;
1628 const artifact = yield* runComputeAutoBuild({
1629 appPath,
1630 entrypoint,
1631 framework: auto?.framework,
1632 env: auto?.env,
1633 outputLimitBytes: auto?.outputLimitBytes,
1634 timeoutSeconds: auto?.timeoutSeconds,
1635 });
1636 const file = yield* createComputeArchive({
1637 directory: artifact.directory,
1638 entrypoint: artifact.entrypoint,
1639 ignore: props.archiveIgnore,
1640 ignorePrefix: artifact.archiveIgnorePrefix,
1641 requiredFiles: artifact.requiredFiles,
1642 output: "file",
1643 }).pipe(Effect.ensuring(artifact.cleanup));
1644 port = props.port ?? artifact.defaultPort ?? 8080;
1645 return {
1646 file,
1647 hash: yield* sha256Object({
1648 artifact: file.sha256,
1649 env,
1650 envClass,
1651 port,
1652 }),
1653 port,
1654 };
1655 }
1656
1657 if (isStaticBuild(props.build)) {
1658 const artifact = yield* runComputeStaticBuild({
1659 appPath,
1660 command: props.build.command,
1661 cwd: props.build.cwd,
1662 outdir: props.build.outdir,
1663 indexPage: props.build.indexPage,
1664 spa: props.build.spa,
1665 env: props.build.env,
1666 outputLimitBytes: props.build.outputLimitBytes,
1667 timeoutSeconds: props.build.timeoutSeconds,
1668 });
1669 const file = yield* createComputeArchive({
1670 directory: artifact.directory,
1671 entrypoint: artifact.entrypoint,
1672 ignore: props.archiveIgnore,
1673 ignorePrefix: artifact.archiveIgnorePrefix,
1674 requiredFiles: artifact.requiredFiles,
1675 output: "file",
1676 }).pipe(Effect.ensuring(artifact.cleanup));
1677 port = props.port ?? artifact.defaultPort ?? 8080;
1678 return {
1679 file,
1680 hash: yield* sha256Object({
1681 artifact: file.sha256,
1682 env,
1683 envClass,
1684 port,
1685 }),
1686 port,
1687 };
1688 }
1689
1690 if (props.build) {
1691 const cwd = props.build.cwd ? path.resolve(props.build.cwd) : appPath;
1692 yield* runBuildCommand({
1693 command: props.build.command,
1694 cwd,
1695 env: processEnv(props.build.env),
1696 outputLimitBytes: props.build.outputLimitBytes,
1697 timeoutSeconds: props.build.timeoutSeconds,
1698 });
1699 directory = path.resolve(cwd, props.build.outdir);
1700 entrypoint = props.build.entrypoint ?? entrypoint;
1701 }
1702
1703 entrypoint ??= yield* readPackageMain(directory);
1704 if (!entrypoint) {
1705 return yield* new ComputeInvalidProps({
1706 message:
1707 "Prisma Compute app entrypoint is required. Set `entrypoint` or package.json `main`.",
1708 });
1709 }
1710
1711 const normalizedEntrypoint = yield* normalizeEntrypoint(entrypoint);
1712 const file = yield* createComputeArchive({
1713 directory,
1714 entrypoint: normalizedEntrypoint,
1715 ignore: props.archiveIgnore,
1716 output: "file",
1717 });
1718 return {
1719 file,
1720 hash: yield* sha256Object({
1721 artifact: file.sha256,
1722 env,
1723 envClass,
1724 port,
1725 }),
1726 port,
1727 };
1728 });
1729
1730 const findExistingApp = Effect.fn(function* (output: Compute["Attributes"] | undefined) {
1731 const appId = output?.appId && !isPrismaDevId(output.appId) ? output.appId : undefined;
1732 return appId
1733 ? yield* getService({ serviceId: appId }).pipe(
1734 Effect.map((response) => response.data),
1735 Effect.catchTag("NotFound", () => Effect.undefined),
1736 )
1737 : undefined;
1738 });
1739
1740 const ensureApp = Effect.fn(function* (
1741 projectId: string,
1742 props: ComputeProps & { appName: string },
1743 output: Compute["Attributes"] | undefined,
1744 observedApp?: ObservedApp,
1745 ) {
1746 let app: ObservedApp | undefined = observedApp ?? (yield* findExistingApp(output));
1747 const branch = yield* desiredComputeBranchId(projectId, props);
1748 if (!branch.resolved) {
1749 return yield* new ComputeOperationFailed({
1750 message:
1751 props.branchGitName === undefined
1752 ? `Prisma project '${projectId}' has no default branch to attach Compute App '${props.appName}'. Create or promote a default branch, or specify branchId/branchGitName.`
1753 : `Prisma project '${projectId}' has no branch named '${props.branchGitName}' to attach Compute App '${props.appName}'.`,
1754 });
1755 }
1756
1757 let createdApp = false;
1758 if (!app) {
1759 const result = yield* createApp(projectId, props, branch.id).pipe(
1760 Effect.map((app) => ({ app, created: true })),
1761 Effect.catchTag("Conflict", (conflict) =>
1762 findApp(projectId, props.appName, props).pipe(
1763 Effect.flatMap((app) =>
1764 app && output?.appId !== undefined && app.id === output.appId
1765 ? Effect.succeed({ app, created: false })
1766 : Effect.fail(
1767 new ComputeConflict({
1768 message: `Prisma App '${props.appName}' already exists on the requested branch but is not owned by this Compute resource. Import it with explicit adoption or choose a different App name.`,
1769 cause: conflict,
1770 }),
1771 ),
1772 ),
1773 ),
1774 ),
1775 );
1776 app = result.app;
1777 createdApp = result.created;
1778 }
1779
1780 yield* ensureAppImmutableIdentity(
1781 app,
1782 projectId,
1783 props.regionId ?? output?.regionId ?? app.region.id,
1784 );
1785 if (app.name !== props.appName || app.branchId !== branch.id) {
1786 app = yield* updateService({
1787 serviceId: app.id,
1788 displayName: props.appName,
1789 branchId: branch.id,
1790 }).pipe(Effect.map((response) => response.data));
1791 }
1792
1793 return { app, created: createdApp };
1794 });
1795
1796 const ensureSkipCodeUploadCanFork = (props: ComputeProps, app: ObservedApp | undefined) =>
1797 Effect.gen(function* () {
1798 if (!(props.skipCodeUpload ?? false)) return;
1799 if (app?.latestDeploymentId) return;
1800 return yield* new ComputeInvalidProps({
1801 message:
1802 "skipCodeUpload requires an existing Prisma deployment to fork from. Upload and start a deployment first, or remove skipCodeUpload.",
1803 });
1804 });
1805
1806 const findEnvironmentVariable = (
1807 projectId: string,
1808 cls: "production" | "preview",
1809 key: string,
1810 branchId?: string | null,
1811 ) =>
1812 Effect.gen(function* () {
1813 // Distilled emits the cursor-paginated list operations as plain ops, so
1814 // callers walk `pagination` themselves (see `src/Neon/Project.ts`).
1815 const variables: GetEnvironmentVariablesResponse["data"][number][] = [];
1816 let cursor: string | undefined;
1817 while (true) {
1818 const page = yield* getEnvironmentVariables({
1819 projectId,
1820 class: cls,
1821 key,
1822 limit: 100,
1823 ...(branchId ? { branchId } : {}),
1824 ...(cursor === undefined ? {} : { cursor }),
1825 });
1826 variables.push(...page.data);
1827 const nextCursor = page.pagination.nextCursor;
1828 if (!page.pagination.hasMore) break;
1829 if (nextCursor === null) {
1830 return yield* new PrismaPaginationError({
1831 message:
1832 "Invalid Prisma Management API pagination response from getEnvironmentVariables: hasMore was true without a non-empty nextCursor",
1833 });
1834 }
1835 cursor = nextCursor;
1836 }
1837 return variables.find((variable) => variable.branchId === (branchId ?? null));
1838 });
1839
1840 const systemManagedEnvironmentVariableError = (key: string) =>
1841 new Error(
1842 `Prisma environment variable '${key}' is managed by Prisma and cannot be managed by Alchemy.`,
1843 );
1844
1845 const ensureUserManagedEnvironmentVariable = (variable: ObservedEnvironmentVariable) =>
1846 Effect.gen(function* () {
1847 if (variable.isManagedBySystem) {
1848 return yield* Effect.fail(systemManagedEnvironmentVariableError(variable.key));
1849 }
1850 });
1851
1852 const environmentVariableOwnershipError = (key: string, variableId: string) =>
1853 new Error(
1854 `Prisma environment variable '${key}' (${variableId}) already exists in this branch/class scope but is not owned by this Compute resource. It may be foreign or left by an interrupted prior Compute deploy; the Management API exposes no ownership marker or plaintext value that would make takeover safe. Use one standalone Prisma.EnvironmentVariable resource as the independently manageable owner, choose a different key, explicitly adopt that resource, or remove the existing variable before deploying.`,
1855 );
1856
1857 interface ComputeEnvironmentScope {
1858 class: "production" | "preview";
1859 branchId: string | null;
1860 }
1861
1862 const environmentScope = (
1863 cls: "production" | "preview",
1864 branchId?: string | null,
1865 ): ComputeEnvironmentScope => ({
1866 class: cls,
1867 branchId: branchId ?? null,
1868 });
1869
1870 const sameEnvironmentScope = (left: ComputeEnvironmentScope, right: ComputeEnvironmentScope) =>
1871 left.class === right.class && left.branchId === right.branchId;
1872
1873 const resolveComputeEnvironmentScope = Effect.fn(function* (app: ObservedApp, props: ComputeProps) {
1874 if (!app.branchId) {
1875 return yield* new ComputeConflict({
1876 message:
1877 "Prisma.Compute requires an attached branch because deployment creation resolves environment variables from the App branch.",
1878 });
1879 }
1880
1881 const branch = yield* getBranch({
1882 branchId: app.branchId,
1883 }).pipe(Effect.map((response) => response.data));
1884 const inferredClass = branch.role;
1885 if (props.envClass !== undefined && props.envClass !== inferredClass) {
1886 return yield* new ComputeInvalidProps({
1887 message: `Prisma.Compute envClass '${props.envClass}' does not match attached branch role '${inferredClass}'. Omit envClass to let Alchemy infer the correct environment variable scope.`,
1888 });
1889 }
1890
1891 return environmentScope(inferredClass, inferredClass === "preview" ? app.branchId : null);
1892 });
1893
1894 interface ComputeEnvironmentPlan {
1895 key: string;
1896 value: string | null;
1897 variable: ObservedEnvironmentVariable | undefined;
1898 }
1899
1900 const rollbackCreatedEnvironmentVariables = Effect.fn(function* (
1901 createdIds: ReadonlyArray<{ key: string; id: string }>,
1902 originalError: unknown,
1903 ) {
1904 if (createdIds.length === 0) {
1905 return yield* Effect.fail(originalError);
1906 }
1907 const cleanupErrors: unknown[] = [];
1908 for (const created of [...createdIds].reverse()) {
1909 const result = yield* Effect.result(
1910 deleteEnvironmentVariable({ envVarId: created.id }).pipe(
1911 Effect.catchTag("NotFound", () => Effect.void),
1912 ),
1913 );
1914 if (Result.isFailure(result)) {
1915 cleanupErrors.push(result.failure);
1916 }
1917 }
1918 if (cleanupErrors.length > 0) {
1919 return yield* Effect.fail(
1920 new AggregateError(
1921 [originalError, ...cleanupErrors],
1922 `Failed to roll back newly created Prisma environment variables after reconcile failed. Manual cleanup: ${createdIds.map(({ id }) => `DELETE /v1/environment-variables/${id}`).join(", ")}.`,
1923 ),
1924 );
1925 }
1926 return yield* Effect.fail(originalError);
1927 });
1928
1929 const syncComputeEnvironmentInternal = Effect.fn(function* (
1930 projectId: string,
1931 cls: "production" | "preview",
1932 env: Record<string, string | Redacted.Redacted<string> | null | undefined> = {},
1933 branchId?: string | null,
1934 ownedIds: Readonly<Record<string, string>> = {},
1935 ) {
1936 const synced: string[] = [];
1937 const deleted: string[] = [];
1938 const nextOwnedIds: Record<string, string> = {};
1939 const createdIds: Array<{ key: string; id: string }> = [];
1940 const plans: ComputeEnvironmentPlan[] = [];
1941
1942 // Observe and validate the entire scope before the first write. In
1943 // particular, a foreign/system-owned key discovered late in the input must
1944 // not leave earlier keys partially created.
1945 for (const [key, value] of Object.entries(plainEnv(env))) {
1946 if (value === null) {
1947 yield* validateComputeEnvironmentKey(key);
1948 } else {
1949 yield* validateComputeEnvironmentWrite(key, value);
1950 }
1951 const variable = yield* findEnvironmentVariable(projectId, cls, key, branchId);
1952 if (variable) {
1953 yield* ensureUserManagedEnvironmentVariable(variable);
1954 if (ownedIds[key] !== variable.id) {
1955 return yield* Effect.fail(environmentVariableOwnershipError(key, variable.id));
1956 }
1957 }
1958 plans.push({ key, value, variable });
1959 }
1960
1961 const apply = Effect.gen(function* () {
1962 for (const { key, value, variable } of plans) {
1963 if (value === null) continue;
1964 if (variable) {
1965 yield* updateEnvironmentVariable({
1966 envVarId: variable.id,
1967 value,
1968 });
1969 nextOwnedIds[key] = variable.id;
1970 } else {
1971 const created = yield* createEnvironmentVariable({
1972 projectId,
1973 ...(branchId ? { branchId } : {}),
1974 class: cls,
1975 key,
1976 value,
1977 }).pipe(
1978 // A replayed create would make a second variable; the retry policy
1979 // cannot see the request, so opt out explicitly.
1980 Retry.none,
1981 Effect.map((response) => response.data),
1982 );
1983 createdIds.push({ key, id: created.id });
1984 nextOwnedIds[key] = created.id;
1985 }
1986 synced.push(key);
1987 }
1988 // Apply explicit deletions only after all ownership checks and upserts.
1989 for (const { key, value, variable } of plans) {
1990 if (value !== null || !variable) continue;
1991 yield* deleteEnvironmentVariable({
1992 envVarId: variable.id,
1993 }).pipe(Effect.catchTag("NotFound", () => Effect.void));
1994 deleted.push(key);
1995 }
1996 return { synced, deleted, ownedIds: nextOwnedIds, createdIds };
1997 });
1998
1999 return yield* apply.pipe(
2000 Effect.catch((error) => rollbackCreatedEnvironmentVariables(createdIds, error)),
2001 );
2002 });
2003
2004 export const syncComputeEnvironment = Effect.fn(function* (
2005 projectId: string,
2006 cls: "production" | "preview",
2007 env: Record<string, string | Redacted.Redacted<string> | null | undefined> = {},
2008 branchId?: string | null,
2009 ownedIds: Readonly<Record<string, string>> = {},
2010 ) {
2011 const result = yield* syncComputeEnvironmentInternal(projectId, cls, env, branchId, ownedIds);
2012 return {
2013 synced: result.synced,
2014 deleted: result.deleted,
2015 ownedIds: result.ownedIds,
2016 };
2017 });
2018
2019 const destroyComputeEnvironment = Effect.fn(function* (
2020 projectId: string,
2021 scope: ComputeEnvironmentScope,
2022 ownedIds: Readonly<Record<string, string>> = {},
2023 ) {
2024 const deleted: string[] = [];
2025 for (const [key, ownedId] of Object.entries(ownedIds)) {
2026 const variable = yield* findEnvironmentVariable(
2027 projectId,
2028 scope.class,
2029 key,
2030 scope.branchId,
2031 ).pipe(Effect.catchTag("NotFound", () => Effect.undefined));
2032 if (!variable) continue;
2033 if (variable.id !== ownedId || variable.isManagedBySystem) continue;
2034 yield* deleteEnvironmentVariable({
2035 envVarId: variable.id,
2036 }).pipe(Effect.catchTag("NotFound", () => Effect.void));
2037 deleted.push(key);
2038 }
2039 return { deleted };
2040 });
2041
2042 const cleanupRemovedComputeEnvironment = Effect.fn(function* (
2043 projectId: string,
2044 oldScope: ComputeEnvironmentScope,
2045 oldOwnedIds: Readonly<Record<string, string>>,
2046 newScope: ComputeEnvironmentScope,
2047 newEnv: Record<string, string | Redacted.Redacted<string> | null | undefined> | undefined,
2048 ) {
2049 const newValues = plainEnv(newEnv);
2050 const deleted: string[] = [];
2051 for (const [key, ownedId] of Object.entries(oldOwnedIds)) {
2052 if (sameEnvironmentScope(oldScope, newScope) && key in newValues) continue;
2053 const variable = yield* findEnvironmentVariable(
2054 projectId,
2055 oldScope.class,
2056 key,
2057 oldScope.branchId,
2058 );
2059 if (!variable) continue;
2060 if (variable.id !== ownedId || variable.isManagedBySystem) continue;
2061 yield* deleteEnvironmentVariable({
2062 envVarId: variable.id,
2063 }).pipe(Effect.catchTag("NotFound", () => Effect.void));
2064 deleted.push(key);
2065 }
2066 return { deleted };
2067 });
2068
2069 const startDev = Effect.fn(function* (id: string, props: ComputeProps) {
2070 const path = yield* Path.Path;
2071 const dev = props.dev;
2072 const processKey = `dev:${id}`;
2073 const localUrl =
2074 dev?.url ??
2075 ((dev?.port ?? props.port) ? `http://localhost:${dev?.port ?? props.port}` : undefined);
2076 if (!dev?.command) {
2077 return localUrl;
2078 }
2079
2080 yield* stopTrackedDevProcess(processKey);
2081
2082 const cwd = dev.cwd ? path.resolve(dev.cwd) : path.resolve(props.path ?? ".");
2083 const env = {
2084 NODE_ENV: "development",
2085 ...processEnv(props.env),
2086 ...processEnv(dev.env),
2087 ...((dev.port ?? props.port) ? { PORT: String(dev.port ?? props.port) } : {}),
2088 };
2089 const handle = yield* ChildProcess.make(dev.command, [], {
2090 shell: true,
2091 cwd,
2092 env,
2093 extendEnv: true,
2094 stdin: "ignore",
2095 stdout: "pipe",
2096 stderr: "pipe",
2097 detached: false,
2098 });
2099 // The dev server's output becomes log records instead of raw writes over
2100 // the CLI's renderer; each drain ends when the process does.
2101 for (const name of ["stdout", "stderr"] as const) {
2102 yield* handle[name].pipe(
2103 Stream.decodeText,
2104 Stream.splitLines,
2105 Stream.runForEach((line) => logChildLine(line, { stream: name })),
2106 Effect.ignore,
2107 Effect.forkDetach,
2108 );
2109 }
2110 devProcesses.set(processKey, handle);
2111 return localUrl;
2112 });
2113
2114 const activeBindingEnv = (
2115 bindings: ResourceBinding<Compute["Binding"]>[],
2116 ): Record<string, string | Redacted.Redacted<string> | null | undefined> =>
2117 bindings
2118 .filter(
2119 (binding: ResourceBinding<Compute["Binding"]> & { action?: string }) =>
2120 binding.action !== "delete",
2121 )
2122 .map((binding) => binding.data?.env)
2123 .reduce<Record<string, string | Redacted.Redacted<string> | null | undefined>>(
2124 (acc, env) => (env ? { ...acc, ...env } : acc),
2125 {} as Record<string, string | Redacted.Redacted<string> | null | undefined>,
2126 );
2127
2128 const ProviderLive = () =>
2129 Provider.effect(
2130 Compute,
2131 Effect.gen(function* () {
2132 return {
2133 stables: ["appId"],
2134 // Compute is a composite over App + Deployment. AppProvider owns nuke
2135 // enumeration to avoid deleting the same canonical App twice.
2136 list: () => Effect.succeed([]),
2137 diff: Effect.fn(function* ({ olds, news, output }) {
2138 if (!isInputObject(news)) return undefined;
2139 if (output?.local || isPrismaDevId(output?.appId)) {
2140 return { action: "update" } as const;
2141 }
2142 const oldProjectId = output?.projectId ?? unresolvedProjectIdOf(olds.project);
2143 const newProjectId = isResolved(news.project)
2144 ? unresolvedProjectIdOf(news.project)
2145 : undefined;
2146 if (concreteIdsChanged(oldProjectId, newProjectId)) {
2147 // A different project is a distinct API uniqueness scope, so the
2148 // old and replacement Apps can safely coexist.
2149 return { action: "replace" } as const;
2150 }
2151 if (isResolved(news.regionId) && news.regionId !== undefined) {
2152 const currentRegionId = output?.regionId ?? olds.regionId;
2153 if (currentRegionId !== undefined && news.regionId !== currentRegionId) {
2154 return yield* new ComputeInvalidProps({
2155 message: `Prisma Compute App region is immutable and cannot be changed atomically without deleting the live App first. Deploy a second Compute App under a different appName in the target region, cut traffic over, then remove the original.`,
2156 });
2157 }
2158 }
2159 // Source files/build output can change with no prop change, so
2160 // reconcile must rerun and decide from the computed artifact hash.
2161 return { action: "update" } as const;
2162 }),
2163 read: Effect.fn(function* ({ id, output, olds }) {
2164 if (output?.local) return output;
2165 const appId = output?.appId && !isPrismaDevId(output.appId) ? output.appId : undefined;
2166 const findAppInProject = Effect.gen(function* () {
2167 const projectId = unresolvedProjectIdOf(olds.project);
2168 return projectId
2169 ? yield* findApp(projectId, yield* createAppName(id, olds.appName), olds)
2170 : undefined;
2171 });
2172 const app = appId
2173 ? yield* getService({ serviceId: appId }).pipe(
2174 Effect.map((response) => response.data),
2175 Effect.catchTag("NotFound", () => Effect.undefined),
2176 )
2177 : yield* findAppInProject;
2178 if (!app) return undefined;
2179 const readDeployment = (id: string) =>
2180 observeDeployment(id).pipe(Effect.catchTag("NotFound", () => Effect.undefined));
2181 const outputDeployment = output?.deploymentId
2182 ? yield* readDeployment(output.deploymentId)
2183 : undefined;
2184 if (outputDeployment) {
2185 yield* ensureDeploymentMembership(app.id, outputDeployment, app.latestDeploymentId);
2186 }
2187 const latestDeployment =
2188 !outputDeployment && app.latestDeploymentId
2189 ? yield* readDeployment(app.latestDeploymentId)
2190 : undefined;
2191 const deployment = outputDeployment ?? latestDeployment;
2192 const deploymentUrl = toDeploymentUrl(deployment?.previewDomain ?? undefined);
2193 const appUrl = toDeploymentUrl(app.appEndpointDomain);
2194 const promoted =
2195 app.latestDeploymentId !== null && deployment?.id === app.latestDeploymentId;
2196 const attrs: Compute["Attributes"] = {
2197 appId: app.id,
2198 deploymentId: deployment?.id,
2199 projectId: app.projectId ?? output?.projectId,
2200 appName: app.name,
2201 regionId: app.region.id,
2202 deploymentEndpointDomain: deployment?.previewDomain ?? undefined,
2203 deploymentUrl,
2204 appEndpointDomain: app.appEndpointDomain ?? output?.appEndpointDomain,
2205 url: promoted ? (appUrl ?? deploymentUrl) : deploymentUrl,
2206 promoted,
2207 previousDeploymentId: output?.previousDeploymentId,
2208 previousDeploymentAction: output?.previousDeploymentAction,
2209 readinessStatus: output?.readinessStatus,
2210 pendingDeploymentCleanup: output?.pendingDeploymentCleanup,
2211 environmentKeys: output?.environmentKeys,
2212 environmentVariableIds: output?.environmentVariableIds,
2213 environmentClass: output?.environmentClass ?? olds.envClass,
2214 environmentBranchId: output?.environmentBranchId,
2215 // A latest-deployment fallback is unrelated to a missing saved
2216 // deployment. Never transfer its artifact identity to other code.
2217 artifactHash: outputDeployment ? output?.artifactHash : undefined,
2218 local: false,
2219 };
2220 return appId ? attrs : Unowned(attrs);
2221 }),
2222 reconcile: Effect.fn(function* ({ id, news, olds, output, bindings }) {
2223 const bindingEnv = activeBindingEnv(bindings);
2224 const effectiveNews = {
2225 ...news,
2226 appName: yield* createAppName(id, news.appName),
2227 env: {
2228 ...bindingEnv,
2229 ...news.env,
2230 },
2231 };
2232 yield* validateComputeProps(effectiveNews);
2233 const projectId = yield* resolveProjectId(effectiveNews.project);
2234 const artifact = yield* resolveArtifact(effectiveNews);
2235 const cleanupArtifact = artifact.file?.cleanup ?? Effect.void;
2236 const releaseArtifactOnFailure = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
2237 effect.pipe(
2238 Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : cleanupArtifact)),
2239 );
2240 const observedApp = effectiveNews.skipCodeUpload
2241 ? yield* releaseArtifactOnFailure(
2242 findExistingApp(output).pipe(
2243 Effect.retry({
2244 while: isAppProvisioningNotFound,
2245 schedule: projectConsistencySchedule,
2246 }),
2247 ),
2248 )
2249 : undefined;
2250 yield* releaseArtifactOnFailure(ensureSkipCodeUploadCanFork(effectiveNews, observedApp));
2251 const ensuredApp = yield* releaseArtifactOnFailure(
2252 ensureApp(projectId, effectiveNews, output, observedApp).pipe(
2253 Effect.retry({
2254 while: isAppProvisioningNotFound,
2255 schedule: projectConsistencySchedule,
2256 }),
2257 ),
2258 );
2259 let app = ensuredApp.app;
2260 let preserveCreatedAppOnFailure = false;
2261 const cleanupCreatedAppOnFailure = (error: unknown) =>
2262 ensuredApp.created && !preserveCreatedAppOnFailure
2263 ? destroyApp(app.id).pipe(
2264 Effect.mapError((cleanupError) =>
2265 aggregateCleanupFailure(
2266 "App",
2267 app.id,
2268 `/v1/services/${app.id}`,
2269 error,
2270 cleanupError,
2271 ),
2272 ),
2273 Effect.andThen(() => Effect.fail(error)),
2274 )
2275 : Effect.fail(error);
2276
2277 let createdEnvironmentVariableIds: Array<{
2278 key: string;
2279 id: string;
2280 }> = [];
2281 let deploymentConverged = false;
2282
2283 return yield* Effect.gen(function* () {
2284 const currentEnvironmentScope = yield* resolveComputeEnvironmentScope(
2285 app,
2286 effectiveNews,
2287 );
2288 const deploymentHash = yield* sha256Object({
2289 artifact: artifact.hash,
2290 branchId: app.branchId,
2291 environmentClass: currentEnvironmentScope.class,
2292 environmentBranchId: currentEnvironmentScope.branchId,
2293 });
2294 const outputArtifactHash = persistedArtifactHashValue(
2295 output?.artifactHash as Redacted.Redacted<string> | string | undefined,
2296 );
2297 const persistedDeployment = output?.deploymentId
2298 ? yield* observeDeployment(output.deploymentId).pipe(
2299 Effect.catchTag("NotFound", () => Effect.undefined),
2300 )
2301 : undefined;
2302 const terminalFailedDeploymentId =
2303 persistedDeployment?.status === "failed" ? persistedDeployment.id : undefined;
2304 const promotionRequested = !(effectiveNews.skipPromote ?? false);
2305 let persistedPendingCleanup = output?.pendingDeploymentCleanup;
2306 const cleanupPreviousDeployment = Effect.fn(function* (
2307 deploymentId: string,
2308 action: "stop" | "destroy",
2309 ) {
2310 const observed = yield* observeDeployment(deploymentId).pipe(
2311 Effect.catchTag("NotFound", () => Effect.undefined),
2312 );
2313 if (!observed) {
2314 return (action === "destroy" ? "destroyed" : "stopped") as "destroyed" | "stopped";
2315 }
2316 yield* ensureDeploymentMembership(app.id, observed, app.latestDeploymentId);
2317 if (action === "destroy") {
2318 yield* destroyDeployment(deploymentId, effectiveNews);
2319 return "destroyed" as const;
2320 }
2321 yield* stopDeploymentIdempotent(deploymentId).pipe(
2322 Effect.catchTag("NotFound", () => Effect.void),
2323 );
2324 yield* waitForDeploymentStatus(deploymentId, "stopped", effectiveNews).pipe(
2325 Effect.catchTag("NotFound", () => Effect.undefined),
2326 );
2327 return "stopped" as const;
2328 });
2329
2330 if (
2331 terminalFailedDeploymentId !== undefined &&
2332 promotionRequested &&
2333 output?.promoted === true &&
2334 app.latestDeploymentId !== null &&
2335 app.latestDeploymentId !== terminalFailedDeploymentId
2336 ) {
2337 return yield* Effect.fail(
2338 new AggregateError(
2339 [],
2340 `Prisma Compute state preserves terminal failed deployment '${terminalFailedDeploymentId}', but App '${app.id}' reports deployment '${app.latestDeploymentId}' as latest. Alchemy cannot prove that the live deployment is the interrupted replacement, and the persisted failed deployment is not a safe rollback target. No new deployment was created and neither deployment was deleted.`,
2341 ),
2342 );
2343 }
2344
2345 // Apply persists the previous stable Attributes before reconcile.
2346 // If a prior attempt promoted a new generation, failed its stable
2347 // health check, and could not roll back, that durable output still
2348 // identifies the deployment we must restore while the App points
2349 // at the displaced unhealthy generation. Recover that transition
2350 // before changing env or creating another deployment, otherwise a
2351 // retry would use the unhealthy generation as its rollback target.
2352 if (
2353 promotionRequested &&
2354 output?.promoted === true &&
2355 output.deploymentId !== undefined &&
2356 terminalFailedDeploymentId === undefined &&
2357 outputArtifactHash !== deploymentHash &&
2358 app.latestDeploymentId !== null &&
2359 app.latestDeploymentId !== output.deploymentId
2360 ) {
2361 const persistedDeploymentId = output.deploymentId;
2362 const displacedDeploymentId = app.latestDeploymentId;
2363 const rollback = yield* createServiceRollback({
2364 serviceId: app.id,
2365 deploymentId: persistedDeploymentId,
2366 }).pipe(
2367 Effect.map((response) => response.data),
2368 Effect.result,
2369 );
2370 const observedAfterRollback = yield* waitForAppDeploymentTarget(
2371 app.id,
2372 persistedDeploymentId,
2373 effectiveNews,
2374 ).pipe(Effect.result);
2375
2376 if (Result.isFailure(observedAfterRollback)) {
2377 return yield* Effect.fail(
2378 new AggregateError(
2379 [
2380 ...(Result.isFailure(rollback) ? [rollback.failure] : []),
2381 ...(Result.isFailure(observedAfterRollback)
2382 ? [observedAfterRollback.failure]
2383 : []),
2384 ],
2385 `Prisma App '${app.id}' has live deployment '${displacedDeploymentId}', while Alchemy state preserves deployment '${persistedDeploymentId}' as the prior promoted generation. Recovery via POST /v1/services/${app.id}/rollback did not converge, so no environment variables or new deployment were changed and neither deployment was deleted.`,
2386 ),
2387 );
2388 }
2389
2390 app = observedAfterRollback.success;
2391 yield* destroyDeployment(displacedDeploymentId, effectiveNews).pipe(
2392 Effect.mapError(
2393 (cleanupError) =>
2394 new AggregateError(
2395 [...(Result.isFailure(rollback) ? [rollback.failure] : []), cleanupError],
2396 `Prisma App '${app.id}' was restored to deployment '${persistedDeploymentId}', but displaced deployment '${displacedDeploymentId}' could not be deleted. No new deployment was created; retry cleanup with DELETE /v1/deployments/${displacedDeploymentId}.`,
2397 ),
2398 ),
2399 );
2400 }
2401
2402 if (output?.readinessStatus === "pending" && outputArtifactHash !== deploymentHash) {
2403 return yield* new ComputeNotReady({
2404 message: `Prisma Compute deployment '${output.deploymentId ?? "unknown"}' still has pending stable-endpoint readiness. Reconcile the existing generation before changing code or environment inputs.`,
2405 });
2406 }
2407 // Keep one cleanup candidate. A non-live older candidate is
2408 // drained before any env/deploy mutation; a candidate that is
2409 // still live is derived from app.latestDeploymentId below.
2410 if (
2411 persistedPendingCleanup !== undefined &&
2412 output?.readinessStatus !== "pending" &&
2413 persistedPendingCleanup.deploymentId !== app.latestDeploymentId
2414 ) {
2415 yield* cleanupPreviousDeployment(
2416 persistedPendingCleanup.deploymentId,
2417 persistedPendingCleanup.action,
2418 );
2419 persistedPendingCleanup = undefined;
2420 } else if (persistedPendingCleanup?.deploymentId === app.latestDeploymentId) {
2421 persistedPendingCleanup = undefined;
2422 }
2423 const previousEnvironmentScope = environmentScope(
2424 olds?.envClass ?? output?.environmentClass ?? "production",
2425 output?.environmentBranchId,
2426 );
2427 const previousEnvironmentVariableIds = output?.environmentVariableIds ?? {};
2428 const environmentResult = yield* syncComputeEnvironmentInternal(
2429 projectId,
2430 currentEnvironmentScope.class,
2431 effectiveNews.env,
2432 currentEnvironmentScope.branchId,
2433 sameEnvironmentScope(previousEnvironmentScope, currentEnvironmentScope)
2434 ? previousEnvironmentVariableIds
2435 : {},
2436 );
2437 createdEnvironmentVariableIds = environmentResult.createdIds;
2438
2439 // Deployment creation snapshots the App branch environment. Remove
2440 // formerly-owned keys before creating it so deleted keys cannot be
2441 // captured into the new runtime. Any failure here happens before
2442 // deployment creation and rolls back newly-created variables.
2443 yield* cleanupRemovedComputeEnvironment(
2444 projectId,
2445 previousEnvironmentScope,
2446 previousEnvironmentVariableIds,
2447 currentEnvironmentScope,
2448 effectiveNews.env,
2449 );
2450
2451 let deployment: ObservedDeployment | undefined =
2452 outputArtifactHash === deploymentHash ? persistedDeployment : undefined;
2453 // A failed deployment is terminal and cannot be repaired by
2454 // replaying start/promotion. Preserve it as the cleanup target,
2455 // but create a fresh generation and do not delete the failed one
2456 // until the replacement has passed preview + stable readiness and
2457 // promotion is observed.
2458 if (
2459 persistedDeployment !== undefined &&
2460 (deployment !== undefined || terminalFailedDeploymentId !== undefined)
2461 ) {
2462 yield* ensureDeploymentMembership(
2463 app.id,
2464 persistedDeployment,
2465 app.latestDeploymentId,
2466 );
2467 }
2468 if (terminalFailedDeploymentId !== undefined) {
2469 deployment = undefined;
2470 }
2471 let createdDeploymentId: string | undefined;
2472 const cleanupCreatedDeploymentOnFailure = (
2473 failedDeploymentId: string,
2474 error: unknown,
2475 ) =>
2476 createdDeploymentId === failedDeploymentId
2477 ? destroyDeployment(failedDeploymentId, effectiveNews).pipe(
2478 Effect.mapError((cleanupError) =>
2479 aggregateCleanupFailure(
2480 "deployment",
2481 failedDeploymentId,
2482 `/v1/deployments/${failedDeploymentId}`,
2483 error,
2484 cleanupError,
2485 ),
2486 ),
2487 Effect.andThen(() => Effect.fail(error)),
2488 )
2489 : Effect.fail(error);
2490
2491 if (!deployment) {
2492 const created = yield* createServiceDeployment({
2493 serviceId: app.id,
2494 portMapping: { http: artifact.port },
2495 ...(effectiveNews.skipCodeUpload === undefined
2496 ? {}
2497 : { skipCodeUpload: effectiveNews.skipCodeUpload }),
2498 }).pipe(
2499 // A replayed create would make a second deployment; the retry
2500 // policy cannot see the request, so opt out explicitly.
2501 Retry.none,
2502 Effect.map((response) => response.data),
2503 );
2504 createdDeploymentId = created.id;
2505 if (artifact.file !== undefined && !created.uploadUrl) {
2506 return yield* cleanupCreatedDeploymentOnFailure(
2507 created.id,
2508 new Error("Prisma deployment creation did not return an upload URL."),
2509 );
2510 }
2511 if (created.uploadUrl && artifact.file !== undefined) {
2512 yield* uploadArtifact(created.uploadUrl, artifact.file, "application/gzip").pipe(
2513 Effect.catch((error) => cleanupCreatedDeploymentOnFailure(created.id, error)),
2514 );
2515 }
2516 deployment = yield* observeDeployment(created.id).pipe(
2517 Effect.catchTag("NotFound", () =>
2518 Effect.succeed({
2519 id: created.id,
2520 foundryVersionId: created.foundryVersionId,
2521 status: "new",
2522 previewDomain: null,
2523 createdAt: undefined,
2524 }),
2525 ),
2526 Effect.catch((error) => cleanupCreatedDeploymentOnFailure(created.id, error)),
2527 );
2528 }
2529 if (!deployment) {
2530 return yield* new ComputeUnexpectedResponse({
2531 message: "Prisma deployment could not be resolved after creation.",
2532 });
2533 }
2534
2535 const previousDeploymentId =
2536 terminalFailedDeploymentId ??
2537 persistedPendingCleanup?.deploymentId ??
2538 (app.latestDeploymentId !== null && app.latestDeploymentId !== deployment.id
2539 ? app.latestDeploymentId
2540 : null);
2541 const rollbackDeploymentId =
2542 previousDeploymentId === terminalFailedDeploymentId ? null : previousDeploymentId;
2543
2544 if (effectiveNews.start ?? true) {
2545 const currentDeployment = deployment;
2546 const currentDeploymentId = currentDeployment.id;
2547 deployment = yield* Effect.gen(function* () {
2548 if (
2549 currentDeployment.status !== "running" &&
2550 currentDeployment.status !== "provisioning"
2551 ) {
2552 yield* startDeploymentIdempotent(currentDeployment.id);
2553 }
2554 const running = yield* waitForDeploymentStatus(
2555 currentDeployment.id,
2556 "running",
2557 effectiveNews,
2558 );
2559 yield* waitForDeploymentUrl(toDeploymentUrl(running.previewDomain), effectiveNews);
2560 return running;
2561 }).pipe(
2562 Effect.catch((error) =>
2563 cleanupCreatedDeploymentOnFailure(currentDeploymentId, error),
2564 ),
2565 );
2566 }
2567
2568 let appEndpointDomain = app.appEndpointDomain;
2569 let previousDeploymentAction: "stopped" | "destroyed" | "still-active" | null =
2570 previousDeploymentId ? "still-active" : null;
2571 let promoted = app.latestDeploymentId === deployment.id;
2572 if (promotionRequested) {
2573 // Replay promotion even when latestDeploymentId already matches.
2574 // Promotion also repairs endpoint/custom-domain routing drift.
2575 preserveCreatedAppOnFailure = true;
2576 const promotedApp = yield* promoteAppObserved(app.id, deployment.id, effectiveNews);
2577 appEndpointDomain = promotedApp.appEndpointDomain;
2578 promoted = true;
2579 }
2580
2581 const deploymentUrl = toDeploymentUrl(deployment.previewDomain);
2582 const appUrl =
2583 toDeploymentUrl(appEndpointDomain) ?? toDeploymentUrl(deployment.previewDomain);
2584 let readinessStatus: "ready" | "pending" | "skipped" = "skipped";
2585 if (promoted && effectiveNews.verifyUrl !== false) {
2586 const readiness = yield* waitForDeploymentUrl(appUrl, effectiveNews).pipe(
2587 Effect.result,
2588 );
2589 if (Result.isSuccess(readiness)) {
2590 readinessStatus = "ready";
2591 } else if (rollbackDeploymentId) {
2592 const rollback = yield* createServiceRollback({
2593 serviceId: app.id,
2594 deploymentId: rollbackDeploymentId,
2595 }).pipe(
2596 Effect.map((response) => response.data),
2597 Effect.result,
2598 );
2599 const observedAfterRollback = yield* waitForAppDeploymentTarget(
2600 app.id,
2601 rollbackDeploymentId,
2602 effectiveNews,
2603 ).pipe(Effect.result);
2604 if (Result.isSuccess(observedAfterRollback)) {
2605 return yield* cleanupCreatedDeploymentOnFailure(
2606 deployment.id,
2607 Result.isSuccess(rollback)
2608 ? readiness.failure
2609 : new AggregateError(
2610 [readiness.failure, rollback.failure],
2611 `Prisma App '${app.id}' endpoint was restored to deployment '${rollbackDeploymentId}', but the rollback response was lost.`,
2612 ),
2613 );
2614 }
2615
2616 return yield* Effect.fail(
2617 new AggregateError(
2618 [
2619 readiness.failure,
2620 ...(Result.isFailure(rollback) ? [rollback.failure] : []),
2621 observedAfterRollback.failure,
2622 ],
2623 `Prisma App '${app.id}' promoted deployment '${deployment.id}', but its stable endpoint failed readiness and rollback to deployment '${rollbackDeploymentId}' did not converge. Alchemy preserved the prior deployment in state and deleted neither deployment; the next reconcile will retry recovery via POST /v1/services/${app.id}/rollback before making any new cloud changes.`,
2624 ),
2625 );
2626 } else {
2627 // A first deployment has no safe rollback target. Never report
2628 // a successful stack deployment while the production endpoint
2629 // is unreachable. A newly created App can be fully cleaned up;
2630 // a pre-existing App is preserved for observed-state recovery.
2631 if (ensuredApp.created) {
2632 preserveCreatedAppOnFailure = false;
2633 } else {
2634 deploymentConverged = true;
2635 }
2636 if (terminalFailedDeploymentId !== undefined) {
2637 return yield* Effect.fail(
2638 new AggregateError(
2639 [readiness.failure],
2640 `Prisma App '${app.id}' promoted replacement deployment '${deployment.id}', but stable readiness failed and persisted deployment '${terminalFailedDeploymentId}' is terminal failed, so no safe rollback target exists. Neither deployment was deleted; a retry will refuse to create another generation while the live target differs from persisted state.`,
2641 ),
2642 );
2643 }
2644 return yield* Effect.fail(readiness.failure);
2645 }
2646 }
2647
2648 deploymentConverged = true;
2649 let pendingDeploymentCleanup =
2650 promoted && previousDeploymentId && previousDeploymentId !== deployment.id
2651 ? {
2652 deploymentId: previousDeploymentId,
2653 action:
2654 persistedPendingCleanup?.deploymentId === previousDeploymentId
2655 ? persistedPendingCleanup.action
2656 : previousDeploymentId === terminalFailedDeploymentId
2657 ? ("destroy" as const)
2658 : effectiveNews.destroyOldDeployment
2659 ? ("destroy" as const)
2660 : ("stop" as const),
2661 }
2662 : undefined;
2663 if (promoted && pendingDeploymentCleanup) {
2664 const cleanup = yield* cleanupPreviousDeployment(
2665 pendingDeploymentCleanup.deploymentId,
2666 pendingDeploymentCleanup.action,
2667 ).pipe(Effect.result);
2668 if (Result.isSuccess(cleanup)) {
2669 previousDeploymentAction = cleanup.success;
2670 pendingDeploymentCleanup = undefined;
2671 } else {
2672 yield* Effect.logWarning(
2673 `Prisma deployment '${pendingDeploymentCleanup.deploymentId}' cleanup is pending and will be retried before another Compute generation is created.`,
2674 );
2675 }
2676 }
2677
2678 return {
2679 appId: app.id,
2680 deploymentId: deployment.id,
2681 projectId,
2682 appName: app.name,
2683 regionId: app.region.id,
2684 deploymentEndpointDomain: deployment.previewDomain ?? undefined,
2685 deploymentUrl,
2686 appEndpointDomain,
2687 url: promoted ? appUrl : deploymentUrl,
2688 promoted,
2689 previousDeploymentId,
2690 previousDeploymentAction,
2691 readinessStatus,
2692 pendingDeploymentCleanup,
2693 environmentKeys: managedEnvKeys(effectiveNews.env),
2694 environmentVariableIds: environmentResult.ownedIds,
2695 environmentClass: currentEnvironmentScope.class,
2696 environmentBranchId: currentEnvironmentScope.branchId,
2697 artifactHash: Redacted.make(deploymentHash),
2698 local: false,
2699 };
2700 }).pipe(
2701 Effect.catch((error) =>
2702 deploymentConverged
2703 ? Effect.fail(error)
2704 : rollbackCreatedEnvironmentVariables(createdEnvironmentVariableIds, error),
2705 ),
2706 Effect.catch(cleanupCreatedAppOnFailure),
2707 Effect.ensuring(cleanupArtifact),
2708 );
2709 }),
2710 delete: Effect.fn(function* ({ olds, output }) {
2711 if (output.local || isPrismaDevId(output.appId)) {
2712 yield* stopTrackedDevProcess(output.appId);
2713 return;
2714 }
2715 yield* destroyComputeEnvironment(
2716 output.projectId,
2717 environmentScope(
2718 olds?.envClass ?? output.environmentClass ?? "production",
2719 output.environmentBranchId,
2720 ),
2721 output.environmentVariableIds,
2722 );
2723 yield* destroyApp(output.appId);
2724 }),
2725 tail: ({ output }) =>
2726 output.deploymentId ? tailDeploymentLogs(output.deploymentId) : Stream.empty,
2727 };
2728 }),
2729 );
2730
2731 export const ComputeDevProvider = () =>
2732 Provider.effect(
2733 Compute,
2734 Effect.gen(function* () {
2735 const ctx = yield* AlchemyContext;
2736 return {
2737 stables: ["appId"],
2738 list: () => Effect.succeed([]),
2739 diff: Effect.fn(function* () {
2740 return { action: "update" } as const;
2741 }),
2742 read: Effect.fn(function* ({ output }) {
2743 return output?.local ? output : undefined;
2744 }),
2745 reconcile: Effect.fn(function* ({ id, news, output, bindings }) {
2746 const bindingEnv = activeBindingEnv(bindings);
2747 const effectiveNews = {
2748 ...news,
2749 env: {
2750 ...bindingEnv,
2751 ...news.env,
2752 },
2753 };
2754 yield* validateComputeProps(effectiveNews);
2755 const projectId = yield* resolveProjectId(effectiveNews.project);
2756 if (!ctx.dev) {
2757 return yield* new ComputeOperationFailed({
2758 message: "ComputeDevProvider requires Alchemy dev mode.",
2759 });
2760 }
2761 const localUrl = yield* startDev(id, effectiveNews);
2762 return {
2763 appId: output?.appId ?? `dev:${id}`,
2764 deploymentId: undefined,
2765 projectId,
2766 appName: effectiveNews.appName ?? id,
2767 regionId: effectiveNews.regionId ?? "us-east-1",
2768 deploymentEndpointDomain: localUrl,
2769 deploymentUrl: localUrl,
2770 appEndpointDomain: localUrl,
2771 url: localUrl,
2772 promoted: false,
2773 previousDeploymentId: undefined,
2774 previousDeploymentAction: undefined,
2775 readinessStatus: "skipped",
2776 pendingDeploymentCleanup: undefined,
2777 environmentKeys: managedEnvKeys(effectiveNews.env),
2778 environmentVariableIds: {},
2779 environmentClass: effectiveNews.envClass ?? "production",
2780 environmentBranchId: null,
2781 artifactHash: undefined,
2782 local: true,
2783 };
2784 }),
2785 delete: Effect.fn(function* ({ output }) {
2786 yield* stopTrackedDevProcess(output.appId);
2787 }),
2788 };
2789 }),
2790 );
2791
2792 export const ComputeProvider = () =>
2793 ProviderLayer.dual(Compute, {
2794 local: () => ComputeDevProvider(),
2795 live: () => ProviderLive(),
2796 });