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

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

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

Synced Nov 21, 04:45 UTC

main
ts 785 lines 29.7 KB
Raw
1 import { Retry } from "@distilled.cloud/prisma";
2 import {
3 type GetServiceDeploymentsResponse,
4 getServiceDeployments,
5 createServiceDeployment,
6 } from "@distilled.cloud/prisma/management";
7 import { deepEqual, isResolved } from "alchemy/Diff";
8 import * as ProviderLayer from "alchemy/Local/ProviderLayer";
9 import * as Provider from "alchemy/Provider";
10 import { Resource } from "alchemy/Resource";
11 import { sha256Object } from "alchemy/Util/sha256";
12 import * as Data from "effect/Data";
13 import * as Effect from "effect/Effect";
14 import * as Path from "effect/Path";
15 import * as Redacted from "effect/Redacted";
16 import * as Stream from "effect/Stream";
17 import type { App } from "./App.ts";
18 import {
19 destroyDeployment,
20 PrismaDeploymentWaitTimeout,
21 waitForDeploymentStatus,
22 } from "./ComputeLifecycle.ts";
23 import { promoteAppObserved } from "./internal/AppPromotion.ts";
24 import {
25 inspectArtifactFile,
26 readArtifactFile,
27 type ArtifactFile,
28 } from "./internal/ArtifactFile.ts";
29 import { executeArtifactUpload } from "./internal/ArtifactUpload.ts";
30 import { aggregateCleanupFailure } from "./internal/CleanupFailure.ts";
31 import { startDeploymentIdempotent } from "./internal/DeploymentActions.ts";
32 import { ensureDeploymentMembership } from "./internal/DeploymentIdentity.ts";
33 import { observeDeployment } from "./internal/DeploymentObserve.ts";
34 import { DEV_TIMESTAMP, attrOrString, devId, devProvider } from "./internal/DevStub.ts";
35 import type { ObservedDeployment } from "./internal/Observed.ts";
36 import { PrismaPaginationError } from "./internal/Pagination.ts";
37 import {
38 concreteIdsChanged,
39 isInputObject,
40 isPrismaDevId,
41 resolveAppId,
42 unresolvedAppIdOf,
43 } from "./internal/Refs.ts";
44 import { tailDeploymentLogs } from "./PrismaLogs.ts";
45 import type { Providers } from "./Providers.ts";
46
47 export class DeploymentConflict extends Data.TaggedError("DeploymentConflict")<{
48 readonly message: string;
49 readonly cause?: unknown;
50 }> {}
51
52 export class DeploymentInvalidProps extends Data.TaggedError("DeploymentInvalidProps")<{
53 readonly message: string;
54 readonly cause?: unknown;
55 }> {}
56
57 export class DeploymentOperationFailed extends Data.TaggedError("DeploymentOperationFailed")<{
58 readonly message: string;
59 readonly cause?: unknown;
60 }> {}
61
62 export class DeploymentUnexpectedResponse extends Data.TaggedError("DeploymentUnexpectedResponse")<{
63 readonly message: string;
64 readonly cause?: unknown;
65 }> {}
66
67 export const MAX_DEPLOYMENT_ARTIFACT_BYTES = 768 * 1024 * 1024;
68
69 export interface DeploymentProps {
70 /**
71 * App ID or Prisma.App resource that owns this deployment.
72 */
73 app: string | App;
74 /**
75 * Port mapping for the deployment. Set `http` to `null` to reset to
76 * Foundry's default port (8080); non-null values must be integers from
77 * 1 through 65535.
78 */
79 portMapping?: { http?: number | null };
80 /**
81 * Create the deployment by reusing the App's currently promoted artifact
82 * instead of uploading code. Requires an existing promoted deployment.
83 */
84 skipCodeUpload?: boolean;
85 /**
86 * Path to a pre-created artifact file to upload to the pre-signed upload URL.
87 */
88 artifactPath?: string;
89 /**
90 * Content type for artifact uploads.
91 *
92 * @default "application/octet-stream"
93 */
94 artifactContentType?: string;
95 /**
96 * Start the deployment after it is created.
97 *
98 * @default false
99 */
100 start?: boolean;
101 /**
102 * Promote the deployment to the App's stable endpoint after start.
103 * If `start` is omitted, enabling promotion starts the deployment first.
104 *
105 * @default false
106 */
107 promote?: boolean;
108 /**
109 * Opaque key/value map; when any resolved value changes, a replacement
110 * deployment is planned (create-before-delete) even if the artifact is
111 * unchanged — the same contract as `AWS.ApiGateway.Deployment.triggers`.
112 * Because values here may be secrets, they are folded into the deployment
113 * fingerprint as a salted hash and persisted `Redacted` rather than
114 * compared as plaintext; plaintext never lands in state.
115 *
116 * Prisma snapshots environment variables into a deployment when the
117 * deployment is created, so changing only an environment variable's value
118 * updates the platform's variable record but never reaches the running app.
119 * Pass those values here to make such a change take effect.
120 *
121 * Members may be wrapped in `Redacted.make(secret)`; they are unwrapped only
122 * to compute the fingerprint.
123 *
124 * If the value cannot be resolved while the deploy is being planned —
125 * because it reads an attribute of another resource that the same deploy is
126 * changing — the diff cannot prove the fingerprint is unchanged, and the
127 * engine offers no later opportunity to plan a replacement. The deployment
128 * is then replaced conservatively, but only once a fingerprint has already
129 * been recorded: adding `triggers` to an existing deployment records its
130 * fingerprint through a plain update rather than forcing a replacement.
131 *
132 * Leaving `triggers` unset tracks nothing, so removing it from a
133 * deployment that had it does not trigger a replacement on its own.
134 *
135 * @example
136 * ```typescript
137 * const deployment = yield* Prisma.Deployment("web", {
138 * app,
139 * artifactPath: "./dist/app.tar.gz",
140 * triggers: { DATABASE_URL: Redacted.make(databaseUrl) },
141 * start: true,
142 * promote: true,
143 * });
144 * ```
145 */
146 triggers?: Record<string, unknown>;
147 }
148
149 export interface Deployment extends Resource<
150 "Prisma.Deployment",
151 DeploymentProps,
152 {
153 /**
154 * Prisma deployment ID.
155 */
156 deploymentId: string;
157 /**
158 * App ID that owns the deployment.
159 */
160 appId: string;
161 /**
162 * Foundry version ID returned by the Prisma Management API.
163 */
164 foundryVersionId: string;
165 /**
166 * Current deployment status, when observed.
167 */
168 status: string | undefined;
169 /**
170 * Preview endpoint domain for the deployment.
171 */
172 previewDomain: string | null | undefined;
173 /**
174 * Hash of the artifact bytes uploaded for this deployment, when Alchemy
175 * uploaded an artifact.
176 */
177 artifactHash?: string;
178 /**
179 * Salted fingerprint of the resolved `triggers` inputs this deployment
180 * was created for. Held `Redacted` so the inputs stay out of plaintext
181 * state; absent when `triggers` is unset.
182 */
183 triggersHash?: Redacted.Redacted<string>;
184 /**
185 * Stable App endpoint domain after promotion.
186 */
187 appEndpointDomain: string | undefined;
188 /**
189 * ISO timestamp when the deployment was created, when observed.
190 */
191 createdAt: string | undefined;
192 },
193 never,
194 Providers
195 > {}
196
197 /**
198 * A Prisma deployment owned by an App.
199 *
200 * This is the low-level resource: it can upload or reuse an artifact, start it,
201 * and promote it, but it does not provide `Prisma.Compute`'s preview/stable
202 * health checks or automatic rollback. Prefer `Prisma.Compute` for production
203 * application deployments.
204 *
205 * Prisma's create-deployment API currently exposes neither an idempotency key
206 * nor a caller-defined natural key. After a crash that loses state immediately
207 * after creation, Alchemy deliberately does not adopt the App's latest
208 * deployment: doing so could take ownership of an unrelated deployment. When
209 * persisted state contains a Foundry version ID, refresh may safely recover the
210 * matching deployment.
211 *
212 * ### Creating a Deployment
213 * **Example:** Fork the currently promoted artifact
214 * ```typescript
215 * const deployment = yield* Prisma.Deployment("web-v2", {
216 * app: app.appId,
217 * skipCodeUpload: true,
218 * start: true,
219 * promote: true,
220 * });
221 * ```
222 *
223 * **Example:** Upload a prebuilt artifact
224 * ```typescript
225 * const deployment = yield* Prisma.Deployment("web-v3", {
226 * app: app.appId,
227 * artifactPath: "./dist/app.tar.gz",
228 * artifactContentType: "application/gzip",
229 * start: true,
230 * promote: true,
231 * });
232 * ```
233 *
234 * @resource
235 * @product Compute
236 */
237 export const Deployment = Resource<Deployment>("Prisma.Deployment");
238
239 // Distilled emits the cursor-paginated list operations as plain ops, so
240 // callers walk `pagination` themselves (see `src/Neon/Project.ts`).
241 const listAppDeployments = (appId: string) =>
242 Effect.gen(function* () {
243 const deployments: GetServiceDeploymentsResponse["data"][number][] = [];
244 let cursor: string | undefined;
245 while (true) {
246 const page = yield* getServiceDeployments(
247 cursor === undefined
248 ? { serviceId: appId, limit: 100 }
249 : { serviceId: appId, limit: 100, cursor },
250 );
251 deployments.push(...page.data);
252 const nextCursor = page.pagination.nextCursor;
253 if (!page.pagination.hasMore) break;
254 if (nextCursor === null) {
255 return yield* new PrismaPaginationError({
256 message:
257 "Invalid Prisma Management API pagination response from getServiceDeployments: hasMore was true without a non-empty nextCursor",
258 });
259 }
260 cursor = nextCursor;
261 }
262 return deployments;
263 });
264
265 const findDeployment = (appId: string, foundryVersionId: string | undefined) =>
266 foundryVersionId === undefined
267 ? Effect.undefined
268 : listAppDeployments(appId).pipe(
269 Effect.flatMap((deployments) => {
270 const matches = deployments.filter(
271 (deployment) => deployment.foundryVersionId === foundryVersionId,
272 );
273 return matches.length > 1
274 ? Effect.fail(
275 new DeploymentConflict({
276 message: `Prisma returned multiple deployments with Foundry version ID '${foundryVersionId}' for App '${appId}'; refusing an ambiguous recovery match.`,
277 }),
278 )
279 : Effect.succeed(matches[0]);
280 }),
281 );
282
283 const attrsFrom = (
284 deployment: ObservedDeployment,
285 appId: string,
286 extra?: {
287 artifactHash?: string;
288 triggersHash?: Redacted.Redacted<string>;
289 appEndpointDomain?: string;
290 },
291 ): Deployment["Attributes"] => ({
292 deploymentId: deployment.id,
293 appId,
294 foundryVersionId: deployment.foundryVersionId,
295 status: deployment.status,
296 previewDomain: deployment.previewDomain,
297 artifactHash: extra?.artifactHash,
298 triggersHash: extra?.triggersHash,
299 appEndpointDomain: extra?.appEndpointDomain,
300 createdAt: deployment.createdAt,
301 });
302
303 export class InvalidArtifactUploadUrlError extends Data.TaggedError(
304 "InvalidArtifactUploadUrlError",
305 )<{
306 readonly message: string;
307 readonly cause?: unknown;
308 }> {}
309
310 export interface ReadUploadArtifactInput {
311 artifact?: string | Uint8Array;
312 artifactPath?: string;
313 output?: "bytes" | "file";
314 }
315
316 export function readUploadArtifact(
317 input: ReadUploadArtifactInput & { readonly output: "file" },
318 ): Effect.Effect<ArtifactFile | undefined, Error, Path.Path>;
319 export function readUploadArtifact(
320 input: ReadUploadArtifactInput & { readonly output?: "bytes" },
321 ): Effect.Effect<Uint8Array | undefined, Error, Path.Path>;
322 export function readUploadArtifact(
323 input: ReadUploadArtifactInput,
324 ): Effect.Effect<Uint8Array | ArtifactFile | undefined, Error, Path.Path>;
325 export function readUploadArtifact(input: ReadUploadArtifactInput) {
326 return readUploadArtifactInternal(input);
327 }
328
329 const readUploadArtifactInternal = Effect.fn(function* (input: ReadUploadArtifactInput) {
330 if (input.artifact !== undefined && input.artifactPath !== undefined) {
331 return yield* new DeploymentInvalidProps({
332 message: "artifact and artifactPath are mutually exclusive.",
333 });
334 }
335 if (input.output === "file" && input.artifact !== undefined) {
336 return yield* new DeploymentInvalidProps({
337 message: "File-backed artifact output requires artifactPath.",
338 });
339 }
340 if (input.artifactPath !== undefined) {
341 const path = yield* Path.Path;
342 const resolved = path.resolve(input.artifactPath);
343 const artifact = yield* inspectArtifactFile(resolved, MAX_DEPLOYMENT_ARTIFACT_BYTES);
344 if (input.output === "file") {
345 return artifact;
346 }
347 return yield* readArtifactFile(artifact);
348 }
349 if (input.artifact !== undefined) {
350 const artifact = input.artifact;
351 const bytes = yield* Effect.sync(() =>
352 typeof artifact === "string" ? new TextEncoder().encode(artifact) : artifact,
353 );
354 return yield* validateDeploymentArtifactBytes(bytes);
355 }
356 return undefined;
357 });
358
359 export const validateDeploymentArtifactBytes = (
360 artifact: Uint8Array,
361 maxBytes = MAX_DEPLOYMENT_ARTIFACT_BYTES,
362 ) =>
363 !Number.isSafeInteger(maxBytes) || maxBytes <= 0
364 ? Effect.fail(
365 new DeploymentInvalidProps({
366 message: "Artifact maxBytes must be a positive safe integer.",
367 }),
368 )
369 : maxBytes > MAX_DEPLOYMENT_ARTIFACT_BYTES
370 ? Effect.fail(
371 new DeploymentInvalidProps({
372 message: `Artifact maxBytes must not exceed the hard limit of ${MAX_DEPLOYMENT_ARTIFACT_BYTES}.`,
373 }),
374 )
375 : artifact.byteLength === 0
376 ? Effect.fail(
377 new DeploymentInvalidProps({
378 message: "Prisma deployment artifact must be non-empty.",
379 }),
380 )
381 : artifact.byteLength > maxBytes
382 ? Effect.fail(
383 new DeploymentInvalidProps({
384 message: `Prisma deployment artifact exceeds the ${maxBytes} byte upload safety limit.`,
385 }),
386 )
387 : Effect.succeed(artifact);
388
389 const artifactHashOf = Effect.fn(function* (props: DeploymentProps) {
390 const artifact = yield* readUploadArtifact({
391 artifactPath: props.artifactPath,
392 output: "file",
393 });
394 if (artifact === undefined) return undefined;
395 return yield* sha256Object({
396 artifact: artifact.sha256,
397 contentType: props.artifactContentType ?? "application/octet-stream",
398 });
399 });
400
401 /**
402 * Domain separator so a `triggers` fingerprint is never the bare SHA-256 of
403 * a secret value, which would otherwise be comparable against a precomputed
404 * digest of a guessed value.
405 */
406 const TRIGGERS_HASH_SALT = "alchemy/Prisma.Deployment/triggers/v1";
407
408 const unwrapRedacted = (value: unknown): unknown => {
409 if (Redacted.isRedacted(value)) return value.pipe(Redacted.value, unwrapRedacted);
410 if (Array.isArray(value)) return value.map(unwrapRedacted);
411 if (value !== null && typeof value === "object") {
412 return Object.fromEntries(
413 Object.entries(value).map(([key, item]) => [key, unwrapRedacted(item)]),
414 );
415 }
416 return value;
417 };
418
419 const triggersHashOf = (triggers: unknown) =>
420 sha256Object({
421 salt: TRIGGERS_HASH_SALT,
422 triggers: unwrapRedacted(triggers) ?? null,
423 });
424
425 const persistedTriggersHash = (value: Redacted.Redacted<string> | string | undefined) =>
426 Redacted.isRedacted(value) ? Redacted.value(value) : value;
427
428 /**
429 * Whether the declared `triggers` inputs differ from the fingerprint the
430 * running deployment was created for.
431 *
432 * Only `diff` can plan a replacement — `reconcile` has no way to ask for one —
433 * so an input that is still unresolved while planning is treated as changed.
434 * That is only reached when another resource in the same deploy owns the
435 * value and is itself changing, in which case the value most likely changed
436 * too; the cost of being wrong is one extra create-before-delete replacement.
437 * Without a recorded fingerprint there is nothing to compare against, so the
438 * first deploy that declares `triggers` records it through the engine's
439 * default update instead of replacing the deployment.
440 */
441 const triggersChanged = Effect.fn(function* (
442 triggers: unknown,
443 persisted: Redacted.Redacted<string> | string | undefined,
444 ) {
445 const recorded = persistedTriggersHash(persisted);
446 if (triggers === undefined || recorded === undefined) return false;
447 if (!isResolved({ triggers })) return true;
448 return (yield* triggersHashOf(triggers)) !== recorded;
449 });
450
451 export const uploadArtifact = (
452 uploadUrl: string,
453 artifact: Uint8Array | ArtifactFile,
454 contentType: string,
455 ) =>
456 Effect.gen(function* () {
457 if (artifact instanceof Uint8Array) {
458 yield* validateDeploymentArtifactBytes(artifact);
459 } else if (artifact.size <= 0 || artifact.size > MAX_DEPLOYMENT_ARTIFACT_BYTES) {
460 return yield* new DeploymentInvalidProps({
461 message: `Prisma deployment artifact exceeds the ${MAX_DEPLOYMENT_ARTIFACT_BYTES} byte upload safety limit.`,
462 });
463 }
464 yield* Effect.try({
465 try: () => {
466 const parsed = new URL(uploadUrl);
467 if (
468 parsed.protocol !== "https:" ||
469 parsed.username.length > 0 ||
470 parsed.password.length > 0
471 ) {
472 throw new Error("invalid upload URL");
473 }
474 },
475 catch: (cause) =>
476 new InvalidArtifactUploadUrlError({
477 message: "Prisma artifact upload URL must be credential-free HTTPS.",
478 cause,
479 }),
480 });
481 yield* executeArtifactUpload(uploadUrl, artifact, contentType);
482 });
483
484 const ProviderLive = () =>
485 Provider.effect(
486 Deployment,
487 Effect.gen(function* () {
488 return {
489 stables: ["deploymentId"],
490 // App deletion cascades deployments. AppProvider is the single nuke
491 // enumerator so a deployment is never deleted twice during teardown.
492 list: () => Effect.succeed([]),
493 diff: Effect.fn(function* ({ olds, news, output }) {
494 if (!isInputObject(news)) return undefined;
495 if (isPrismaDevId(output?.deploymentId)) {
496 return { action: "update" } as const;
497 }
498 // `deploymentId` is stable and Foundry's failed status is terminal.
499 // Route drift recovery through the engine's create-before-delete
500 // replacement lifecycle instead of trying to restart the failed
501 // generation or changing a stable ID during an update.
502 if (output?.status === "failed") {
503 return { action: "replace" } as const;
504 }
505 // Checked before the resolved-content early return below: a
506 // deferred diff falls back to an update, which reuses the running
507 // deployment and would never apply the changed inputs.
508 if (yield* triggersChanged(news.triggers, output?.triggersHash)) {
509 return { action: "replace" } as const;
510 }
511 const replacementContent = {
512 portMapping: news.portMapping,
513 skipCodeUpload: news.skipCodeUpload,
514 artifactPath: news.artifactPath,
515 artifactContentType: news.artifactContentType,
516 };
517 if (!isResolved(replacementContent)) return undefined;
518 const resolvedReplacementContent = replacementContent as Pick<
519 DeploymentProps,
520 "portMapping" | "skipCodeUpload" | "artifactPath" | "artifactContentType"
521 >;
522 const oldAppId = output?.appId ?? unresolvedAppIdOf(olds.app);
523 const newAppId = isResolved(news.app) ? unresolvedAppIdOf(news.app) : undefined;
524 const oldArtifactHash = output?.artifactHash;
525 const newArtifactHash = yield* artifactHashOf({
526 app: olds.app,
527 ...resolvedReplacementContent,
528 });
529 const appChanged = concreteIdsChanged(oldAppId, newAppId);
530 if (
531 appChanged ||
532 !deepEqual(resolvedReplacementContent.portMapping ?? {}, olds.portMapping ?? {}) ||
533 (resolvedReplacementContent.skipCodeUpload ?? false) !==
534 (olds.skipCodeUpload ?? false) ||
535 resolvedReplacementContent.artifactPath !== olds.artifactPath ||
536 resolvedReplacementContent.artifactContentType !== olds.artifactContentType ||
537 (newArtifactHash !== undefined && newArtifactHash !== oldArtifactHash)
538 ) {
539 return { action: "replace" } as const;
540 }
541 const updateProps = {
542 start: news.start,
543 promote: news.promote,
544 };
545 if (!isResolved(updateProps)) return undefined;
546 const resolvedUpdateProps = updateProps as Pick<DeploymentProps, "start" | "promote">;
547 if ((resolvedUpdateProps.start ?? false) || (resolvedUpdateProps.promote ?? false)) {
548 // Reconcile asserted lifecycle state on every deploy so external
549 // stops and App routing drift are repaired.
550 return { action: "update" } as const;
551 }
552 if (
553 (resolvedUpdateProps.start ?? false) !== (olds.start ?? false) ||
554 (resolvedUpdateProps.promote ?? false) !== (olds.promote ?? false)
555 ) {
556 return { action: "update" } as const;
557 }
558 return undefined;
559 }),
560 read: Effect.fn(function* ({ output, olds }) {
561 if (isPrismaDevId(output?.deploymentId)) return undefined;
562 const appId =
563 output?.appId && !isPrismaDevId(output.appId)
564 ? output.appId
565 : yield* resolveAppId(olds.app);
566 const savedDeployment = output?.deploymentId
567 ? yield* observeDeployment(output.deploymentId).pipe(
568 Effect.catchTag("NotFound", () => Effect.undefined),
569 )
570 : undefined;
571 const listed = savedDeployment
572 ? undefined
573 : yield* findDeployment(appId, output?.foundryVersionId);
574 const deployment =
575 savedDeployment ?? (listed ? yield* observeDeployment(listed.id) : undefined);
576 if (savedDeployment) {
577 yield* ensureDeploymentMembership(appId, savedDeployment);
578 }
579 return deployment ? attrsFrom(deployment, appId, output) : undefined;
580 }),
581 reconcile: Effect.fn(function* ({ news, output }) {
582 if (
583 news.portMapping?.http !== undefined &&
584 news.portMapping.http !== null &&
585 (!Number.isInteger(news.portMapping.http) ||
586 news.portMapping.http < 1 ||
587 news.portMapping.http > 65_535)
588 ) {
589 return yield* new DeploymentInvalidProps({
590 message: "portMapping.http must be an integer between 1 and 65535.",
591 });
592 }
593 if (!(news.skipCodeUpload ?? false) && news.artifactPath === undefined) {
594 return yield* new DeploymentInvalidProps({
595 message: "Prisma.Deployment requires artifactPath or skipCodeUpload: true.",
596 });
597 }
598 if ((news.skipCodeUpload ?? false) && news.artifactPath !== undefined) {
599 return yield* new DeploymentInvalidProps({
600 message: "skipCodeUpload cannot be combined with artifactPath.",
601 });
602 }
603 if ((news.promote ?? false) && news.start === false) {
604 return yield* new DeploymentInvalidProps({
605 message: "promote cannot be combined with start: false.",
606 });
607 }
608 const artifact = yield* readUploadArtifact({
609 artifactPath: news.artifactPath,
610 output: "file",
611 });
612 const artifactHash =
613 artifact === undefined
614 ? output?.artifactHash
615 : yield* sha256Object({
616 artifact: artifact.sha256,
617 contentType: news.artifactContentType ?? "application/octet-stream",
618 });
619 const triggersHash =
620 news.triggers === undefined
621 ? undefined
622 : Redacted.make(yield* triggersHashOf(news.triggers));
623 const appId = yield* resolveAppId(news.app);
624 const deploymentId = isPrismaDevId(output?.deploymentId)
625 ? undefined
626 : output?.deploymentId;
627 let deployment: ObservedDeployment | undefined = deploymentId
628 ? yield* observeDeployment(deploymentId).pipe(
629 Effect.catchTag("NotFound", () => Effect.undefined),
630 )
631 : undefined;
632 if (deployment) {
633 yield* ensureDeploymentMembership(appId, deployment);
634 if (deployment.status === "failed") {
635 return yield* new DeploymentOperationFailed({
636 message: `Prisma deployment '${deployment.id}' is in terminal status 'failed' and must be replaced before reconcile; refusing to restart it or change the stable deploymentId during an update.`,
637 });
638 }
639 }
640 let createdDeploymentId: string | undefined;
641 const cleanupCreatedDeploymentOnFailure = (failedDeploymentId: string, error: unknown) =>
642 createdDeploymentId === failedDeploymentId
643 ? destroyDeployment(failedDeploymentId).pipe(
644 Effect.mapError((cleanupError) =>
645 aggregateCleanupFailure(
646 "deployment",
647 failedDeploymentId,
648 `/v1/deployments/${failedDeploymentId}`,
649 error,
650 cleanupError,
651 ),
652 ),
653 Effect.andThen(() => Effect.fail(error)),
654 )
655 : Effect.fail(error);
656
657 if (!deployment) {
658 const created = yield* createServiceDeployment({
659 serviceId: appId,
660 ...(news.portMapping === undefined ? {} : { portMapping: news.portMapping }),
661 ...(news.skipCodeUpload === undefined ? {} : { skipCodeUpload: news.skipCodeUpload }),
662 }).pipe(
663 // A replayed create would make a second deployment; the retry
664 // policy cannot see the request, so opt out explicitly.
665 Retry.none,
666 Effect.map((response) => response.data),
667 );
668 createdDeploymentId = created.id;
669 if (artifact !== undefined && !created.uploadUrl) {
670 return yield* cleanupCreatedDeploymentOnFailure(
671 created.id,
672 new Error("Prisma deployment creation did not return an upload URL."),
673 );
674 }
675 if (created.uploadUrl && artifact !== undefined) {
676 yield* uploadArtifact(
677 created.uploadUrl,
678 artifact,
679 news.artifactContentType ?? "application/octet-stream",
680 ).pipe(Effect.catch((error) => cleanupCreatedDeploymentOnFailure(created.id, error)));
681 }
682 deployment = yield* observeDeployment(created.id).pipe(
683 Effect.catchTag("NotFound", () =>
684 Effect.succeed({
685 id: created.id,
686 foundryVersionId: created.foundryVersionId,
687 status: "new",
688 previewDomain: null,
689 createdAt: undefined,
690 }),
691 ),
692 Effect.catch((error) => cleanupCreatedDeploymentOnFailure(created.id, error)),
693 );
694 }
695 if (!deployment) {
696 return yield* new DeploymentUnexpectedResponse({
697 message: "Prisma deployment could not be resolved after creation.",
698 });
699 }
700
701 let appEndpointDomain = output?.appEndpointDomain;
702 const shouldStart = news.start ?? news.promote ?? false;
703 if (shouldStart) {
704 const currentDeployment = deployment;
705 const currentDeploymentId = currentDeployment.id;
706 deployment = yield* Effect.gen(function* () {
707 if (
708 currentDeployment.status !== "running" &&
709 currentDeployment.status !== "provisioning"
710 ) {
711 const started = yield* startDeploymentIdempotent(currentDeployment.id);
712 if (started) {
713 return yield* waitForDeploymentStatus(currentDeployment.id, "running").pipe(
714 Effect.map((running) => ({
715 ...running,
716 previewDomain: started.previewDomain,
717 })),
718 );
719 }
720 }
721 return yield* waitForDeploymentStatus(currentDeployment.id, "running");
722 }).pipe(
723 Effect.catch((error) =>
724 cleanupCreatedDeploymentOnFailure(currentDeploymentId, error),
725 ),
726 );
727 }
728 if (news.promote ?? false) {
729 // Promotion is deliberately replayed even when the control-plane
730 // record already names this deployment. The endpoint operation also
731 // repairs provider routing and custom-domain assignment drift.
732 const promoted = yield* promoteAppObserved(appId, deployment.id);
733 appEndpointDomain = promoted.appEndpointDomain;
734 }
735
736 return attrsFrom(deployment, appId, {
737 artifactHash,
738 triggersHash,
739 appEndpointDomain,
740 });
741 }),
742 delete: Effect.fn(function* ({ output }) {
743 if (isPrismaDevId(output.deploymentId)) return;
744 const deployment = yield* observeDeployment(output.deploymentId).pipe(
745 Effect.catchTag("NotFound", () => Effect.undefined),
746 );
747 if (!deployment) return;
748 yield* ensureDeploymentMembership(output.appId, deployment);
749 yield* destroyDeployment(output.deploymentId).pipe(
750 // The stop was requested; it finishes once open connections close.
751 Effect.catchIf(
752 (error) => error instanceof PrismaDeploymentWaitTimeout,
753 (error) =>
754 Effect.fail(
755 new Provider.DeleteInProgress({
756 message: `${error.message}. Prisma Compute drains open connections before it stops a deployment, and only a stopped deployment can be deleted.`,
757 }),
758 ),
759 ),
760 );
761 }),
762 tail: ({ output }) =>
763 output.deploymentId ? tailDeploymentLogs(output.deploymentId) : Stream.empty,
764 };
765 }),
766 );
767
768 const ProviderLocal = () =>
769 devProvider(Deployment, ["deploymentId"], ({ id, news }) => ({
770 deploymentId: devId("deployment", id),
771 appId: attrOrString(news.app, "appId"),
772 foundryVersionId: devId("foundry-version", id),
773 status: "new",
774 previewDomain: undefined,
775 artifactHash: undefined,
776 triggersHash: undefined,
777 appEndpointDomain: undefined,
778 createdAt: DEV_TIMESTAMP,
779 }));
780
781 export const DeploymentProvider = () =>
782 ProviderLayer.dual(Deployment, {
783 local: () => ProviderLocal(),
784 live: () => ProviderLive(),
785 });