diff --git a/.drive/projects/variable-groups-compat/deferred.md b/.drive/projects/variable-groups-compat/deferred.md index 776178063..e030c49aa 100644 --- a/.drive/projects/variable-groups-compat/deferred.md +++ b/.drive/projects/variable-groups-compat/deferred.md @@ -4,3 +4,6 @@ - **Hints use `prisma project env` for the built-in groups.** Move them to `prisma variable` when it is the CLI most users have. - **An app upgrading directly from a version before the address change** can have one service receive another's old row once. The guide tells it to deploy with a release from 0.35.0 to 0.39.0 first. A check in preflight against the deploy state would refuse it instead. - **Ask the platform to put the limit and the count in its quota error for service variables.** Composer checks its own count, but cannot count variables a user set in Console. +- **The upstream pull requests for `variables`.** Alchemy (`Prisma.Deployment.variables`) and Distilled (the request field) are carried as `pnpm` patches; the proposed source changes are in `slices/upstream/`. The Distilled patch JSON guesses the converter's input shape name, `PostV1ServicesByServiceIdDeploymentsRequest`; check it against the generated spec. The patch to Distilled's compiled `lib/services/management.js` leaves the byte-offset index its `distilled-lazy` build reads out of date; nothing in this repository uses that build. Composer cannot release this change until both packages ship the field: a published package installs the unpatched provider, which drops `variables` without an error. +- **Ask the platform for a "delete every key with this prefix I did not send" flag** on the create-deployment request. It would make `SentVariableNames` unnecessary and delete keys Composer never recorded. +- **A structured error raised while a deploy is planned is reported as `DEPLOY.ENGINE_FAILED`.** The 50-variable refusal carries its own code, `DEPLOY.SERVICE_VARIABLE_LIMIT`, with a why and a fix, but the CLI wraps every failed converge as `DEPLOY.ENGINE_FAILED` (`convergeFailure` in `packages/0-framework/3-tooling/cli/src/operations/execute-deploy-destroy.ts`), so the user sees "Alchemy could not deploy the app" with the real message as one reason. Fixing it is a change to the framework's CLI and probably the converge contract: when every reason of a failed converge is a structured error raised during planning, report it under its own code. Found in manual QA of slice 3, 2026-11-21. diff --git a/.drive/projects/variable-groups-compat/design.md b/.drive/projects/variable-groups-compat/design.md index 0f0c16e91..7d11e86b2 100644 --- a/.drive/projects/variable-groups-compat/design.md +++ b/.drive/projects/variable-groups-compat/design.md @@ -148,7 +148,7 @@ With the pull request above merged, no value in the map depends on a deployment: **Keys a service used to send are deleted.** A key the service's code no longer declares, such as a removed dependency's params or a renamed generated value, would otherwise stay stored: readable by every later deployment of that service, and counted toward the limit of 50, with no way for the user to delete it. So Composer keeps, for each service, a record of every key it has ever sent, and sends `null` for each recorded key that is not in this deploy's map. -- The record is a Composer-owned Alchemy resource in the deploy state, one per service, like the one that keeps a generated value stable (`GeneratedParam`). Its input is this deploy's key names. Its output is every key name it has been given, ever. It holds names, never values. +- The record is a Composer-owned Alchemy resource in the deploy state, `PrismaCloud.SentVariableNames` with the ID `
.sent-variable-names`, one per service, like the one that keeps a generated value stable (`GeneratedParam`). Its input is this deploy's key names. Its output is every key name it has been given, ever. It holds names, never values. As built, it is registered for the hosted and the local target. - When the key names do not change, the record does not change, its output is known at plan time, and the map is the same as last time. So the `null`s are stable and replace nothing. - When the key names change, the record changes and so does the map. That deploy replaces the deployment anyway, because the keys changed. - The record starts at the first deploy with this version. Before it, Composer wrote rows, and Alchemy deleted the rows of removed keys itself. @@ -168,7 +168,7 @@ variables?: Record | null>; - **Declared `variables` with no recorded hash also replaces.** This differs from `triggers`, which records its first hash through an update. An update creates no deployment, so the values would never reach the platform. - Leaving `variables` unset sends no field, so every existing user of the resource is unaffected. -The generated client `@distilled.cloud/prisma` gains the field on the request type. It is generated from the platform's published production API description, and it can also carry a hand-written patch for a field the description does not have yet. +The generated client `@distilled.cloud/prisma` gains the field on the request type. It is generated from the platform's published production API description, and it can also carry a hand-written patch for a field the description does not have yet. As built, both packages carry the field as `pnpm` patches under `patches/`, and the proposed upstream changes are in `slices/upstream/`. **Under `prisma dev`.** The local `Prisma.Deployment` provider takes the service's own keys from its `variables` prop, where it reads `env.json` today. A `null` entry is left out. Everything else in `materializeEnv` stays: the emulator's port is still laid over `COMPOSER_
_PORT`, and the platform variables are still added. A changed `variables` is a changed prop, so a changed value still restarts the service. @@ -182,14 +182,14 @@ A service that runs a dev server has no deployment, so it has no prop to carry t 2. Alchemy then deletes the resources that are in its state and no longer declared: the old variable rows, on production and on preview. Each row is deleted after the old deployment it fed has stopped. A deployment that is still draining open connections holds its rows until a later deploy finds it stopped, so rows can remain visible in Console after the first deploy. 3. While both exist, the service variable wins over the row. 4. On production, the `COMPOSER_` keys leave the user's production group. -5. A row already deleted in Console, or one the platform manages, is skipped. A row the platform refuses to delete because its recorded identity does not match is removed from the deploy state and reported as a warning that names the key, so one bad row cannot fail this deploy and every deploy after it. +5. A row already deleted in Console, or one the platform manages, is skipped (upstream's own delete does this). A row the platform refuses to delete because its recorded identity does not match is removed from the deploy state and reported as a warning that names the key, so one bad row cannot fail this deploy and every deploy after it. As built, Composer registers the hosted `Prisma.EnvironmentVariable` provider through its own layer (`providerForDeletingOldVariableRows()` in `lowering/src/providers.ts`), whose delete catches upstream's `EnvironmentVariableConflict`, logs the warning, and succeeds, so Alchemy drops the row from state. 6. If the deploy is interrupted after the replacements, the next deploy replaces nothing again and finishes the deletes. Deleting a row by id keeps working after override writes are rejected. **What is deleted with the rows.** The key-clash check and the code that computes the clashes: with no rows written, two rows cannot collide. One narrow case remains for an app that upgrades directly from a version before the address change: a service whose new key equals another service's old key, and which has no value for it, would receive the other service's old row once. The guide tells such an app to deploy once with any release from 0.35.0 to 0.39.0 first. `asOwnRow` is no longer applied to variables. Build reporting stops listing variable rows, except the deletes on the first deploy. -**Going back to an older Composer** after a deploy with this version is not supported, and the release note says why: the older version writes rows again, and the stored service variables win over them, so a value that changed since never reaches the service. +**Going back to an older Composer** after a deploy with this version is not possible: deploy state then holds a `PrismaCloud.SentVariableNames` resource per service, an older version registers no provider for it, and Alchemy stops while planning, before changing anything. **Not part of this:** options on `prisma deploy` that set a user's value on a service, which the platform spec proposes as `--variable`. The decision that defines platform variables says the deploy sets no user values until that has its own design. diff --git a/.drive/projects/variable-groups-compat/plan.md b/.drive/projects/variable-groups-compat/plan.md index 81db6ad67..32453c979 100644 --- a/.drive/projects/variable-groups-compat/plan.md +++ b/.drive/projects/variable-groups-compat/plan.md @@ -14,7 +14,20 @@ Design section 4.1. Builds on: slice 1. Merges when the new read is live in prod ## Slice 3: a service's `COMPOSER_` keys travel with its deployment -Design section 4.2. Builds on: the open pull request "an unchanged deploy no longer replaces a service that depends on another service", merged. Independent of slice 2. Opened early as a draft, with `pnpm` patches standing in for the upstream packages, for Ty to align his interface against. Needs one pull request on Distilled and one on Alchemy once the platform's field is final. Merges when the platform accepts `variables` in production and both upstream packages have released. +Design section 4.2. Builds on: the open pull request "an unchanged deploy no longer replaces a service that depends on another service", merged. Opened early as a draft, with `pnpm` patches standing in for the upstream packages, for Ty to align his interface against. Needs one pull request on Distilled and one on Alchemy once the platform's field is final. Merges when the platform accepts `variables` in production and both upstream packages have released. + +Its code is independent of slice 2 and can be built and reviewed on its own, but it merges after slice 2: its glossary copies slice 2's entries for variable group and service variable word for word, and those entries describe slice 2's preflight, which reads the variable group the branch receives; on `main` before slice 2 they would be false. When slice 2 merges, rebase this branch onto it. + +Before marking the pull request ready: + +- [ ] The platform accepts `variables` on the create-deployment request in production. +- [ ] `@distilled.cloud/prisma` and `@alchemy.run/prisma` have released the field. +- [ ] Composer's pins are raised to those releases, `patches/` and `pnpm.patchedDependencies` are gone, and `check:patched-dependencies` passes. +- [ ] The paragraphs about the patches in ADR-0069 (end of "Decision") and in `alchemy-lowering.md` (the `Prisma.Deployment` row) are removed. +- [ ] The `Deploy, verify, destroy` check passes against a platform that accepts `variables`. +- [ ] A manual upgrade against that platform: an app deployed with 0.39.0 on a production and a preview environment, then deployed with this branch, with the services watched for at least ten minutes afterwards. + +When opening the draft, the pull request description says the E2E deploy job fails until the platform accepts `variables` in production. ## Release diff --git a/.drive/projects/variable-groups-compat/slices/slice-3-plan.md b/.drive/projects/variable-groups-compat/slices/slice-3-plan.md new file mode 100644 index 000000000..d603774f5 --- /dev/null +++ b/.drive/projects/variable-groups-compat/slices/slice-3-plan.md @@ -0,0 +1,16 @@ +# Slice 3: a service's `COMPOSER_` keys travel with its deployment + +Design: [design.md](../design.md) section 4.2, with the tests in section 9 and in the principal engineer's design review. One pull request, opened as a draft for the platform team to align the create-deployment field against. + +This branch starts from `main` with the open pull request "an unchanged deploy no longer replaces a service that depends on another service" merged in. When that pull request merges, the branch is rebased onto `main`. + +## Dispatches, in order + +1. **The upstream prop, as local patches.** `pnpm` patches for `@alchemy.run/prisma` (the `variables` prop on `Prisma.Deployment`: sent on create, hashed for `diff`, replaces when changed, unresolved or first declared, never sent on update) and `@distilled.cloud/prisma` (the field on the create-deployment request). The same change is prepared as source diffs against the upstream clones, for the two upstream pull requests later. +2. **The hosted deploy.** `serialize` returns the map; every key boot reads is a value or `null`; the per-service record of key names and the `null`s it produces; the limit of 50; `deploy` passes `variables`; triggers keep only platform variable members; `appAfter` keeps the producer wait; the key-clash check is deleted; the hosted variable provider stays registered. Tests with the real engine, including the upgrade from state written by today's code. +3. **`prisma dev`.** The local deployment provider takes the service's keys from `variables`; `reserve` keeps rows for dev servers, never writes a `null`, and fails outside the local application. +4. **Docs.** The new decision record and every record, guide and glossary entry the design's section 8 lists for 4.2. + +## Not in this slice + +The upstream pull requests themselves, which wait for the platform's field to be final. diff --git a/.drive/projects/variable-groups-compat/slices/upstream/alchemy-prisma-deployment-variables.diff b/.drive/projects/variable-groups-compat/slices/upstream/alchemy-prisma-deployment-variables.diff new file mode 100644 index 000000000..b00ee70e3 --- /dev/null +++ b/.drive/projects/variable-groups-compat/slices/upstream/alchemy-prisma-deployment-variables.diff @@ -0,0 +1,159 @@ +diff --git a/packages/prisma/src/Deployment.ts b/packages/prisma/src/Deployment.ts +index 71258d31..704a5e02 100644 +--- a/packages/prisma/src/Deployment.ts ++++ b/packages/prisma/src/Deployment.ts +@@ -144,6 +144,25 @@ export interface DeploymentProps { + * ``` + */ + triggers?: Record; ++ /** ++ * Variables the platform stores on the App, sent with the request that ++ * creates the deployment. A string sets a key, `null` deletes it, and a key ++ * left out keeps its stored value. The platform accepts them only when a ++ * deployment is created, so any change to the resolved map, a value that is ++ * not resolved while planning, or declaring `variables` on a deployment that ++ * was created without them replaces the deployment. They are never sent on ++ * an update. ++ * ++ * The values are stored on the App and outlive this deployment: deleting or ++ * replacing the Deployment leaves them, and so does removing `variables` ++ * from its props; only `null` or deleting the App removes one. Every ++ * Deployment of one App writes to the same store. ++ * ++ * Values may be wrapped in `Redacted.make(secret)`; they are unwrapped only ++ * for the request and the fingerprint. Leaving `variables` unset sends no ++ * field. ++ */ ++ variables?: Record | null>; + } + + export interface Deployment extends Resource< +@@ -181,6 +200,11 @@ export interface Deployment extends Resource< + * state; absent when `triggers` is unset. + */ + triggersHash?: Redacted.Redacted; ++ /** ++ * Salted fingerprint of the resolved `variables` this deployment was ++ * created with; absent when `variables` is unset. ++ */ ++ variablesHash?: Redacted.Redacted; + /** + * Stable App endpoint domain after promotion. + */ +@@ -286,6 +310,7 @@ const attrsFrom = ( + extra?: { + artifactHash?: string; + triggersHash?: Redacted.Redacted; ++ variablesHash?: Redacted.Redacted; + appEndpointDomain?: string; + }, + ): Deployment["Attributes"] => ({ +@@ -296,6 +321,7 @@ const attrsFrom = ( + previewDomain: deployment.previewDomain, + artifactHash: extra?.artifactHash, + triggersHash: extra?.triggersHash, ++ variablesHash: extra?.variablesHash, + appEndpointDomain: extra?.appEndpointDomain, + createdAt: deployment.createdAt, + }); +@@ -424,9 +450,43 @@ const triggersHashOf = (triggers: unknown) => + triggers: unwrapRedacted(triggers) ?? null, + }); + +-const persistedTriggersHash = (value: Redacted.Redacted | string | undefined) => ++const persistedHash = (value: Redacted.Redacted | string | undefined) => + Redacted.isRedacted(value) ? Redacted.value(value) : value; + ++const VARIABLES_HASH_SALT = "alchemy/Prisma.Deployment/variables/v1"; ++ ++const variablesHashOf = (variables: unknown) => ++ sha256Object({ ++ salt: VARIABLES_HASH_SALT, ++ variables: unwrapRedacted(variables) ?? null, ++ }); ++ ++const requestVariables = ( ++ variables: Record | string | null>, ++): Record => ++ Object.fromEntries( ++ Object.entries(variables).map(([key, value]) => [ ++ key, ++ Redacted.isRedacted(value) ? Redacted.value(value) : value, ++ ]), ++ ); ++ ++/** ++ * Whether the declared `variables` require a new deployment. Unlike ++ * `triggers`, a declaration with no recorded fingerprint replaces: an update ++ * creates no deployment, so the values would never reach the platform. ++ */ ++const variablesChanged = Effect.fn(function* ( ++ variables: unknown, ++ persisted: Redacted.Redacted | string | undefined, ++) { ++ if (variables === undefined) return false; ++ const recorded = persistedHash(persisted); ++ if (recorded === undefined) return true; ++ if (!isResolved({ variables })) return true; ++ return (yield* variablesHashOf(variables)) !== recorded; ++}); ++ + /** + * Whether the declared `triggers` inputs differ from the fingerprint the + * running deployment was created for. +@@ -444,7 +504,7 @@ const triggersChanged = Effect.fn(function* ( + triggers: unknown, + persisted: Redacted.Redacted | string | undefined, + ) { +- const recorded = persistedTriggersHash(persisted); ++ const recorded = persistedHash(persisted); + if (triggers === undefined || recorded === undefined) return false; + if (!isResolved({ triggers })) return true; + return (yield* triggersHashOf(triggers)) !== recorded; +@@ -510,6 +570,9 @@ const ProviderLive = () => + if (yield* triggersChanged(news.triggers, output?.triggersHash)) { + return { action: "replace" } as const; + } ++ if (yield* variablesChanged(news.variables, output?.variablesHash)) { ++ return { action: "replace" } as const; ++ } + const replacementContent = { + portMapping: news.portMapping, + skipCodeUpload: news.skipCodeUpload, +@@ -622,6 +685,10 @@ const ProviderLive = () => + news.triggers === undefined + ? undefined + : Redacted.make(yield* triggersHashOf(news.triggers)); ++ const variablesHash = ++ news.variables === undefined ++ ? undefined ++ : Redacted.make(yield* variablesHashOf(news.variables)); + const appId = yield* resolveAppId(news.app); + const deploymentId = isPrismaDevId(output?.deploymentId) + ? undefined +@@ -661,6 +728,9 @@ const ProviderLive = () => + serviceId: appId, + ...(news.portMapping === undefined ? {} : { portMapping: news.portMapping }), + ...(news.skipCodeUpload === undefined ? {} : { skipCodeUpload: news.skipCodeUpload }), ++ ...(news.variables === undefined ++ ? {} ++ : { variables: requestVariables(news.variables) }), + }).pipe( + // A replayed create would make a second deployment; the retry + // policy cannot see the request, so opt out explicitly. +@@ -740,6 +810,7 @@ const ProviderLive = () => + return attrsFrom(deployment, appId, { + artifactHash, + triggersHash, ++ variablesHash, + appEndpointDomain, + }); + }), +@@ -778,6 +849,7 @@ const ProviderLocal = () => + previewDomain: undefined, + artifactHash: undefined, + triggersHash: undefined, ++ variablesHash: undefined, + appEndpointDomain: undefined, + createdAt: DEV_TIMESTAMP, + })); diff --git a/.drive/projects/variable-groups-compat/slices/upstream/distilled-prisma-006-add-deployment-variables.patch.json b/.drive/projects/variable-groups-compat/slices/upstream/distilled-prisma-006-add-deployment-variables.patch.json new file mode 100644 index 000000000..6ae619bdf --- /dev/null +++ b/.drive/projects/variable-groups-compat/slices/upstream/distilled-prisma-006-add-deployment-variables.patch.json @@ -0,0 +1,29 @@ +{ + "description": "Declare the `variables` field the platform is adding to the create-deployment request (POST /v1/services/{serviceId}/deployments): a map from key to a string, which sets the key, or null, which deletes it. A key not sent keeps its stored value. Remove this patch once the published API description carries the field. The input shape name below follows the converter's naming for this operation and must be checked against .generated-specs before committing.", + "patches": [ + { + "op": "add", + "path": "/shapes/com.prisma#ServiceVariables", + "value": { + "type": "map", + "key": { + "target": "smithy.api#String" + }, + "value": { + "target": "smithy.api#String" + }, + "traits": { + "smithy.api#sparse": {}, + "smithy.api#documentation": "Variables stored on the service. A string sets the key, null deletes it, and a key not sent keeps its stored value." + } + } + }, + { + "op": "add", + "path": "/shapes/com.prisma#PostV1ServicesByServiceIdDeploymentsRequest/members/variables", + "value": { + "target": "com.prisma#ServiceVariables" + } + } + ] +} diff --git a/.drive/projects/variable-groups-compat/slices/upstream/distilled-prisma-generated-management.diff b/.drive/projects/variable-groups-compat/slices/upstream/distilled-prisma-generated-management.diff new file mode 100644 index 000000000..283199650 --- /dev/null +++ b/.drive/projects/variable-groups-compat/slices/upstream/distilled-prisma-generated-management.diff @@ -0,0 +1,20 @@ +diff --git a/packages/prisma/src/services/management.ts b/packages/prisma/src/services/management.ts +index 7c0702e0..afed79d4 100644 +--- a/packages/prisma/src/services/management.ts ++++ b/packages/prisma/src/services/management.ts +@@ -977,6 +977,7 @@ export interface CreateServiceDeploymentRequest { + serviceId: string; + portMapping?: CreateServiceDeploymentRequestPortMapping; + skipCodeUpload?: boolean; ++ variables?: { [key: string]: string | null }; + } + export interface CreateServiceDeploymentResponseData { + id: string; +@@ -6235,6 +6236,7 @@ function __c57(j: number): any { + serviceId: S.String.pipe(T.Label()), + portMapping: S.optional(__S(912, __c57, 0)), + skipCodeUpload: S.optional(S.Boolean), ++ variables: S.optional(S.Record(S.String, S.NullOr(S.String))), + }).pipe(T.Http({ method: "POST", uri: "/v1/services/{serviceId}/deployments", code: 200 })), + ).annotate({ identifier: "CreateServiceDeploymentRequest" }); + case 2: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d10063921..6645fa07b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,6 +31,9 @@ jobs: run: pnpm lint:retired-binary-name - name: Lint (no control bytes in tracked files) run: pnpm lint:control-bytes + # A pnpm patch never reaches a user's install, so a release must not depend on one. + - name: Lint (no published package depends on a patched package) + run: pnpm check:patched-dependencies typecheck: name: Type Check diff --git a/.github/workflows/preview-publish.yml b/.github/workflows/preview-publish.yml index 43ea0f686..e0497f4a1 100644 --- a/.github/workflows/preview-publish.yml +++ b/.github/workflows/preview-publish.yml @@ -56,6 +56,10 @@ jobs: - name: Install dependencies run: pnpm install --frozen-lockfile + # A preview install gets no pnpm patch, so a branch that needs one publishes no preview. + - name: Check no published package depends on a patched package + run: pnpm check:patched-dependencies + - name: Build packages run: pnpm build diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index b467c5b8e..94b8c0dd0 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -91,6 +91,9 @@ jobs: - name: Check publish dependency specifiers run: pnpm check:publish-deps + - name: Check no published package depends on a patched package + run: pnpm check:patched-dependencies + # The remaining publish-blocking invariants, against the exact artifacts # this run would upload (the build step above built everything): # engine-once — the engine is an exact peer of the CLI package, external diff --git a/architecture.config.json b/architecture.config.json index 4b272e84b..1886e141e 100644 --- a/architecture.config.json +++ b/architecture.config.json @@ -349,7 +349,7 @@ "plane": "control" }, { - "glob": "packages/1-prisma-cloud/1-extensions/target/src/env-key-clash.ts", + "glob": "packages/1-prisma-cloud/1-extensions/target/src/sent-variable-names-resource.ts", "domain": "prisma-cloud", "layer": "extensions", "plane": "control" diff --git a/docs/design/03-domain-model/glossary.md b/docs/design/03-domain-model/glossary.md index 01ae2ce7b..7ec2428f9 100644 --- a/docs/design/03-domain-model/glossary.md +++ b/docs/design/03-domain-model/glossary.md @@ -157,7 +157,7 @@ In code the type is `Value`, and `RealValuesOf` is the tuple of real-value A [value](#value) whose data exists only on the platform the app is deployed to: the service reads it at boot. A platform variable node's value, `generatedParam()` and `serviceOrigin()` give one. In code a runtime value is `RuntimeValue`, which is `Value>`. `T` is the data the service receives: `string` for `serviceOrigin()`, and for a plain platform variable the type its `schema` gives, such as `RuntimeValue` for `variable({ name: 'SMTP_PORT', schema: type('number') })`. -At deploy its real value is a **pointer**: an object that names the [variable on the platform](#a-variable-on-the-platform) holding the data. For a platform variable node's value that is the platform variable; for `generatedParam()` and `serviceOrigin()` it is one of Composer's own `COMPOSER_` rows. The deploy writes the pointer into the service's input document, and the service reads the variable at boot. A pointer has one of two kinds, which it records in its data: +At deploy its real value is a **pointer**: an object that names the [variable on the platform](#a-variable-on-the-platform) holding the data. For a platform variable node's value that is the platform variable; for `generatedParam()` and `serviceOrigin()` it is one of the service's own `COMPOSER_` keys, which Composer sends as a [service variable](#service-variable). The deploy writes the pointer into the service's input document, and the service reads the variable at boot. A pointer has one of two kinds, which it records in its data: - a **secret pointer**, typed `Pointer`, from a platform secret's value and a redacted `generatedParam()`; - a **plain pointer**, typed `Pointer` for the data type `T` its source gives, from a plain platform variable's value, `serviceOrigin()` and a plain `generatedParam()`. @@ -170,7 +170,7 @@ A pointer is typed by its source. `serviceOrigin()` and a plain `generatedParam( ### Platform variable -A variable on the platform that a service reads by name at boot. The app declares each one with a [platform variable node](#platform-variable-node) in its root, so every message can name the node. The service reads it through a field of its `input`. "Plain platform variable" means the non-secret kind; the secret kind is a [platform secret](#platform-secret). A deploy does not copy its value from the developer's local environment and does not read it: the platform hands it to the running service. For now the operator sets it with `prisma project env add`. Under `prisma dev`, the local target plays the platform's part: it reads a plain platform variable's value from the app configuration and a platform secret's from the app secrets, and hands it to the local service. A variable has a class row (production or preview) and, on a preview environment, may have a branch row for one branch; the branch row wins ([ADR-0064](../90-decisions/ADR-0064-an-app-declares-its-platform-variables-in-its-root-and-the-deploy-copies-no-local-values.md)). Composer's own `COMPOSER_` rows are [variables on the platform](#a-variable-on-the-platform) but not platform variables, because the app does not declare them. In code: `PlatformVariableReader`, `UnsetPlatformVariable`, `PlatformVariableCheck`. +A variable on the platform that a service reads by name at boot. The app declares each one with a [platform variable node](#platform-variable-node) in its root, so every message can name the node. The service reads it through a field of its `input`. "Plain platform variable" means the non-secret kind; the secret kind is a [platform secret](#platform-secret). A deploy does not copy its value from the developer's local environment and does not read it: the platform hands it to the running service. For now the operator sets it on Prisma Cloud, in the [variable group](#variable-group) the environment's branch receives. Under `prisma dev`, the local target plays the platform's part: it reads a plain platform variable's value from the app configuration and a platform secret's from the app secrets, and hands it to the local service. A deployment receives the values of its branch's group, then the branch's overrides, then its service's [service variables](#service-variable); a later one wins. Deploy preflight checks the group and the overrides, not the service variables ([ADR-0064](../90-decisions/ADR-0064-an-app-declares-its-platform-variables-in-its-root-and-the-deploy-copies-no-local-values.md)). Composer's own `COMPOSER_` keys are [service variables](#service-variable), not platform variables, because the app does not declare them. In code: `PlatformVariableReader`, `UnsetPlatformVariable`, `PlatformVariableCheck`. ### Platform variable node @@ -194,7 +194,15 @@ A [platform variable](#platform-variable) whose value is handled as a secret: bo ### A variable on the platform -Any entry, or **row**, in a Prisma Cloud project's environment variables: a name and a non-empty text, at a class and optionally a branch. That includes Composer's own `COMPOSER_` rows, which are not [platform variables](#platform-variable). The term names the platform's storage, as distinct from what the app reads. Prisma Cloud calls these rows environment variables. +Any entry, or **row**, in a Prisma Cloud project's environment variables: a name and a non-empty text. An older Composer wrote its own `COMPOSER_` keys as rows; they were never [platform variables](#platform-variable), and Composer now sends them as [service variables](#service-variable). A **group row** belongs to a [variable group](#variable-group); what was called a class row is a row of the `production` or `preview` group. A **branch override** (formerly "branch row") belongs to one branch and wins over its group's value. The platform is removing branch overrides: after a notice period, it rejects a write that names a branch. Composer releases before [ADR-0069](../90-decisions/ADR-0069-a-services-composer-keys-travel-with-its-deployment-as-service-variables.md) write a service's `COMPOSER_` rows on a preview environment as branch overrides, so their preview deploys fail once the platform rejects them. The term names the platform's storage, as distinct from what the app reads. Prisma Cloud calls these rows environment variables. + +### Variable group + +Prisma Cloud's term for a named set of [variables on the platform](#a-variable-on-the-platform) in one project. Every project has a `production` group and a `preview` group; it can add custom groups, each with one rule on a branch's git name (`equals` or `startsWith`). Each branch receives exactly one group: the production branch receives `production`, any other branch the custom group with the most precise matching rule, or else `preview`. Groups do not combine. A group's **class** is a field of the group that names its kind: `production`, `preview` or `custom`. It is not the old class of a row, which had only the values `production` and `preview`. + +### Service variable + +Prisma Cloud's term for a value stored on one platform service, which is one Composer [service](#service) in one environment (`Prisma.App` in code). It is set only when a deployment is created, through the create-deployment request, which Console's "Save and Deploy" sends, and is deleted with the platform service. It wins over the branch's group and overrides. Composer sends each service's `COMPOSER_` keys as service variables, a name Composer no longer sends as `null`, and reads none ([ADR-0069](../90-decisions/ADR-0069-a-services-composer-keys-travel-with-its-deployment-as-service-variables.md)). ### Value resource @@ -242,7 +250,7 @@ Every node in the topology either has a managed lifecycle or names a value the o ### Address and logical ID -A node's **address** is its identity: the path of provision IDs starting at the root, assigned by Load (`shop`, `shop.catalog`, `shop.auth.api`). The root's address is the deployed app name, so every address starts with it. A provision ID is the node's name (`publicUrl()` takes it as `id`) unless `provision()` sets an `id`, so a node's name is, by default, part of its identity. The app name starts with a letter or digit and contains only letters, digits, `-` and `_`; below the root, provision IDs contain only letters and digits. Every platform **name** Composer writes (an App's display name, a Connection's, Bucket's or access key's `name`) is the address too; it is a label, never identity. On the platform a Connection's name is the address followed by `-` and a 12-character token that upstream adds. On Prisma Cloud the address is the node's **logical ID** (`logicalId`): Composer writes it, byte for byte, on the node's topology entry and on the node's one platform row (Project, App, Database or Bucket). The same node on two branches has the same logical ID. A **display name** is a label only and never identity. An **Alchemy resource ID** names one of the resources a node lowers to: the address for the node's main resource (`shop.catalog`), and the address plus `.` and a role for its other pieces (`shop.catalog.connection`, `shop.web.deployment`). Alchemy's own docs call it a "logical ID"; it is a different field from the platform's `logicalId`. Composer's environment variable keys are `COMPOSER_` plus the address upper-cased, with `.` and `-` turned into `_` (`COMPOSER_SHOP_WEB_…`). Changing a node's address, including by changing its name, makes it a different entity; it is not a rename. A node that names something Composer does not own, such as a [platform variable node](#platform-variable-node), records no platform row and no topology node, and the thing it names keeps its owner's handle, such as the variable's name. See [ADR-0057](../90-decisions/ADR-0057-a-nodes-address-is-its-full-path-from-the-app-name.md). +A node's **address** is its identity: the path of provision IDs starting at the root, assigned by Load (`shop`, `shop.catalog`, `shop.auth.api`). The root's address is the deployed app name, so every address starts with it. A provision ID is the node's name (`publicUrl()` takes it as `id`) unless `provision()` sets an `id`, so a node's name is, by default, part of its identity. The app name starts with a letter or digit and contains only letters, digits, `-` and `_`; below the root, provision IDs contain only letters and digits. Every platform **name** Composer writes (an App's display name, a Connection's, Bucket's or access key's `name`) is the address too; it is a label, never identity. On the platform a Connection's name is the address followed by `-` and a 12-character token that upstream adds. On Prisma Cloud the address is the node's **logical ID** (`logicalId`): Composer writes it, byte for byte, on the node's topology entry and on the node's one platform row (Project, App, Database or Bucket). The same node on two branches has the same logical ID. A **display name** is a label only and never identity. An **Alchemy resource ID** names one of the resources a node lowers to: the address for the node's main resource (`shop.catalog`), and the address plus `.` and a role for its other pieces (`shop.catalog.connection`, `shop.web.deployment`). Alchemy's own docs call it a "logical ID"; it is a different field from the platform's `logicalId`. The keys of a service's configuration, which reach it as environment variables and which Composer sends on Prisma Cloud as [service variables](#service-variable), are `COMPOSER_` plus the address upper-cased, with `.` and `-` turned into `_` (`COMPOSER_SHOP_WEB_…`). Changing a node's address, including by changing its name, makes it a different entity; it is not a rename. A node that names something Composer does not own, such as a [platform variable node](#platform-variable-node), records no platform row and no topology node, and the thing it names keeps its owner's handle, such as the variable's name. See [ADR-0057](../90-decisions/ADR-0057-a-nodes-address-is-its-full-path-from-the-app-name.md). ## Connections @@ -502,22 +510,12 @@ is in `layering.md`; this is the term-by-term catalogue. emits one Stack for the whole app; `prisma deploy` drives it over the app module the config's `entry` names (no hand-written stack file — ADR-0003). `→` **Topology / app root**. -- **Resource\** — a managed entity with a string type - tag, desired-input **Props**, and cloud-returned **Attributes**. Declared, then - `yield*`-ed. Composer binds upstream alchemy's: `Prisma.Project`, `Database`, - `Connection`, `App`, `Deployment`, `EnvironmentVariable`. - `→` a **Service** lowers to `App` + `Deployment` (+ `EnvironmentVariable`); a - first-class **Resource** (Postgres) lowers to `Database` + `Connection`. +- **Resource\** — a managed entity with a string type tag, desired-input **Props**, and cloud-returned **Attributes**. Declared, then `yield*`-ed. Composer binds upstream alchemy's: `Prisma.Project`, `Database`, `Connection`, `App`, `Deployment`, `EnvironmentVariable`. `→` a **Service** lowers to `App` + `Deployment`, whose `variables` carry its `COMPOSER_` keys (an `EnvironmentVariable` row only for a dev server under `prisma dev`); a first-class **Resource** (Postgres) lowers to `Database` + `Connection`. - **Props** — the desired configuration passed at declare time; diffed against the last deploy to detect change. (A rebuild registers as a change because the artifact is content-addressed: new bytes, new `artifactPath`.) `→` a node's **dependencies** + **Input**. -- **Attributes / Output\** — values the cloud returns (`appEndpointDomain`, - `deploymentId`, ids); lazy references that flow into other Resources' Props. - Resource-to-resource wiring is Output → Props. `→` a node's **exposed interfaces**; a - **connection** (exposed interface→dependency) lowers to Output→Props, plus an - `EnvironmentVariable` when the consumer reads it at runtime (what `AUTH_URL` - does today). +- **Attributes / Output\** — values the cloud returns (`appEndpointDomain`, `deploymentId`, ids); lazy references that flow into other Resources' Props. Resource-to-resource wiring is Output → Props. `→` a node's **exposed interfaces**; a **connection** (exposed interface→dependency) lowers to Output→Props: a value the consumer reads at runtime is a key in its Deployment's `variables`. - **Provider** — implements a Resource type's lifecycle; an Effect `Layer`. We author one per Prisma resource with `Provider.effect(Resource, reconcile)`, bundled via `Provider.collection([…])` into a `Provider.ProviderCollection` diff --git a/docs/design/05-prisma-cloud/alchemy-lowering.md b/docs/design/05-prisma-cloud/alchemy-lowering.md index 441266007..a47c8cc9c 100644 --- a/docs/design/05-prisma-cloud/alchemy-lowering.md +++ b/docs/design/05-prisma-cloud/alchemy-lowering.md @@ -5,12 +5,7 @@ The Alchemy resource types Composer lowers to over the lowering graphs — including the correction that makes deploy ordering a property of the dependency graph rather than luck. -The postgres family (`Project`, `Database`, `Connection`), the compute -family (`App`, `Deployment`, `EnvironmentVariable`) and the bucket family -(`Bucket`, `BucketAccessKey`) are **upstream alchemy's** (`@alchemy.run/prisma`), not -ours: Composer registers their providers and binds their props. What -`@internal/lowering` still owns is the artifact packager, `ServiceKey`, and the -hosted state store. +The postgres family (`Project`, `Database`, `Connection`), the compute family (`App`, `Deployment`, `EnvironmentVariable`) and the bucket family (`Bucket`, `BucketAccessKey`) are **upstream alchemy's** (`@alchemy.run/prisma`), not ours: Composer registers their providers and binds their props. What `@internal/lowering` still owns is the artifact packager, `ServiceKey`, and the hosted state store. A hosted deploy declares no `EnvironmentVariable`: a service's `COMPOSER_` keys go in its Deployment's `variables` ([ADR-0069](../90-decisions/ADR-0069-a-services-composer-keys-travel-with-its-deployment-as-service-variables.md)). ## Placement: one Project per application, one Branch per environment @@ -24,10 +19,7 @@ Consequences, stated plainly: - Config keys are namespaced per service by the pack's mapping (e.g. `AUTH_DB_URL`, `STOREFRONT_AUTH_URL`) — collisions are a naming concern the pack owns, not a reason to split projects. -- The Project is thereby also the **secret-visibility boundary**: every service's - process env physically contains its co-located siblings' variables. One - application = one trust domain; anything that must not be visible across - services belongs in a different project (a different application). +- The Project is thereby also the **secret-visibility boundary**: every service on a Branch receives every variable of the group that Branch receives. A service's own `COMPOSER_` keys are service variables, stored on that service only. One application = one trust domain; anything that must not be visible across services belongs in a different project (a different application). Every deploy environment — production, staging, a per-PR preview — is a **Branch** of that one Project @@ -68,8 +60,9 @@ behind them. | `Prisma.Database` | Database | project, name?, region, branchId?, logicalId? | databaseId, connection strings | one per Module-provisioned postgres resource; never the project default; a branch-attached database is created with `branchId` and no display name (upstream refuses the combination — see [deploying.md](../../guides/deploying.md)) | | `Prisma.Connection` | database connection info | database, name | connectionId, directConnectionString | Composer binds the DIRECT string explicitly; upstream's `databaseUrl` is pooled-first | | `Prisma.App` | App | project, displayName, regionId, branchId?, logicalId? | appId, appEndpointDomain | `branchId` targets the Branch of an environment other than `production`; omitted, upstream attaches the App to the project's default (production) Branch. `appEndpointDomain` is available at provision — that is what a service's own origin and its published `url` are read from | -| `Prisma.EnvironmentVariable` | ConfigVariable | project, class, key, value (Redacted), branchId? | environmentVariableId | production-class with no `branchId` for `production`; preview-class with `branchId` for any other environment. Values are write-only, so upstream re-applies the desired one on every deploy | -| `Prisma.Deployment` | Deployment (ComputeVersion) + Promotion | app, artifactPath, artifactContentType, portMapping, triggers, start, promote | deploymentId, appEndpointDomain | provider reconcile: create → upload tar.gz → start → poll until running → promote; `appEndpointDomain` read **post-promote**; it is the same domain the App reports from its create. It is replaced, not updated, when its artifact fingerprint or its `triggers` fingerprint moves | +| `Prisma.EnvironmentVariable` | ConfigVariable | project, class, key, value (Redacted), branchId? | environmentVariableId | declared by no hosted deploy. Its provider stays registered so Alchemy can delete the rows an older Composer wrote; Composer's layer around it drops a row the platform refuses to delete because its recorded identity differs, with a warning naming the key. Under `prisma dev`, `reserve` declares one per key a dev server reads | +| `Prisma.Deployment` | Deployment (ComputeVersion) + Promotion | app, artifactPath, artifactContentType, portMapping, variables, triggers, start, promote | deploymentId, appEndpointDomain | provider reconcile: create (with `variables`) → upload tar.gz → start → poll until running → promote; `appEndpointDomain` read **post-promote**; it is the same domain the App reports from its create. It is replaced, not updated, when its artifact fingerprint, its `variables` fingerprint or its `triggers` fingerprint moves, and when `variables` is declared on a deployment that recorded none. `variables` is a `pnpm` patch until the platform accepts it in production and the upstream release carries it; `check:patched-dependencies` blocks a release until then | +| `SentVariableNames` (Composer's) | none | names (this deploy's variable names) | names (every name ever given) | one per compute service; the deploy sends `null` for each name Composer no longer sends. Holds names, never values | | `Prisma.Bucket` | Bucket | project, name, branchId?, logicalId? | bucketId, name | one per bucket resource; `Prisma.BucketAccessKey` mints its read-write S3 credentials, which become the node's outputs | `logicalId` is set on every deploy except branchless local dev; [§ Platform identity](#platform-identity-logicalid) says what it carries. @@ -114,8 +107,8 @@ Rules: - The value is the address. Composer passes it explicitly, even where it equals the Alchemy resource ID, because upstream's Prisma resources default `logicalId` to their own fully qualified resource ID. - For App, Database and Bucket, the resource that creates the row writes its `logicalId`, as a prop. No separate resource or later API call writes it. -- On the app's own Project and Branch, the row holding a node's `logicalId` is that node's row. The descriptors declare App, Database, Bucket and `COMPOSER_` EnvironmentVariable resources with `asOwnRow` (Alchemy's `adopt(true)`), so a deploy resuming an interrupted create uses the row instead of failing with `OwnedBySomeoneElse`. On resume, Connections need nothing: their generated name already proves which create made them. Deployments and bucket access keys are never reported as someone else's, so an interrupted create of one is simply made again, and the first attempt can be left behind. -- Other platform rows a node lowers to carry no `logicalId`: `Prisma.Connection`, `Prisma.Deployment`, `Prisma.EnvironmentVariable`, `Prisma.BucketAccessKey`. Composer's local resources (`ServiceKey`, `PgWarm`, `OrmMigration`, `GeneratedParam`, `S3Credentials`) create no platform row. +- On the app's own Project and Branch, the row holding a node's `logicalId` is that node's row. The descriptors declare App, Database and Bucket resources with `asOwnRow` (Alchemy's `adopt(true)`), so a deploy resuming an interrupted create uses the row instead of failing with `OwnedBySomeoneElse`. On resume, Connections need nothing: their generated name already proves which create made them. Deployments and bucket access keys are never reported as someone else's, so an interrupted create of one is simply made again, and the first attempt can be left behind. +- Other platform rows a node lowers to carry no `logicalId`: `Prisma.Connection`, `Prisma.Deployment`, `Prisma.BucketAccessKey`. Composer's local resources (`ServiceKey`, `PgWarm`, `OrmMigration`, `GeneratedParam`, `SentVariableNames`, `S3Credentials`) create no platform row. - Branchless local dev creates no platform rows and writes none. ### Resource IDs @@ -128,7 +121,8 @@ For the app `shop`: | --- | --- | --- | --- | | compute service `shop.web` | `Prisma.App` | `shop.web` | `web-svc` | | | `Prisma.Deployment` | `shop.web.deployment` | `web-deploy` | -| | `Prisma.EnvironmentVariable`, one per key | `shop.web.env.` | `-var` | +| | `SentVariableNames` | `shop.web.sent-variable-names` | (new) | +| | `Prisma.EnvironmentVariable` under `prisma dev`, one per key a dev server reads | `shop.web.env.` | (none) | | | `GeneratedParam`, one per generated input leaf | `shop.web.generated.` | `:-generated` | | | `ServiceKey` for an RPC input (per calling service and input) | `shop.web.servicekey.` | `servicekey-web.` | | | `ServiceKey` for a streams provider (per providing service) | `.streamkey` | `streamskey-` | @@ -140,7 +134,7 @@ For the app `shop`: | | `Prisma.BucketAccessKey` | `shop.uploads.accesskey` | `uploads-key` | | s3 credentials `shop.creds` | `S3Credentials` | `shop.creds` | `creds-creds` | -Every role is a noun naming the piece: `deployment`, `env`, `generated`, `servicekey`, `streamkey`, `connection`, `warmup`, `migration`, `accesskey`. The old ID is computed in `legacy-resource-ids.ts` from `addressBelowApp(address, app)`, which removes the known `.` prefix, by the rule the previous release used. `` is the environment variable key the previous release wrote, built from that shorter address. +Every role is a noun naming the piece: `deployment`, `sent-variable-names`, `env`, `generated`, `servicekey`, `streamkey`, `connection`, `warmup`, `migration`, `accesskey`. The old ID is computed in `legacy-resource-ids.ts` from `addressBelowApp(address, app)`, which removes the known `.` prefix, by the rule the previous release used. `` is the input document key the previous release used, built from that shorter address. Variable rows an older release wrote stay in deploy state under the ID they were stored with, and Alchemy deletes them as resources no longer declared. **Platform names.** Every platform name Composer writes is the node's address (`shop.catalog`, `shop.auth.api`): the App `displayName`, the branchless Database `name`, and the Connection, Bucket and BucketAccessKey `name`. They are labels, never identity. Upstream adds `-` and a 12-character token to every Connection name, so a Connection's platform name is the address plus that suffix. `validatePlatformName` checks the address against each kind's limit (Connection 52, so the address fits beside the suffix in the platform's 65; Bucket 100; App 256; an access key has none) and fails naming the address; it never shortens a name. A hosted Database takes no name from Composer, because upstream refuses a name together with branch attachment; upstream derives its physical name from the resource ID and updates it in place. @@ -148,11 +142,10 @@ On the upgrade deploy every one of these names changes from the short address to - a Connection when its `name` or database changes, which mints new credentials; - a BucketAccessKey when its `name`, `role` or bucket changes, which mints new credentials; -- an EnvironmentVariable when its `key`, `class`, `branchId` or project changes; - an App, Database or Bucket only when its project (or, for a Database, its region, source or default flag) changes; -- a Deployment when its artifact or `triggers` fingerprint changes. +- a Deployment when its artifact, `variables` or `triggers` fingerprint changes. -So the upgrade updates every App, Database and Bucket in place, along with every `logicalId` and a hosted Database's derived name; a Bucket's display name is not its S3 bucket name, so its objects stay. It recreates each of Composer's Connections and bucket access keys with new credentials, and Composer's services receive them in the same deploy. Each replace is create-first and then deletes only the old Connection or key, by the id Composer stored, after checking its database or bucket and name still match. The database, the bucket's objects and any Connection or key made by hand are untouched. Environment variable rows are replaced because their keys change; their values are rewritten on every deploy, so nothing is lost, and the changed environment makes a new Deployment as any environment change does. +So the upgrade updates every App, Database and Bucket in place, along with every `logicalId` and a hosted Database's derived name; a Bucket's display name is not its S3 bucket name, so its objects stay. It recreates each of Composer's Connections and bucket access keys with new credentials, and Composer's services receive them in the same deploy. Each replace is create-first and then deletes only the old Connection or key, by the id Composer stored, after checking its database or bucket and name still match. The database, the bucket's objects and any Connection or key made by hand are untouched. Every `COMPOSER_` key changes name, so every service's `variables` changes and its Deployment is replaced. Status: @@ -174,10 +167,7 @@ logic is untouched. ## The mapping, both directions -- **Ours → PDP**: each resource's provider (`reconcile`/`delete`) calls the - Management API; the table above is that mapping. One resource maps to one PDP - entity except `Deployment`, which spans version-create + upload + start + - promote (and therefore owns the env-snapshot moment). +- **Ours → PDP**: each resource's provider (`reconcile`/`delete`) calls the Management API; the table above is that mapping. One resource maps to one PDP entity except `Deployment`, which spans version-create + upload + start + promote (and therefore owns the env-snapshot moment, and carries the service's `variables`). - **PDP → ours**: `foundryVersionId`, `Promotion`, and Foundry's version record have no resource of ours; they are internal to the `Deployment` provider's behavior or unmodeled. **Branch** likewise has no Alchemy resource — it is resolved and its lifecycle managed by the CLI's container-resolution client, outside the Alchemy graph entirely (see [§ Environments and container resolution](#environments-and-container-resolution)). `serviceEndpointDomain` surfaces as `App.appEndpointDomain` and `Deployment.appEndpointDomain`; both are the same domain. ## The lowering graphs @@ -202,15 +192,14 @@ flowchart LR ```mermaid flowchart TB subgraph P [Project: shop] - DBa[(Database shop.authdb)] --> Ca[Connection shop.authdb.connection] -- url --> EVa["EnvironmentVariable(COMPOSER_SHOP_AUTH_DB_URL)"] - DBs[(Database shop.storefrontdb)] --> Cs[Connection shop.storefrontdb.connection] -- url --> EVs["EnvironmentVariable(COMPOSER_SHOP_STOREFRONT_DB_URL)"] + DBa[(Database shop.authdb)] --> Ca[Connection shop.authdb.connection] -- "url → variables.COMPOSER_SHOP_AUTH_DB_URL" --> Da + DBs[(Database shop.storefrontdb)] --> Cs[Connection shop.storefrontdb.connection] -- "url → variables.COMPOSER_SHOP_STOREFRONT_DB_URL" --> Ds Sa[App shop.auth] --> Da[Deployment shop.auth.deployment] Ss[App shop.storefront] --> Ds[Deployment shop.storefront.deployment] - EVa -- resource ref --> Da - EVs -- resource ref --> Ds - Sa -- appEndpointDomain --> EVu["EnvironmentVariable(COMPOSER_SHOP_STOREFRONT_AUTH_URL)"] - EVu -- resource ref --> Ds - Da -- "serviceId (after promote)" --> Ds + Ka[SentVariableNames shop.auth.sent-variable-names] -- names --> Da + Ks[SentVariableNames shop.storefront.sent-variable-names] -- names --> Ds + Sa -- "appEndpointDomain → variables.COMPOSER_SHOP_STOREFRONT_AUTH_URL" --> Ds + Da -- "serviceId (after promote), on app" --> Ds end ``` @@ -218,31 +207,22 @@ How the pieces map: - **The application** lowers to one `Project`, resolved by the CLI before Alchemy runs. It provisions no variables of its own. -- **Each service** lowers to an `App → Deployment` chain plus its own - `Database → Connection`, whose url is written as that service's **explicitly - named** variable — the same `serialize` path as any other config value. -- **The connection** lowers to two edges: the producer's App's endpoint domain flows into a named `EnvironmentVariable`, and that **whole resource flows into the consumer's `Deployment`** through its `app` prop. The domain comes from the App, not the Deployment: the Deployment is promoted on every deploy, so its domain is unknown while planning, and a consumer's deployment, whose triggers hold the value, would be replaced on every deploy. Because the App's domain is known, an unchanged consumer keeps its deployment when its producer is redeployed. -- Every `EnvironmentVariable` a Deployment boots with is threaded into its `app` — database URLs and connection URLs alike — so the deployment depends on its config being written first. +- **Each service** lowers to an `App → Deployment` chain, a `SentVariableNames` record, plus its own `Database → Connection`, whose url is one of that service's **explicitly named** keys in the Deployment's `variables` — the same `serialize` path as any other config value. +- **The connection** lowers to two edges: the producer's App's endpoint domain becomes a named key in the consumer's Deployment's `variables`, and the producer's outputs ride the consumer's `app` prop. The domain comes from the App, not the Deployment: the Deployment is promoted on every deploy, so its domain is unknown while planning, and a consumer's deployment, whose `variables` hold the value, would be replaced on every deploy. Because the App's domain is known, an unchanged consumer keeps its deployment when its producer is redeployed. +- Every value a Deployment boots with is in its `variables`, so Alchemy schedules the Deployment after every resource those values come from. - Every output of a consumer's producers is threaded into its Deployment's `app` too, so its deployment waits for its producers' promotion: a Compute producer's `serviceId` comes from its Deployment and resolves only after the promotion. The wait is on `app`, not in `triggers`, and upstream treats an unresolved `app` as unchanged, so an unchanged consumer is not replaced. - The Deployment's `portMapping.http` rides the same seam: `serialize` resolves the service's `port` param from the typed Config and surfaces it in its outputs, and `deploy` routes the platform to it — so the routed port and the `PORT` the app binds trace to one value and cannot drift. -That ordering edge is essential and mirrors PDP's own dataflow — the -deployment-create call literally contains the materialized env map, so the -environment is genuinely an input to a deployment (see the -[config lifecycle](pdp-data-model.md#the-config-lifecycle--what-is-resolved-when)). -The edge's job is **ordering**: the variable write completes before -deployment-create, so new and replacement deployments boot with the completed -configuration updates. -Without it the two race — the failure documented as PRO-211 in `gotchas.md`. +That ordering mirrors PDP's own dataflow — the deployment-create call contains the service's variables, so they are genuinely an input to a deployment (see the [config lifecycle](pdp-data-model.md#the-config-lifecycle--what-is-resolved-when)). -**Why the edge rides `app`.** Upstream's `Prisma.Deployment` has no `environment` prop (Composer's deleted one did). Alchemy derives its dependency graph from the resource references a prop's *value* is built from, so the descriptor builds `app` as an Output over the app id, every whole variable resource and every output of the service's producers, resolving to the app id itself: the graph gains the edges. A persisted variable ID can resolve before its pending value update finishes; the whole resource keeps that update as a dependency. The edge cannot ride `artifactPath` (or any of upstream's other replacement-block props): the diff reads that block as one unit and gives no opinion the moment any member is unresolved — and a brand-new variable's reference IS unresolved at plan time — which would skip the artifact comparison and silently drop a code change. [ADR-0048](../90-decisions/ADR-0048-prisma-cloud-resources-come-from-the-upstream-alchemy-provider.md) records the full argument, and `compute/__tests__/deployment-edge.test.ts` drives upstream's real diff. +**Why the producer edge rides `app`.** Upstream's `Prisma.Deployment` has no prop for "wait for these". Alchemy derives its dependency graph from the resource references a prop's *value* is built from, so the descriptor builds `app` as an Output over the app id and every output of the service's producers, resolving to the app id itself (`appAfter`): the graph gains the edges. The edge cannot ride `artifactPath` (or any of upstream's other replacement-block props): the diff reads that block as one unit and gives no opinion the moment any member is unresolved, which would skip the artifact comparison and silently drop a code change. [ADR-0048](../90-decisions/ADR-0048-prisma-cloud-resources-come-from-the-upstream-alchemy-provider.md) records the full argument, and `compute/__tests__/deployment-edge.test.ts` drives upstream's real diff. -**Change propagation is wired through `Prisma.Deployment.triggers`.** The platform freezes a deployment's environment at create, so a *value* change (a rotated URL) reaches a running service only through a new deployment. The compute descriptor declares one trigger member per environment row, carrying the same `Redacted` value the row writes; upstream folds the resolved members into a salted fingerprint inside its own encrypted state and plans a replacement exactly when one moved (and conservatively when a member cannot be resolved at plan time because the producing resource is itself changing). Unchanged service → same fingerprint → reuse; changed value or artifact → replace. Because upstream resolves the actual values, a value re-issued under a stable resource identity (a connection rotated in place, a re-minted service key) moves the fingerprint too. No plaintext lands in state — the members are `Redacted` in props and only the salted hash is persisted. A platform variable a row merely POINTS at (operator-owned; Composer never reads its value) contributes a `:updatedAt` member instead, read at preflight and handed to the lowering in the extension's preflight payload, so an out-of-band rotation still ships a new deployment. A service's input document is not an environment row and has no trigger member: it travels in the service's artifact, in the `inputDocument` field of `compute.bootstrap.json` ([ADR-0065](../90-decisions/ADR-0065-a-compute-services-input-document-travels-in-its-artifact.md)), so a changed document changes the artifact's bytes and its content-addressed `artifactPath`, which replaces the deployment. A platform variable the document names is still a `:updatedAt` member. +**Change propagation is wired through `variables` and `triggers`.** The platform copies a deployment's environment at create, so a *value* change (a rotated URL) reaches a running service only through a new deployment. Upstream records a salted hash of the resolved `variables` and plans a replacement when it moves, when a value cannot be resolved at plan time because the producing resource is itself changing, and when `variables` is declared on a deployment that recorded no hash. Unchanged service → same hash → reuse; changed value or artifact → replace. Because upstream resolves the actual values, a value re-issued under a stable resource identity (a connection rotated in place, a re-minted service key) replaces too. Every key the service reads at boot is in `variables`, as its value or `null`, and `SentVariableNames` adds `null` for every name Composer no longer sends, so it is deleted from the service ([ADR-0069](../90-decisions/ADR-0069-a-services-composer-keys-travel-with-its-deployment-as-service-variables.md)). The values are stored in deploy state in plain text: Alchemy writes every prop to state, and a `Redacted` value as its text; each is a value the deploy produced, never a platform variable's. A platform variable the service reads (operator-owned; Composer never holds its value) contributes a `:updatedAt` member to `triggers` instead, read at preflight and handed to the lowering in the extension's preflight payload, so an out-of-band rotation still ships a new deployment. A service's input document is not in `variables` and has no trigger member: it travels in the service's artifact, in the `inputDocument` field of `compute.bootstrap.json` ([ADR-0065](../90-decisions/ADR-0065-a-compute-services-input-document-travels-in-its-artifact.md)), so a changed document changes the artifact's bytes and its content-addressed `artifactPath`, which replaces the deployment. A platform variable the document names is still a `:updatedAt` member. -The compute descriptor constructs these edges (the `serialize` env-var records thread into `deploy` through the service SPI, and the producers' outputs come from the lowering context); no app author ever hand-wires them. +The compute descriptor constructs these edges (the `serialize` map threads into `deploy` through the service SPI, and the producers' outputs come from the lowering context); no app author ever hand-wires them. ## Related diff --git a/docs/design/05-prisma-cloud/build-reporting.md b/docs/design/05-prisma-cloud/build-reporting.md index db375abe6..7af6b6f6e 100644 --- a/docs/design/05-prisma-cloud/build-reporting.md +++ b/docs/design/05-prisma-cloud/build-reporting.md @@ -149,9 +149,9 @@ The mapping, keyed by upstream `@alchemy.run/prisma` type ids: | `Prisma.Bucket` | `bucket` | | `Prisma.App` | `app` | | `Prisma.Deployment` | `deployment` (also attaches the deployment to the build and records the app) | -| `Prisma.EnvironmentVariable` | `config_variable` | +| `Prisma.EnvironmentVariable` | `config_variable`. A hosted deploy declares none ([ADR-0069](../90-decisions/ADR-0069-a-services-composer-keys-travel-with-its-deployment-as-service-variables.md)), so the only ones reported are the rows an older Composer wrote, as `deleted`, on the first deploy with this version | | `Prisma.BucketAccessKey` | not reported; no platform type corresponds | -| `ServiceKey`, `PgWarm`, any other extension's resource | not reported; not a platform resource | +| `ServiceKey`, `PgWarm`, `SentVariableNames`, any other extension's resource | not reported; not a platform resource | | Terminal state status | Reported action | | --- | --- | diff --git a/docs/design/05-prisma-cloud/pdp-data-model.md b/docs/design/05-prisma-cloud/pdp-data-model.md index ff701ebe5..c02b5735f 100644 --- a/docs/design/05-prisma-cloud/pdp-data-model.md +++ b/docs/design/05-prisma-cloud/pdp-data-model.md @@ -83,16 +83,13 @@ This is the timing model Prisma Composer's graph must respect: | --- | --- | --- | | default DB provisioned | the platform **writes** `DATABASE_URL` and `DATABASE_URL_POOLED` as ordinary project-level production-class ConfigVariable **templates** (user-set values win) | `compute-config/wireDefaultDatabaseUrl.ts` | | any time | ConfigVariable rows are created/updated/deleted via the environment-variables API — **rows only; no effect on any existing version** | `routes/v1/environment-variables.ts` | -| **version create** | `materializeBranchEnvVars(app.branchId)` resolves the complete map — production branch → production templates; preview branch → preview templates merged with that branch's overrides (override wins) — decrypts it, and hands the **plain map to Foundry with the version**. The env is **frozen into the version** | `routes/v1/versions.ts` → `resolveDeployEnvVars.ts` → `compute-config/materializeBranchEnvVars.ts` | +| **version create** | `materializeBranchEnvVars(app.branchId)` resolves the branch's map — production branch → production templates; preview branch → preview templates merged with that branch's overrides (override wins) — and decrypts it; then the request's `variables`, when sent, are stored on the service (a string sets a key, `null` deletes it, a key not sent keeps its value), and every stored service variable is laid over the map. The plain map goes **to Foundry with the version**; the env is **frozen into the version** | `routes/v1/services.ts` (`POST /v1/services/{serviceId}/deployments`) → `interactors/compute/saveServiceVariablesAndDeploy.ts` → `compute-config/materializeBranchEnvVars.ts` | | version start | boots the version; **no env re-resolution** | `routes/v1/version-handlers.ts` | | promote | endpoint routed to the version; `serviceEndpointDomain` persisted. The domain returned at *create* names the domain the service will serve on | `interactors/compute/service.ts` | Consequences Prisma Composer designs around: -1. **A version's environment is a snapshot taken at version creation.** A config - value that must be visible to a service's code has to exist as a - ConfigVariable row *before* that service's version-create call (the failure - mode when it doesn't is documented as PRO-211 in `gotchas.md`). +1. **A version's environment is a snapshot taken at version creation.** A config value that must be visible to a service's code has to exist *before* that service's version-create call (the failure mode when it doesn't is documented as PRO-211 in `gotchas.md`). Composer sends a service's own keys in that call, as service variables, so they cannot arrive late ([ADR-0069](../90-decisions/ADR-0069-a-services-composer-keys-travel-with-its-deployment-as-service-variables.md)); a service variable wins over the branch's values. 2. **Changing config requires a new version to take effect.** There is no restart-on-config-change and no live re-resolution; a late-written variable never reaches an existing version. Propagating a changed value (e.g. a @@ -101,7 +98,7 @@ Consequences Prisma Composer designs around: the deployment, so the change reaches the running service (see the change-propagation note in [alchemy-lowering.md](alchemy-lowering.md#the-lowering-graphs)). -3. **`DATABASE_URL` is not a separate mechanism.** It is a platform-written template flowing through the same materialization as user variables — a convenience for hand-provisioned single services. The platform owns it (system-managed) and writes it only for a project's default database. Prisma Composer refuses to bind or manage the name and creates no default database (see [alchemy-lowering.md](alchemy-lowering.md#database_url-is-forbidden--and-left-to-the-platform)); every database URL a service consumes is an explicit, service-named variable. +3. **`DATABASE_URL` is not a separate mechanism.** It is a platform-written template flowing through the same materialization as user variables — a convenience for hand-provisioned single services. The platform owns it (system-managed) and writes it only for a project's default database. Prisma Composer refuses to bind or manage the name and creates no default database (see [alchemy-lowering.md](alchemy-lowering.md#database_url-is-forbidden--and-left-to-the-platform)); every database URL a service consumes is an explicit, service-named key. 4. **Branch + class is the platform's environments model** (production templates vs preview templates + per-branch overrides) — the substrate [an environment as a Branch](../10-domains/deploy-cli.md#environments-and-containers) is diff --git a/docs/design/10-domains/config-params.md b/docs/design/10-domains/config-params.md index 1ffcfbc39..86afb7dbe 100644 --- a/docs/design/10-domains/config-params.md +++ b/docs/design/10-domains/config-params.md @@ -80,16 +80,16 @@ Follow a compute service `web` in the app `shop`, with a `rawPostgres()` depende Config = { service: { port: 3000 }, inputs: { db: { url: 'postgres://…' } } } ``` -**Deploy: serialize and store (the target).** `@prisma/composer-prisma-cloud` encodes each value as one environment variable on the platform, keyed `COMPOSER_` plus the full address, upper-cased, with `.` and `-` turned into `_`, then the owner and name. Every generated key carries the `COMPOSER_` prefix, the framework's reserved namespace, kept clear of the platform variables the operator sets: +**Deploy: serialize and store (the target).** `@prisma/composer-prisma-cloud` encodes each value as one key in the `variables` of the service's deployment, which the platform stores on the service as a service variable ([ADR-0069](../90-decisions/ADR-0069-a-services-composer-keys-travel-with-its-deployment-as-service-variables.md)), keyed `COMPOSER_` plus the full address, upper-cased, with `.` and `-` turned into `_`, then the owner and name. Every generated key carries the `COMPOSER_` prefix, the framework's reserved namespace, kept clear of the platform variables the operator sets: ``` COMPOSER_SHOP_WEB_PORT = '3000' COMPOSER_SHOP_WEB_DB_URL = '"postgres://…"' ``` -The service's deployment depends on these variables, so it is created after the writes and replaced when a value changes. +The deployment is created with these keys, after every resource their values come from, and replaced when a value changes. A key with no value is sent as `null`, which deletes a value an earlier deploy stored. -**Boot: deserialize (the target).** The service's bootstrap reads the rows back and reverses the encoding: `port` is validated into a number, and the dependency's params into its connection values. +**Boot: deserialize (the target).** The service's bootstrap reads the keys back and reverses the encoding: `port` is validated into a number, and the dependency's params into its connection values. **Runtime.** The service reads the port through `service.port()` and its dependencies through `service.load()`, which hydrates them. Its input comes separately, from its input document, through `service.input()` ([ADR-0042](../90-decisions/ADR-0042-service-input-is-one-standard-schema.md)). diff --git a/docs/design/10-domains/core-model.md b/docs/design/10-domains/core-model.md index 9927d8456..5ab126e3f 100644 --- a/docs/design/10-domains/core-model.md +++ b/docs/design/10-domains/core-model.md @@ -588,13 +588,13 @@ interface ServiceLowering

{ // references — the whole stack effect runs before Alchemy applies anything. provision(ctx: LowerContext): Effect.Effect // serialize: encode the typed Config core built into the service's runtime - // environment (on Prisma Cloud: EnvironmentVariables on the project, and the - // input document for the artifact), keyed by the deployment address. + // environment (on Prisma Cloud: the keys of the deployment's `variables`, and + // the input document for the artifact), keyed by the deployment address. // The pack owns the encoding; run()'s deserialize reverses it through the same // serializer, so writer and reader cannot drift. Leaf values are provisioning - // refs → the env writes depend on the resources/producer (the ordering edges). - // Returns the env-var records so `deploy` can reference them (the environment - // edge — see alchemy-lowering.md), and whatever `package` puts in the artifact. + // refs → the deployment depends on the resources/producer (the ordering edges). + // Returns the encoded values so `deploy` can pass them (see + // alchemy-lowering.md), and whatever `package` puts in the artifact. serialize(ctx: LowerContext, provisioned: P, config: Config): Effect.Effect // package: assemble the deployable artifact from the build adapter's normalized @@ -778,19 +778,7 @@ nodes are edges only and never lower. Then for each service: 5. `deploy(artifact)` — the first version snapshots an environment that is already complete. -**How the ordering is actually enforced:** our walk only *assembles* Alchemy resource descriptions — Alchemy executes them in dependency order and runs unordered resources concurrently; declaration order is never consulted. So core realizes the sequence as **dependency edges**: most arise naturally from value flow (the env var consumes the project id and the producer's URL), and two do not. Deploy-after-serialize exists because the service descriptor builds the `Deployment`'s props out of the environment records it boots with, which is PDP's own dataflow restored (the deployment-create call literally contains the materialized env map). Deploy-after-producers exists because the service descriptor also builds them out of its producers' outputs, so a consumer's deployment is created after its producers go live. See the lowering graphs in -[`../05-prisma-cloud/alchemy-lowering.md`](../05-prisma-cloud/alchemy-lowering.md). -This is what makes the fresh-deploy config race (PRO-211) structurally impossible -on every target — the edge's **ordering** job. Its second job, **propagating** -a wire whose value genuinely changes, is wired by the deploy hook: a deploy -whose environment differs from the running deployment's replaces the -deployment, so changed values reach the running service. Secret *values* are -never hashed or persisted for this — the mechanism keys off the non-secret -material Composer's rows carry (ADR-0042 pointers) and platform metadata. The -long-term carrier is the deployment resource itself (inputs it must be -recreated for), tracked as an upstream follow-up. -Secrets are platform-sourced and rotate through the platform, not this edge (see -the [input glossary entry](../03-domain-model/glossary.md#input)). +**How the ordering is actually enforced:** our walk only *assembles* Alchemy resource descriptions — Alchemy executes them in dependency order and runs unordered resources concurrently; declaration order is never consulted. So core realizes the sequence as **dependency edges**: most arise naturally from value flow (the consumer's deployment `variables` consume the producer's URL and the database connection), and two do not. Deploy-after-serialize exists because the service descriptor builds the `Deployment`'s props out of the values it boots with, which is PDP's own dataflow (the deployment-create call carries the service's variables). Deploy-after-producers exists because the service descriptor also builds them out of its producers' outputs, so a consumer's deployment is created after its producers go live. See the lowering graphs in [`../05-prisma-cloud/alchemy-lowering.md`](../05-prisma-cloud/alchemy-lowering.md). This is what makes the fresh-deploy config race (PRO-211) structurally impossible on every target — the edge's **ordering** job. Its second job, **propagating** a wire whose value genuinely changes, is wired by the deploy hook: a deploy whose environment differs from the running deployment's replaces the deployment, so changed values reach the running service. On Prisma Cloud the carrier is the deployment resource itself: a salted hash of its `variables`, and a `:updatedAt` trigger per platform variable it reads, whose value Composer never holds (ADR-0069). Secrets are platform-sourced and rotate through the platform, not this edge (see the [input glossary entry](../03-domain-model/glossary.md#input)). **Deployment identity — address, bootstrap, and why.** A node's identity is its **address**: the path of provision ids starting at the root, assigned by Load from graph position. The root's address is the deployed app name, so every address starts with it (`shop`, `shop.catalog`, `shop.auth.api`). A provision id is the node's name unless `provision()` sets an `id`, and the path qualifies it, so registry modules with common internal names (`db`, `service`) cannot collide. Identity cannot travel through the environment: every App in a Project boots a byte-identical env (ConfigVariables are project+branch-scoped and snapshotted at version create — see the [PDP data model](../05-prisma-cloud/pdp-data-model.md)), so any "who am I" variable is one shared key, last write wins. The only per-service channel is the artifact itself. Hence the bootstrap: the artifact's entrypoint takes identity as a parameter, and deploy is the caller. The Compute artifact the pack assembles: @@ -1087,27 +1075,29 @@ export const prismaCloud = (opts: PrismaCloudOptions = {}): ExtensionDescriptor return { serviceId: svc.appId, projectId: projectIdOf(application), endpointDomain: svc.appEndpointDomain } // : ComputeProvisioned }), - // Encode the typed Config into the runtime environment — one env var per - // leaf, keyed by the SAME serializer run() reads with at boot. Values are - // the provisioning refs core built the Config from, so each env var depends - // on its resource/producer (the ordering edges). Returns the records deploy - // must depend on, plus the resolved listen port. + // Encode the typed Config into the runtime environment — one key per + // leaf, keyed by the SAME serializer run() reads with at boot, `null` + // when it has no value. Values are the provisioning refs core built the + // Config from, so the deployment depends on its resource/producer (the + // ordering edges). A record of every name ever sent adds `null` for each + // name Composer no longer sends. Returns the map deploy sends, plus the resolved listen port. serialize: ({ address, node, graph }, provisioned, config) => Effect.gen(function* () { - const records = [] + const bootVariables = {} for (const d of configOf(node)) { const value = d.owner === "service" ? config.service[d.name] : config.inputs[d.owner.input]?.[d.name] - if (value === undefined) continue - records.push(yield* Prisma.EnvironmentVariable(`${address}.env.${configKey(address, d)}`, { - project: provisioned.projectId, key: configKey(address, d), - value: Redacted.make(encode(d.owner, value)), class: "production", - })) + bootVariables[configKey(address, d)] = value === undefined ? null : Redacted.make(encode(d.owner, value)) } + const everSent = yield* SentVariableNames(`${address}.sent-variable-names`, { names: Object.keys(bootVariables).sort() }) + const requestVariables = Output.map(everSent.names, (names) => ({ + ...Object.fromEntries(names.map((name) => [name, null])), + ...bootVariables, + })) // The input document is not a variable: its text travels in the artifact. const binding = graph.inputBindings.find((b) => b.serviceAddress === address)?.binding const input = serializeInput(node, address, binding) const port = typeof config.service.port === "number" ? config.service.port : 3000 - return { environment: records, port, ...(input !== undefined ? { input } : {}) } // : ComputeSerialized → deploy's edges, package's document + return { bootVariables, requestVariables, port, ...(input !== undefined ? { input } : {}) } // : ComputeSerialized → deploy's variables, package's document }), // Print the bootstrap and assemble the deployable artifact from the build @@ -1118,10 +1108,9 @@ export const prismaCloud = (opts: PrismaCloudOptions = {}): ExtensionDescriptor package: ({ id }, { assembled, address }, serialized) => Effect.try(() => Prisma.packageComputeArtifact({ id, bundleDir: assembled.dir, appEntry: assembled.entry, address, inputDocument: serialized.input && JSON.parse(serialized.input.value) })), - // create → upload → start → promote. The app id is read through - // serialize's env-var records and every output of its producers, so the - // deployment is created after its rows are written (PRO-211) and after - // its producers are promoted. Returns a LoweredResult: `url` IS + // create (with the variables) → upload → start → promote. The app id is + // read through every output of its producers, so the deployment is + // created after its producers are promoted. Returns a LoweredResult: `url` IS // published here — a Compute service's deployed URL is a public endpoint, // and this descriptor is the only party that knows it. It is the App's // domain, not the deployment's: the deployment is promoted on every @@ -1135,8 +1124,9 @@ export const prismaCloud = (opts: PrismaCloudOptions = {}): ExtensionDescriptor .flatMap((edge) => Object.values(lowered.get(edge.from) ?? {})) .filter(Output.isOutput) const deployment = yield* Prisma.Deployment(`${address}.deployment`, { - app: appAfter(provisioned.serviceId, serialized.environment, producerOutputs), + app: appAfter(provisioned.serviceId, producerOutputs), artifactPath: artifact.path, + variables: serialized.requestVariables, artifactContentType: "application/gzip", portMapping: { http: serialized.port }, start: true, promote: true, }) diff --git a/docs/design/10-domains/local-dev.md b/docs/design/10-domains/local-dev.md index cf99a7170..036380219 100644 --- a/docs/design/10-domains/local-dev.md +++ b/docs/design/10-domains/local-dev.md @@ -294,18 +294,7 @@ A start in flight ends with the first of these that applies: The exit of a process the emulator no longer tracks is ignored. -The env materialization is the one platform-side behavior the local target -implements itself: the hosted platform joins the branch's config variables -into a deployment at version-create; locally, the `Deployment` provider -performs the same join from the `EnvironmentVariable` records the lowering -emitted — against props defined in this repo, once, not an emulation of a -foreign API. One pinned deviation: the local join is scoped to the -service's own rows (plus any row outside the `COMPOSER_` namespace, which is -a platform-owned name by definition), because the platform -diffs a deployment only on its own referenced rows while an app-wide local -snapshot diffs on bytes — which restart-amplified dependents on every -first-after-cold converge. No sanctioned reader consumes sibling rows, so -the scoping changes restart behavior only. +The env materialization is the one platform-side behavior the local target implements itself: the hosted platform copies a service's variables into a deployment at version-create; locally, the `Deployment` provider builds the same environment from the `variables` the lowering gave the deployment ([ADR-0069](../90-decisions/ADR-0069-a-services-composer-keys-travel-with-its-deployment-as-service-variables.md)), leaving out a key sent as `null`, then lays the port the emulator assigned over `COMPOSER_

_PORT` and adds the platform variables the service reads — against props defined in this repo, once, not an emulation of a foreign API. A changed `variables` is a changed prop, so it restarts exactly the service that reads it. A dev server has no deployment: its rows, which `reserve` declares, are in `env.json`, and its environment is built from the rows under its own address (plus any row outside the `COMPOSER_` namespace, which is a platform-owned name by definition), so a sibling's row never changes it. The Postgres and bucket emulators follow the same model: a database is an instance with a generated id (`db_<16 hex digits>`), served by a @@ -478,8 +467,8 @@ semantics): | `Database` | the database instance the directory's record names for the resource, on its own `@prisma/dev` server hosted by the Postgres emulator; started if stopped, created when missing; `databaseId` is the instance id | | `Connection` | the URL of the database instance its `Database` names | | `App` | finds the service's Compute instance through the directory's record, creating it when there is none; the instance holds the service's port; `appEndpointDomain = http://localhost:` — which makes origin (ADR-0039) work unchanged. Deleting it deletes the instance | -| `Deployment` | unpacks the artifact once per hash, reads the input document from its `compute.bootstrap.json`, materializes the env, and puts the deployment at the service's Compute instance, which (re)starts the child; updated when its instance does not run the recorded artifact | -| `EnvironmentVariable` | a key→value row in the dev state store | +| `Deployment` | unpacks the artifact once per hash, reads the input document from its `compute.bootstrap.json`, materializes the env from its `variables`, and puts the deployment at the service's Compute instance, which (re)starts the child; updated when its instance does not run the recorded artifact | +| `EnvironmentVariable` | a key→value row in the dev state store (`env.json`); only `reserve` declares one, for a dev server | | `Bucket` | the bucket instance the directory's record names for the resource, over a directory under `.prisma-composer/dev//buckets///`, served by the bucket emulator; `bucketId` is the instance id, also its S3 name | | `BucketKey` | credentials registered with the bucket emulator for its bucket | | `ServiceKey` | **unchanged** — mints locally, persists in state | @@ -552,7 +541,7 @@ The worker thread of a `prisma dev` converge runs no adapter. The main thread pa A rebuild runs no dev preflight, so a read of a platform variable that a code change adds would have no value. `prisma dev` therefore sends each converge's worker thread the reads of the graph it started with (`valueReads`: reader, node and path) and each read node's address and `props`. The worker, which has just loaded the app as it is on disk, compares them with its own graph's before it converges. If either differs, it does not converge; `prisma dev` emits the `value-reads-changed` event with the nodes whose reads were added, removed or changed, and pauses rebuilds until it is restarted. If the first converge sees a difference, which usually means an app file changed while `prisma dev` was starting, and otherwise that a module body builds a different graph each time it runs, `prisma dev` stops and names the reads that changed. For a rebuild the CLI prints a warning: `The platform variables the app reads changed since dev started: reads of "shop.smtpPort" were added, reads of "shop.emailFrom" were removed, and "shop.sender" was changed. Restart dev to apply them; rebuilds are paused until then.` An edit that adds or removes a node fails the rebuild with a message that says to restart `prisma dev`. -The local `Deployment` provider gives each service only the variables its own input reads: the `$platform` markers in its input document, at any depth. For a service that runs its artifact, it reads the input document for this from the unpacked artifact's `compute.bootstrap.json`, with the reader `@internal/lowering` exports next to the packer. It ignores a `COMPOSER_
_INPUT` entry in `env.json` for such a service, whether or not the artifact holds a document, and does not put that key into the process's environment, because the artifact's bootstrap passes the document to `run()`. For a service that runs a dev server, which has no artifact, the compute descriptor's `reserve` writes the input document as a `COMPOSER_
_INPUT` variable, which the local target keeps in `env.json` with the service's other rows. This isolation is a requirement of the local target only. On Prisma Cloud every deployment receives every variable of its class. +The local `Deployment` provider gives each service only the variables its own input reads: the `$platform` markers in its input document, at any depth. For a service that runs its artifact, it reads the input document for this from the unpacked artifact's `compute.bootstrap.json`, with the reader `@internal/lowering` exports next to the packer. It does not read `env.json` for such a service, and the artifact's bootstrap passes the document to `run()`. For a service that runs a dev server, which has no artifact, the compute descriptor's `reserve` writes the input document as a `COMPOSER_
_INPUT` row, which the local target keeps in `env.json` with the service's other rows. This isolation is a requirement of the local target only. On Prisma Cloud every deployment receives every variable of the group its branch receives. To load `.env` files, list `dotenv()` in `config` and `secrets`, with `environmentVariables()` after it to keep the shell. It reads `.env`, `.env.local`, `.env.` and `.env..local` beside `prisma.config.ts`, through `dotenv-flow`, and skips `.env.local` for the environment `test`. Values in `.env.dev` are read only by the environment `dev`; values in `.env` and `.env.local` are read by every environment, `prisma deploy` to `production` included. The deploy does not copy a secret to the platform, but a plain value there reaches the root's input in every environment. `import 'dotenv/config'` at the top of `prisma.config.ts` still works with the default lists; remove it when you list `dotenv()`. diff --git a/docs/design/90-decisions/ADR-0032-params-bind-at-provision-to-a-literal-or-a-deploy-time-value.md b/docs/design/90-decisions/ADR-0032-params-bind-at-provision-to-a-literal-or-a-deploy-time-value.md index 288945376..380f06c98 100644 --- a/docs/design/90-decisions/ADR-0032-params-bind-at-provision-to-a-literal-or-a-deploy-time-value.md +++ b/docs/design/90-decisions/ADR-0032-params-bind-at-provision-to-a-literal-or-a-deploy-time-value.md @@ -37,7 +37,7 @@ A param takes no source: not a platform variable node's value, not `generatedPar - A provision-time literal or deploy-time value is schema-validated when config is built, and beats the `default`. - A required param that nothing binds fails the deploy loudly. -- The deploy writes each param as one JSON-encoded row, `COMPOSER_
_`, and boot reads it back with the param's schema ([ADR-0019](ADR-0019-the-target-owns-config-serialization.md)). No param row names a variable on the platform. +- The deploy sends each param as one JSON-encoded key, `COMPOSER_
_`, with the service's deployment ([ADR-0069](ADR-0069-a-services-composer-keys-travel-with-its-deployment-as-service-variables.md)), and boot reads it back with the param's schema ([ADR-0019](ADR-0019-the-target-owns-config-serialization.md)). No param names a variable on the platform. - A value change needs a redeploy: a deployment snapshots its environment at creation. - Where a compute service's port is set is not decided: through this per-key param, or somewhere else such as the build options. diff --git a/docs/design/90-decisions/ADR-0039-a-compute-services-own-origin-is-a-target-resolved-property.md b/docs/design/90-decisions/ADR-0039-a-compute-services-own-origin-is-a-target-resolved-property.md index a863e21d7..bc4fcfff5 100644 --- a/docs/design/90-decisions/ADR-0039-a-compute-services-own-origin-is-a-target-resolved-property.md +++ b/docs/design/90-decisions/ADR-0039-a-compute-services-own-origin-is-a-target-resolved-property.md @@ -44,12 +44,7 @@ the service will serve on. The framework never string-builds the URL from a region map — that would couple it to the platform's URL convention and break silently if the scheme changed (the no-guessing rule, ADR-0005). -**The framework supplies the value in every environment**, like any other -config: deploy writes the row unconditionally; a test harness sets -`COMPOSER_ORIGIN` exactly as it sets other `COMPOSER_*` rows; a local runner -writes it because it binds the port. Calling `origin()` where nothing supplied -the row is an ordinary loud missing-config error, raised lazily at the call so -services that never read it are unaffected. +**The framework supplies the value in every environment**, like any other config: deploy sends the key unconditionally (ADR-0069); a test harness sets `COMPOSER_ORIGIN` exactly as it sets other `COMPOSER_*` keys; a local runner gives it because it binds the port. Calling `origin()` where nothing supplied the row is an ordinary loud missing-config error, raised lazily at the call so services that never read it are unaffected. ## Consequences diff --git a/docs/design/90-decisions/ADR-0041-local-dev-runs-the-deploy-pipeline-against-local-providers.md b/docs/design/90-decisions/ADR-0041-local-dev-runs-the-deploy-pipeline-against-local-providers.md index a82fe718e..162b7f61e 100644 --- a/docs/design/90-decisions/ADR-0041-local-dev-runs-the-deploy-pipeline-against-local-providers.md +++ b/docs/design/90-decisions/ADR-0041-local-dev-runs-the-deploy-pipeline-against-local-providers.md @@ -82,23 +82,11 @@ three clusters: | Cluster | Resources | Local implementation | | --- | --- | --- | -| Compute | `ComputeService`, `Deployment`, `EnvironmentVariable` | a Compute **emulator** owning one child process per service, plus a local env-var store | +| Compute | `ComputeService`, `Deployment`, `EnvironmentVariable` | a Compute **emulator** owning one child process per service, plus a local env-var store for dev servers | | Postgres | `Project`, `Database`, `Connection` | the ORM CLI's local Postgres **emulator** (`prisma dev`) | | Buckets | `Bucket`, `BucketKey` | a bucket **emulator**: the storage module's existing S3 wire handler + SigV4 verifier over a disk-backed object store — objects are plain files at their key paths | -**The target runs one emulator per node kind — the platform's primitives, -locally.** The extension's `emulators` hook inspects the loaded topology and -ensures a machine-scoped emulator daemon per node kind the app uses: a -**Compute emulator** (runs service processes), the **Postgres emulator** (the -ORM's `prisma dev` — its daemon manager is the ORM CLI's own), and a **bucket -emulator** (the S3 wire over disk). Each emulator is multi-tenant and -long-lived — the firebase/supabase model — and is capable of creating an -*isolated instance* of its node type: a running service, a database, a -bucket. The local providers provision those instances by communicating with -the emulators during converge, and the orchestration wires the instances to -each other through the same lowered `EnvironmentVariable` records a deploy -produces — the topology composes locally exactly as it does on the platform. -Emulator instances are removed only by `--fresh`, through `teardown`. +**The target runs one emulator per node kind — the platform's primitives, locally.** The extension's `emulators` hook inspects the loaded topology and ensures a machine-scoped emulator daemon per node kind the app uses: a **Compute emulator** (runs service processes), the **Postgres emulator** (the ORM's `prisma dev` — its daemon manager is the ORM CLI's own), and a **bucket emulator** (the S3 wire over disk). Each emulator is multi-tenant and long-lived — the firebase/supabase model — and is capable of creating an *isolated instance* of its node type: a running service, a database, a bucket. The local providers provision those instances by communicating with the emulators during converge, and the orchestration wires the instances to each other through the same lowered values a deploy produces — the `variables` of each service's `Deployment` ([ADR-0069](ADR-0069-a-services-composer-keys-travel-with-its-deployment-as-service-variables.md)), or, for a dev server, the `EnvironmentVariable` rows `reserve` declares — so the topology composes locally exactly as it does on the platform. Emulator instances are removed only by `--fresh`, through `teardown`. **Converge terminates; the Compute emulator keeps serving.** Alchemy's converge is a run-to-completion program (ADR-0007 drives it in a child @@ -135,16 +123,7 @@ assembly consumes, never sources; the user's own watcher (`next dev` is not involved — `tsdown --watch`, `bun build --watch`, whatever their build does) produces the rebuild, and dev responds by re-running assemble and converge. -**A service boots exactly as deployed.** The artifact's bootstrap calls -`run(address, boot, inputDocument)` with the input document the artifact's -`compute.bootstrap.json` holds -([ADR-0065](ADR-0065-a-compute-services-input-document-travels-in-its-artifact.md)), -against the same `COMPOSER_*` environment protocol a deploy's platform -injection produces — the local `Deployment` provider materializes that -environment from the same `EnvironmentVariable` records the lowering emitted, -and reads the artifact's input document to work out which platform variables -the service's process receives. Deserialization, stashing, -`load()`/`config()`/`secrets()` all execute the deployed code path. +**A service boots exactly as deployed.** The artifact's bootstrap calls `run(address, boot, inputDocument)` with the input document the artifact's `compute.bootstrap.json` holds ([ADR-0065](ADR-0065-a-compute-services-input-document-travels-in-its-artifact.md)), against the same `COMPOSER_*` environment protocol a deploy's platform injection produces — the local `Deployment` provider materializes that environment from the same `variables` the lowering gave the deployment, leaving out a key sent as `null`, and reads the artifact's input document to work out which platform variables the service's process receives. Deserialization, stashing, `load()`/`config()`/`secrets()` all execute the deployed code path. ## Reasoning @@ -277,6 +256,7 @@ this repo owns. provisioning seam that every extension must implement and keep from drifting, duplicating exactly the orchestration the deploy pipeline already performs — and contradicting goals.md's stand-in-beside-provider shape. +- **Every service's keys in the local env-var store.** The position before ADR-0069: the local `Deployment` provider read each service's own rows from `env.json`, which the lowering's `EnvironmentVariable` records filled. A deployment now carries its keys in `variables`, and only a dev server, which has no deployment, keeps rows. - **Direct-injection boot** (`service.runLocal(values)` — hand the service its hydrated bindings, bypassing the env wire protocol). Retained as a *testing* convenience only. Dev drives the real `run(address, boot)` path so that diff --git a/docs/design/90-decisions/ADR-0044-errors-are-structural-envelopes-with-dotted-namespace-codes.md b/docs/design/90-decisions/ADR-0044-errors-are-structural-envelopes-with-dotted-namespace-codes.md index c95a18501..53e479409 100644 --- a/docs/design/90-decisions/ADR-0044-errors-are-structural-envelopes-with-dotted-namespace-codes.md +++ b/docs/design/90-decisions/ADR-0044-errors-are-structural-envelopes-with-dotted-namespace-codes.md @@ -64,7 +64,7 @@ Closed subcode registry: - `CONFIG` — SECTION_MISSING, FIELD_INVALID, FIELD_UNKNOWN, FIELD_RETIRED, FILE_MISSING, FILE_RETIRED, EXTENSION_DUPLICATE, EXTENSION_MISSING, DESCRIPTOR_MISSING, DESCRIPTOR_KIND_MISMATCH, ENTRY_MISSING, ADAPTER_FAILED, ADAPTER_INVALID, SECRET_AS_PLAIN_VALUE *(EXPORT_INVALID, PATH_MISMATCH and EVALUATION_FAILED retired by [ADR-0049](ADR-0049-composers-configuration-is-the-composer-section-of-prisma-config.md))*. ENTRY_MISSING: neither `entry` in the `composer` section nor `--entry`, or the operation's `entry` input, names the entry module. ADAPTER_FAILED: a config or secrets adapter threw or rejected; its message is redacted. ADAPTER_INVALID: an adapter returned something other than an object of values, or a secrets adapter returned a value that is not text. SECRET_AS_PLAIN_VALUE: a plain value Load read would contain a known secret, a value under a secrets key the graph names; `deploy` raises it before anything is created, `destroy` and `prisma dev` before they write the app configuration file. The error names the field or configuration key and the secrets key, never the value. - `COMPOSE` — ENTRY_UNLOADABLE, ENTRY_EXPORT_INVALID, ROOT_NOT_MODULE, NAME_MISSING, GRAPH_INVALID. ENTRY_EXPORT_INVALID: the entry's default export is not the app's root, an app root built with `appRoot()` or a module built with `module()`. ROOT_NOT_MODULE: the entry default-exports a service; the fix provisions the service inside an `appRoot()` root. Both are raised before Load, by every command that loads the entry. - `ASSEMBLE` — EXTENSION_MISSING, DESCRIPTOR_MISSING, DESCRIPTOR_KIND_MISMATCH, SERVICE_MISSING, BUILD_FAILED -- `DEPLOY` — FLAG_INVALID, TARGET_CONFLICT, TARGET_MISSING, TARGET_NOT_FOUND, ENVIRONMENT_INVALID, ENVIRONMENT_UNVALIDATABLE, ENVIRONMENT_REQUIRED, CONTAINER_FAILED, PREFLIGHT_FAILED, ENGINE_FAILED, TEARDOWN_FAILED, CONTAINER_REMOVE_FAILED, BUILD_REQUIRED, INTERRUPTED, CONVERGE_RUNNING, WORKER_THREAD, MANAGEMENT_API_URL_CONFLICT *(STAGE_INVALID, STAGE_UNVALIDATABLE and SCOPE_MISSING retired by [ADR-0059](ADR-0059-a-deployment-environment-is-called-an-environment.md); ALCHEMY_BIN_MISSING, NODE_MISSING and STACK_WRITE_FAILED retired by [ADR-0068](ADR-0068-destroy-runs-alchemy-in-process.md))*. ENVIRONMENT_REQUIRED: a `destroy` call names no environment. ENGINE_FAILED: Alchemy failed. `deploy` and `destroy` run Alchemy in process ([ADR-0066](ADR-0066-deploy-runs-alchemy-in-process.md), [ADR-0068](ADR-0068-destroy-runs-alchemy-in-process.md)); `prisma deploy` exits 2. INTERRUPTED: the abort signal stopped the plan or apply of a `deploy` or a `destroy`. `prisma deploy` exits 130 (143 for SIGTERM): it reports this code as a message event and ends with the engine's abort, `CLI.ABORTED`. CONVERGE_RUNNING: another in-process converge holds this process's working directory and the reporter variables it sets in the environment. WORKER_THREAD: `deploy` or `destroy` was called from a worker thread with a `cwd` other than the process's working directory, which a worker cannot change. MANAGEMENT_API_URL_CONFLICT: the deploy was given a Management API client, and `PRISMA_API_URL` names another host than the one that client sends to (`PRISMA_MANAGEMENT_API_URL`, or `https://api.prisma.io`). Raised by the Prisma Cloud extension when it resolves the environment's container, for `deploy` and `destroy`, and when it builds its providers or its state store, for `deploy`. +- `DEPLOY` — FLAG_INVALID, TARGET_CONFLICT, TARGET_MISSING, TARGET_NOT_FOUND, ENVIRONMENT_INVALID, ENVIRONMENT_UNVALIDATABLE, ENVIRONMENT_REQUIRED, CONTAINER_FAILED, PREFLIGHT_FAILED, ENGINE_FAILED, TEARDOWN_FAILED, CONTAINER_REMOVE_FAILED, BUILD_REQUIRED, INTERRUPTED, CONVERGE_RUNNING, WORKER_THREAD, MANAGEMENT_API_URL_CONFLICT, SERVICE_VARIABLE_LIMIT *(STAGE_INVALID, STAGE_UNVALIDATABLE and SCOPE_MISSING retired by [ADR-0059](ADR-0059-a-deployment-environment-is-called-an-environment.md); ALCHEMY_BIN_MISSING, NODE_MISSING and STACK_WRITE_FAILED retired by [ADR-0068](ADR-0068-destroy-runs-alchemy-in-process.md))*. ENVIRONMENT_REQUIRED: a `destroy` call names no environment. ENGINE_FAILED: Alchemy failed. `deploy` and `destroy` run Alchemy in process ([ADR-0066](ADR-0066-deploy-runs-alchemy-in-process.md), [ADR-0068](ADR-0068-destroy-runs-alchemy-in-process.md)); `prisma deploy` exits 2. INTERRUPTED: the abort signal stopped the plan or apply of a `deploy` or a `destroy`. `prisma deploy` exits 130 (143 for SIGTERM): it reports this code as a message event and ends with the engine's abort, `CLI.ABORTED`. CONVERGE_RUNNING: another in-process converge holds this process's working directory and the reporter variables it sets in the environment. WORKER_THREAD: `deploy` or `destroy` was called from a worker thread with a `cwd` other than the process's working directory, which a worker cannot change. MANAGEMENT_API_URL_CONFLICT: the deploy was given a Management API client, and `PRISMA_API_URL` names another host than the one that client sends to (`PRISMA_MANAGEMENT_API_URL`, or `https://api.prisma.io`). Raised by the Prisma Cloud extension when it resolves the environment's container, for `deploy` and `destroy`, and when it builds its providers or its state store, for `deploy`. SERVICE_VARIABLE_LIMIT: the app declares more values for one Compute service than Prisma Cloud stores on a service; the summary names the service, the count and the limit. Raised by the Prisma Cloud extension while it plans the service, before any resource is created, changed or deleted, for `deploy` and for `prisma dev`, which refuses what a deploy would ([ADR-0069](ADR-0069-a-services-composer-keys-travel-with-its-deployment-as-service-variables.md)). It is reported today as the tag of one of the reasons of `DEPLOY.ENGINE_FAILED` for `deploy`, and of `DEV.CONVERGE_FAILED` for `prisma dev`. - `DEV` — PLATFORM_UNSUPPORTED, TARGET_UNSUPPORTED, CONTAINER_FAILED, TEARDOWN_FAILED, PREFLIGHT_FAILED, EMULATOR_FAILED, SERVICE_START_FAILED, CONVERGE_FAILED, ATTACH_FAILED, EMULATORS_DIR_INVALID, EMULATOR_UNREACHABLE, SERVICE_READY_TIMEOUT_INVALID, NOT_STARTED_HERE, ADDRESS_UNKNOWN, NOT_RUNNING, INTERRUPTED, CONVERGE_RUNNING, WORKER_THREAD, ENVIRONMENT_WRITE_FAILED *(STACK_WRITE_FAILED retired by [ADR-0067](ADR-0067-prisma-dev-converges-in-a-worker-thread.md): `prisma dev` writes no stack file)*. CONVERGE_FAILED: a dev converge failed or could not start. When the engine failed, it carries the tag and message of each error the engine failed with. It is also raised, with no engine errors, when the first converge sees other reads of platform variables than dev prepared for, and when a rebuild finds a node added or removed, or a root input field the root did not pass on at start. An error raised before the converge with a code of its own, such as `COMPOSE.ENTRY_UNLOADABLE`, fails the first converge under that code. INTERRUPTED: the abort signal stopped the first converge. CONVERGE_RUNNING: another converge in this process, a deploy's or a dev session's, holds the working directory. WORKER_THREAD: `dev` was called from a thread that cannot change the process's working directory, with a `cwd` other than that directory; only the main thread can change it. ENVIRONMENT_WRITE_FAILED: the dev environment's folder could not be written. EMULATOR_UNREACHABLE is raised by the emulator client when it cannot connect, so `log` raises it under `DEV` too; for a connection failure it takes the place of SERVICE_START_FAILED, ATTACH_FAILED and `LOG.ATTACH_FAILED`. `devUrl` also raises it when the emulator a node runs on is not running. NOT_STARTED_HERE (no `prisma dev` has recorded an app in the directory) is raised by `devUrl` and `devStop`; ADDRESS_UNKNOWN (the recorded app has no node at that address; the known addresses are listed) and NOT_RUNNING (the node exists but is not running; its state is named, and the reason and fix depend on it) by `devUrl` alone ([ADR-0053](ADR-0053-dev-url-dev-stop-and-emulator-list.md)). Both operations raise EMULATOR_FAILED when the local target fails without a code. `emulator list` fails only with EMULATORS_DIR_INVALID; an emulator it cannot list is reported in that emulator's entry with EMULATOR_UNREACHABLE or EMULATOR_FAILED. - `LOG` — PLATFORM_UNSUPPORTED, ATTACH_FAILED, ADDRESS_UNKNOWN - `DEPS` — EXECUTOR_UNLOADABLE, EXTENSION_INCOMPATIBLE, CONVERGE_UNRESOLVABLE, CONVERGE_CONTRACT_MISMATCH *(EFFECT_VERSION_CONFLICT retired by [ADR-0049](ADR-0049-composers-configuration-is-the-composer-section-of-prisma-config.md))*. EXTENSION_INCOMPATIBLE: an installed extension is older than the Composer running the deploy or destroy, so the container it resolved, rebuilt through its own `deserialize`, does not name the environment that was asked for. CONVERGE_UNRESOLVABLE: `deploy` cannot load `@prisma/composer/internal/converge` from the app's own install, or that install predates it ([ADR-0066](ADR-0066-deploy-runs-alchemy-in-process.md)). CONVERGE_CONTRACT_MISMATCH: the app's `@prisma/composer` speaks another converge contract than the `prisma` CLI's Composer; the message names both contract numbers and both package versions, and the fix says which side to upgrade. Different package versions with the same contract are accepted. diff --git a/docs/design/90-decisions/ADR-0048-prisma-cloud-resources-come-from-the-upstream-alchemy-provider.md b/docs/design/90-decisions/ADR-0048-prisma-cloud-resources-come-from-the-upstream-alchemy-provider.md index 4ba87166f..8b1e3e2df 100644 --- a/docs/design/90-decisions/ADR-0048-prisma-cloud-resources-come-from-the-upstream-alchemy-provider.md +++ b/docs/design/90-decisions/ADR-0048-prisma-cloud-resources-come-from-the-upstream-alchemy-provider.md @@ -4,8 +4,6 @@ Amended by [ADR-0057](ADR-0057-a-nodes-address-is-its-full-path-from-the-app-nam Amended 2026-10-30: from Alchemy 2.0.0-beta.84 the provider is its own package, `@alchemy.run/prisma`, versioned in lockstep with `alchemy`; before that it was the `alchemy/Prisma` module of the `alchemy` package. Only `@prisma/composer-prisma-cloud` and the Prisma Cloud internals it bundles depend on it; `@prisma/composer` and `@prisma/composer-cli` depend on `alchemy` alone. The move kept every resource type id (`Prisma.*`), so deploy state carries over unchanged. The decision below is unchanged. -Amended 2026-11-20: a compute service's published `url` is its App's `appEndpointDomain`, not its Deployment's: the Deployment is updated on every deploy, so its domain is unknown while planning, and every consumer's deployment, whose `triggers` hold the url, would be replaced on every deploy. A consumer's deployment waits for its producers' promotion through the deployment's `app` prop, which also carries every output of the nodes it depends on (a compute producer's `serviceId` resolves only after its promotion), never through `triggers`, so an unchanged consumer is reused. - ## Decision Composer does not implement Alchemy resources for Prisma Cloud's Management API. It composes the official upstream Prisma provider's (`@alchemy.run/prisma`, formerly `alchemy/Prisma`) resources and providers, and defines its own resources only where the upstream provider has no support yet (buckets, whose routes upstream deferred) or where no Management API exists behind them (local mechanisms like migration steps). @@ -20,7 +18,7 @@ Layer.mergeAll( Prisma.ConnectionProvider(), Prisma.AppProvider(), Prisma.DeploymentProvider(), - Prisma.EnvironmentVariableProvider(), + providerForDeletingOldVariableRows(), // upstream's, deleting the rows an older Composer wrote (ADR-0069) ), // + Composer's own resources: Bucket, BucketKey, ServiceKey, // GeneratedParam, S3Credentials, OrmMigration, PgWarm @@ -30,10 +28,11 @@ and a lowered compute service is upstream resources wired by Composer's descript ```ts const app = Prisma.App(`${id}-svc`, { project, regionId, branchId }); -const vars = records.map((r) => Prisma.EnvironmentVariable(...)); const deployment = Prisma.Deployment(`${id}-deploy`, { - app: appAfter(app, vars, producerOutputs), // see "The ordering edge" below - artifactPath, // Composer's own tar.gz — never built by Alchemy + app: appAfter(app.appId, producerOutputs), // see "The ordering edge" below + artifactPath, // Composer's own tar.gz — never built by Alchemy + variables, // the service's COMPOSER_ keys (ADR-0069) + triggers, // one `:updatedAt` per platform variable it reads start: true, promote: true, }); @@ -45,34 +44,39 @@ Why hand Composer's most platform-critical surface to an external package: the p ## The compute family binds the low-level trio, not `Prisma.Compute` -Upstream offers two shapes for compute: a composite `Prisma.Compute` that owns app, environment, and deployment in one resource, and the low-level `App` / `Deployment` / `EnvironmentVariable`. Composer uses the low-level trio. The deciding constraint is a cycle: +Upstream offers two shapes for compute: a composite `Prisma.Compute` that owns app, environment, and deployment in one resource, and the low-level `App` / `Deployment` / `EnvironmentVariable`. Composer uses `App` and `Deployment`; `EnvironmentVariable` is declared only by `prisma dev` for a dev server, and its hosted provider stays registered to delete rows an older Composer wrote ([ADR-0069](ADR-0069-a-services-composer-keys-travel-with-its-deployment-as-service-variables.md)). The deciding constraint is a cycle: -Every service's environment includes `COMPOSER_
_ORIGIN` — the service's *own* platform-assigned endpoint domain (ADR-0039). A composite resource that owns both the environment rows and the app makes that row an input of the very resource that produces the domain: a self-edge the planner rejects. Split, the wiring is legal: the App exists first and hands out `appEndpointDomain`, environment rows are written from it, the Deployment comes last. +Every service's environment includes `COMPOSER_
_ORIGIN` — the service's *own* platform-assigned endpoint domain (ADR-0039). A composite resource that owns both the environment and the app makes that value an input of the very resource that produces the domain: a self-edge the planner rejects. Split, the wiring is legal: the App exists first and hands out `appEndpointDomain`, and the Deployment is created with the value in its `variables`. Two supporting reasons: -- `Compute` owns environment rows through an internal ownership map and refuses in-scope rows absent from it; Composer's per-key rows have no honest mapping into that map. +- `Compute` manages environment rows through an internal ownership map and refuses in-scope rows absent from it; Composer's keys are service variables on the create-deployment request, which that map does not describe. - `Compute` carries build, framework detection, and bundling. Its `artifactPath` prop bypasses them, but a bypass is a prop value; `Prisma.Deployment` has **no build path at all**, which is ADR-0005's guarantee in structural form. What the trio costs: `Compute`'s preview/stable health checks and automatic rollback are not inherited, and deployment reuse must be handled by Composer (next two sections). ## The ordering edge rides the `app` prop -Environment rows must be written before the deployment is created, because the platform snapshots the branch environment into a deployment at create. Upstream's `Deployment` has no prop for that dependency, so Composer builds the edge into the `app` prop: an Output over the app id *and* every whole environment resource, resolving to the app id (`lowering/src/compute/deployment-edge.ts`). A persisted variable ID is stable and can resolve while its value update is still pending; depending on that ID loses the ordering edge. Whole-resource references preserve the dependency on completion of the writes, including updates to existing variables. Alchemy derives its graph from those resource references inside prop values, so every row is scheduled first. +A consumer's deployment must not go live before its producers', or a consumer could call a method its producer has only just added. A compute service publishes its App's `appEndpointDomain` as its `url`, not its Deployment's: the Deployment is updated on every deploy, so its domain is unknown while planning, and every consumer whose `variables` hold the url would be replaced on every deploy. The App exists before any deployment, so the url alone orders nothing. Upstream's `Deployment` has no prop for that dependency, so Composer builds the edge into the `app` prop: an Output over the app id *and* every output of the nodes the service depends on, resolving to the app id (`appAfter` in `lowering/src/compute/deployment-edge.ts`). A compute producer's `serviceId` output comes from its Deployment and resolves only after the producer is promoted. Alchemy derives its graph from the resource references inside prop values, so every producer is promoted first, and an unchanged consumer is still reused because nothing in its `variables` or `triggers` changes. -The edge must not ride `artifactPath`. Upstream's diff reads `{portMapping, skipCodeUpload, artifactPath, artifactContentType}` as one block and offers no opinion when any member is unresolved — and a brand-new environment row is always unresolved at plan time. The consequence of getting this wrong is severe and quiet: the artifact comparison never runs, the engine falls back to a plain update, and the reconcile keeps the running deployment while recording the new artifact's fingerprint as deployed — a code change silently never ships, and every later deploy agrees it already did. The `app` prop sits outside that block and tolerates being unresolved. `compute/__tests__/deployment-edge.test.ts` drives upstream's real diff and real Output machinery and fails if the edge ever moves back. +The edge must not ride `artifactPath`. Upstream's diff reads `{portMapping, skipCodeUpload, artifactPath, artifactContentType}` as one block and offers no opinion when any member is unresolved — and an output of a resource the same deploy is changing is unresolved at plan time. The consequence of getting this wrong is severe and quiet: the artifact comparison never runs, the engine falls back to a plain update, and the reconcile keeps the running deployment while recording the new artifact's fingerprint as deployed — a code change silently never ships, and every later deploy agrees it already did. The `app` prop sits outside that block and tolerates being unresolved. `compute/__tests__/deployment-edge.test.ts` drives upstream's real diff and real Output machinery and fails if the edge ever moves back. ## A deployment is replaced when its environment changes -The platform bakes environment values into a deployment at create, and upstream reuses a deployment whose artifact is unchanged — so a value-only change (a rotated secret) would update the platform's variable row and never reach the running app. Composer closes this by declaring each service's environment values as `Prisma.Deployment.triggers` (upstream's replacement-inputs prop, shipped in alchemy 2.0.0-beta.74; designed as `redeployOn` and renamed in review): one `Redacted` member per environment row, carrying the same value the row writes. Alchemy resolves the members, folds them into a salted fingerprint inside its own encrypted state, and plans a replacement exactly when one moved — unchanged service, same fingerprint, deployment reused; changed value or artifact, replace. A service's input document is not an environment row: it travels in the artifact ([ADR-0065](ADR-0065-a-compute-services-input-document-travels-in-its-artifact.md)), so a changed document changes the artifact and replaces the deployment that way. A member that cannot be resolved at plan time (its producing resource is itself changing in the same deploy) replaces conservatively, and the first deploy that declares triggers records its fingerprint through a plain update rather than forcing a replacement. +The platform copies a service's environment into a deployment when it creates it, and upstream reuses a deployment whose artifact is unchanged — so a value-only change (a rotated secret) must replace the deployment to reach the running app. Two props of `Prisma.Deployment` carry the values whose change replaces it. + +- **`variables`**, the service's `COMPOSER_` keys ([ADR-0069](ADR-0069-a-services-composer-keys-travel-with-its-deployment-as-service-variables.md)). Upstream records a salted hash of the resolved map and plans a replacement when the hash changes, when a value is not resolved at plan time (its producing resource is itself changing in the same deploy), and when the prop is declared on a deployment that recorded no hash, because an update creates no deployment and the values would never reach the platform. Because upstream resolves the actual values, a value re-issued under a stable resource identity (a connection rotated in place, a re-minted service key) replaces too. +- **`triggers`** (upstream's replacement-inputs prop, shipped in alchemy 2.0.0-beta.74; designed as `redeployOn` and renamed in review), with one member per platform variable the service reads. Composer never holds such a variable's value, so its out-of-band rotation is detected through its `updatedAt` metadata, read at preflight and passed to the lowering as a value (a timestamp, never a variable's value), and joined as a `:updatedAt` member. Upstream folds the members into a salted fingerprint and replaces when one moved; a member unresolved at plan time replaces conservatively, and the first deploy that declares `triggers` records its fingerprint through a plain update. + +A service's input document is in neither: it travels in the artifact ([ADR-0065](ADR-0065-a-compute-services-input-document-travels-in-its-artifact.md)), so a changed document changes the artifact and replaces the deployment that way. -No plaintext reaches state: members are `Redacted` in props, and only the salted hash is persisted. Because alchemy resolves the actual values, a value re-issued under a stable resource identity (a connection rotated in place, a re-minted service key) moves the fingerprint too — the narrowing the earlier Composer-side fingerprint (a hash of non-secret environment material folded into the artifact path, deleted with the beta.74 bump) had to accept is closed. A pointed platform variable Composer never writes still has no value to trigger on; its out-of-band rotation is detected through its `updatedAt` metadata, read at preflight, carried to the Alchemy process over the framework's preflight-transport channel (a timestamp, never a value), and joined as a `:updatedAt` trigger member. +The values in `variables` are stored in deploy state in plain text: Alchemy writes every prop to state, and writes a `Redacted` value as its text. `Redacted` keeps them out of logs and error messages. Each is a value the deploy produced, never a platform variable's value, which the deploy never holds. ## Consequences - **Namespaces.** The `Prisma.*` resource type-id namespace and the `'Prisma'` collection tag belong to upstream. Composer's collection tag is `'PrismaComposer'` and its own resources are `PrismaComposer.*`. Rows persisted under retired Composer type-ids are rewritten on read by the hosted state store (`state/legacy-resources.ts`): ids, attribute shapes, and the retirement of the `DATABASE_URL` claim rows that earlier versions tracked as resources (see "Claim both names with a placeholder" under Alternatives considered). The module is the durable compatibility boundary for state written by earlier Composer versions. Scope: "legacy" here means rows already INSIDE the platform state API (ADR-0045), written under retired type-ids or shapes. The older generation — the retired SQL `prisma-composer-state` stores — stays under ADR-0045's own rule: never read, cleaned up by destroy or Branch deletion. The two rules govern different stores and do not overlap. - **Branch-stage databases carry generated physical names.** Upstream refuses an explicit name combined with branch attachment at create — and it is right to: the Management API creates the database and attaches the branch in separate transactions with no idempotency key, so a lost response is indistinguishable from a foreign database. Attaching after create does not survive either: upstream's reconcile detaches a branch its props don't declare. So branch stages attach at create and take the generated name; production keeps explicit names. -- **The platform's `DATABASE_URL` is left alone.** Prisma Cloud writes `DATABASE_URL`/`DATABASE_URL_POOLED` only when a project is created with a database, or when a database is created as the project's default, and marks them system-managed; upstream refuses to manage system-managed variables. Composer creates projects without a database and never creates a default one, so the platform writes neither on a Composer project. Composer never creates, overwrites, updates, deletes, or tracks either variable. The guarantee that apps read configuration through the framework is held at the authoring end: `variable()` and `variable.secret()` reject the reserved names (`variable-name.ts`), and every row Composer writes is `COMPOSER_`-prefixed. An app that reads `process.env.DATABASE_URL` directly sees whatever the platform or the user put there. +- **The platform's `DATABASE_URL` is left alone.** Prisma Cloud writes `DATABASE_URL`/`DATABASE_URL_POOLED` only when a project is created with a database, or when a database is created as the project's default, and marks them system-managed; upstream refuses to manage system-managed variables. Composer creates projects without a database and never creates a default one, so the platform writes neither on a Composer project. Composer never creates, overwrites, updates, deletes, or tracks either variable. The guarantee that apps read configuration through the framework is held at the authoring end: `variable()` and `variable.secret()` reject the reserved names (`variable-name.ts`), and every key Composer sends is `COMPOSER_`-prefixed. An app that reads `process.env.DATABASE_URL` directly sees whatever the platform or the user put there. - **Auth never touches Alchemy's profile store.** Alchemy's own credential flow prompts on a TTY and hard-fails non-interactive; Composer runs alchemy as a subprocess with piped stdio. Composer provides `PrismaEnvironment` directly from `PRISMA_SERVICE_TOKEN`, with one base-URL resolver shared between upstream's providers and Composer's own SDK client so both always target the same host. - **A known weakness is inherited:** upstream retries a conflicting App delete for only a few seconds, where Composer's own resource waited out deployment drain for minutes. Slow drains can fail a destroy and need a re-run. @@ -82,6 +86,8 @@ No plaintext reaches state: members are `Redacted` in props, and only the salted - **The composite `Prisma.Compute`.** Rejected for the self-edge, the environment-ownership map, and ADR-0005 (above). - **Vendor the provider's source into Composer.** Mechanically possible; inherits its dependencies and permanent drift. Kept only as a fallback if a future alchemy upgrade proves unshippable. - **Adopt upstream's built-in dev mode instead of the local target.** Would replace a whole-layer seam that already works with per-provider substitution, and tie local-dev iteration to an external release cadence. +- **Write each `COMPOSER_` key as a `Prisma.EnvironmentVariable` row, ordered before the deployment through the `app` prop, with one `triggers` member per row repeating its value.** The position before ADR-0069. The `app` edge held every whole row resource, because a persisted variable ID can resolve while its value update is still pending. Rows were branch overrides on preview, which the platform is removing; the record of that change is ADR-0069. +- **Take a consumer's url from its producer's Deployment.** Its domain is unknown while planning, so every consumer would be replaced on every deploy. - **Replace the deployment on every deploy** (the pre-adoption behavior). Ships every change by brute force but gives up upstream's reuse entirely; superseded first by the Composer-side fingerprint, then by `Deployment.triggers`. - **Claim both names with a placeholder.** Earlier versions wrote `"-"` under `DATABASE_URL` and `DATABASE_URL_POOLED`, in the production and preview classes at project level, so the platform could not put a live credential there. The first versions did it through tracked `EnvironmentVariable` resources, so the rows were in deploy state; later versions did it with create-only calls outside deploy state. Both rested on the belief that the platform fills in a missing `DATABASE_URL` on the first Compute deploy from any ready database in the project. The platform does not do that, so on a Composer project the rows protected nothing. Rows already written stay on existing projects. State entries from the tracked form are dropped on read by `state/legacy-resources.ts`, with no call to the platform. - **Hash environment values Composer-side.** A bare hash of a secret in a plaintext path or state row is an offline-guessing target; rejected. The interim Composer-side fingerprint therefore hashed only material that was non-secret by construction (accepting the re-issued-value narrowing above); upstream's `triggers` avoids the exposure differently — a salted fingerprint computed and persisted inside alchemy's own state, never a bare hash of a secret in the open. diff --git a/docs/design/90-decisions/ADR-0056-prisma-dev-runs-a-service-with-its-build-adapters-dev-server.md b/docs/design/90-decisions/ADR-0056-prisma-dev-runs-a-service-with-its-build-adapters-dev-server.md index eef452250..4477dbe7f 100644 --- a/docs/design/90-decisions/ADR-0056-prisma-dev-runs-a-service-with-its-build-adapters-dev-server.md +++ b/docs/design/90-decisions/ADR-0056-prisma-dev-runs-a-service-with-its-build-adapters-dev-server.md @@ -216,7 +216,7 @@ export interface ServiceLowering

{ In core's lowering loop, for an address in `unassembled`: `provision` and `serialize` run as always; the bundle lookup and `missingBundleError` are skipped; `package` is not called; `reserve` is called with the same `ctx`, `provisioned` and `serialized` that `deploy` would get; its result is stored in `lowered` and `entries` exactly as `deploy`'s is. A descriptor without `reserve` fails the lowering with a `LowerError` whose message is ``service "

" runs a dev server but its descriptor (/) has no `reserve` step``, which `prisma dev` reports as `DEV.DEV_SERVER_UNSUPPORTED`. An address in `unassembled` that is also in `bundles`, or that is not a service, is a `LowerError` naming it. -The Prisma Cloud compute descriptor's `reserve` creates the service's input document as a variable, `COMPOSER_
_INPUT`, because there is no artifact to carry it, and returns what its `deploy` returns with the `Deployment` removed: `outputs: { url: provisioned.app.appEndpointDomain, projectId: provisioned.projectId }` and the one `compute-service` entity with `id: provisioned.serviceId`, `url` the same, and the `details` built from `serialized.input` exactly as in `deploy`. Locally the App's `appEndpointDomain` is `http://localhost:` from the instance, the same string the `Deployment` would have reported, so dependents' rows do not change between a run that serves a service and one that does not, and dependents do not restart. +The Prisma Cloud compute descriptor's `reserve` declares a local variable row for each of the service's keys that is not `null` and one for its input document, `COMPOSER_
_INPUT`, because there is no deployment to carry the keys and no artifact to carry the document ([ADR-0069](ADR-0069-a-services-composer-keys-travel-with-its-deployment-as-service-variables.md)). It fails as a bug in any application other than the local, branchless one, so no row reaches Prisma Cloud. It returns what its `deploy` returns with the `Deployment` removed: `outputs: { url: provisioned.app.appEndpointDomain, projectId: provisioned.projectId }` and the one `compute-service` entity with `id: provisioned.serviceId`, `url` the same, and the `details` built from `serialized.input` exactly as in `deploy`. Locally the App's `appEndpointDomain` is `http://localhost:` from the instance, the same string the `Deployment` would have reported, so dependents' rows do not change between a run that serves a service and one that does not, and dependents do not restart. The dev stack file renders `unassembled` from `Object.keys(assembled.devServers)`: @@ -257,7 +257,7 @@ export interface LocalTargetAttachment { The Prisma Cloud target's `serve`: 1. Finds the service's instance through the directory's record (`ensureServiceInstance(scope, address)`, which creates none here because the converge already did), taking its `id` and `port`. -2. Materializes the deployment environment with the existing `materializeEnv(devDir, address, port)`: the service's own rows from `env.json` (`scopedEnvRows`), `COMPOSER_
_PORT`, the current values of the variables its rows point at (every value in `secrets.json` until [ADR-0058](ADR-0058-prisma-dev-reads-secrets-from-the-app-secrets-and-never-invents-them.md)), and `PATH` and `HOME` from the shell. The service's rows include its input document, which `reserve` wrote. +2. Materializes the deployment environment with `materializeEnv(devServerRows(devDir, address), address, port, …)`: the service's own rows from `env.json` (`scopedEnvRows`), `COMPOSER_
_PORT`, the current values of the variables its rows point at (every value in `secrets.json` until [ADR-0058](ADR-0058-prisma-dev-reads-secrets-from-the-app-secrets-and-never-invents-them.md)), and `PATH` and `HOME` from the shell. The service's rows are the ones `reserve` wrote, its input document included. 3. Applies the stash to it (next section), producing the address-free rows, `PORT` and `HOST`. 4. Builds the command's environment as `{ ...process.env, ...materialized, ...stashed }`, in that order, dropping entries whose value is `undefined`. 5. Calls `server.argv({ port, host: '0.0.0.0' })`. diff --git a/docs/design/90-decisions/ADR-0057-a-nodes-address-is-its-full-path-from-the-app-name.md b/docs/design/90-decisions/ADR-0057-a-nodes-address-is-its-full-path-from-the-app-name.md index 8f63a6fc6..138c7b978 100644 --- a/docs/design/90-decisions/ADR-0057-a-nodes-address-is-its-full-path-from-the-app-name.md +++ b/docs/design/90-decisions/ADR-0057-a-nodes-address-is-its-full-path-from-the-app-name.md @@ -71,7 +71,7 @@ One node lowers to several Alchemy resources: a postgres resource becomes a Data | Node | Main resource | Other pieces | | --- | --- | --- | -| compute service `shop.web` | App `shop.web` | Deployment `shop.web.deployment`, one environment variable row per key `shop.web.env.`, generated values `shop.web.generated.`, RPC service keys `shop.web.servicekey.`, a streams key `shop.web.streamkey` | +| compute service `shop.web` | App `shop.web` | Deployment `shop.web.deployment`, the record of keys sent `shop.web.sent-variable-names`, under `prisma dev` for a dev server one environment variable row per key `shop.web.env.`, generated values `shop.web.generated.`, RPC service keys `shop.web.servicekey.`, a streams key `shop.web.streamkey` | | postgres resource `shop.catalog` | Database `shop.catalog` | Connection `shop.catalog.connection`, `shop.catalog.warmup`, `shop.catalog.migration` | | bucket `shop.uploads` | Bucket `shop.uploads` | access key `shop.uploads.accesskey` | @@ -87,7 +87,7 @@ These IDs cannot collide with an address. Every node is either a module, which h Composer passes a service its configuration as environment variables in the reserved `COMPOSER_` namespace, which apps cannot declare. A key is `COMPOSER_`, the address's segments upper-cased and joined with `_`, then the owner and name of the value: the address `my-shop.api` gives `COMPOSER_MY_SHOP_API_…`. App names may contain `-`, which is not valid in a POSIX variable name, so `-` is replaced by `_`. Within this format that replacement cannot make two keys collide: one app has one root name, and below the root the segments are letters and digits only. The move from the previous format can, and is handled below. -On the app's own Branch a key identifies the variable the way `logicalId` identifies a row. +On a service a key identifies the service variable the way `logicalId` identifies a row. ### `serviceOrigin` takes the full address @@ -118,9 +118,9 @@ Three properties make this safe, and each was checked on the real platform: Every platform name Composer writes is the node's address: the App's `displayName`, a local dev Database's `name`, and the Connection, Bucket and bucket access key `name` (`shop.catalog`, `shop.auth.api`). There is one form of a node's name, and it is the address. Names are labels, never identity. Upstream adds `-` and a 12-character token to every Connection name, so a Connection's platform name is the address plus that suffix (`shop.catalog-`). On the upgrade deploy every one of these names changes from the short address to the full one. App, Database and Bucket names update in place; a Bucket's display name is not its S3 bucket name, so its objects stay where they are. Upstream replaces a Connection when its `name` changes, and a bucket access key when its `name` changes. So the upgrade recreates each of Composer's Connections and access keys with new credentials, and Composer's services receive the new credentials in the same deploy. The replace deletes only the old Connection or key, by the id Composer stored, so the database, the bucket and its objects, and any Connection or key made by hand are untouched. A hosted database takes no name from Composer, because upstream refuses a name together with branch attachment: upstream derives its physical name from the resource ID, and updates it in place when the ID changes. -An environment variable row is replaced whenever its key changes, and every key changes in this migration. That is harmless: Composer writes every row's value on every deploy, so the new row holds the same value as the old one, and a changed environment already makes a new Deployment. +Every key changes in this migration. The release that made it wrote each key as an environment variable row; since [ADR-0069](ADR-0069-a-services-composer-keys-travel-with-its-deployment-as-service-variables.md) the keys are sent with the deployment and no row is written, so a key that changes is simply sent under its new name. -During the move a new key can equal a key the previous release wrote for a different row, because every key is upper-cased and `-` becomes `_`. That happens when a module or service directly below the root has the app's name in any letter case (in the app `shop`, `shop.x` gets `COMPOSER_SHOP_X_…`, the old key of `shop.shop.x` or of the service `shop.shop`'s input `x`), or when modules spell an app name that contains `-` or `_` (`my-shop.x` and `my-shop.my.shop.x`). The old row still holds that key while the deploy runs, so creating the new row would fail partway. Deploy preflight therefore computes every row's new and old key from the graph, and while the old owner's row still holds a clashing key on the stage and has not moved to its new key, it fails the deploy. By then the Branch's application topology has been replaced with the new one and the build recorded. No resource the app declares has been created, changed or deleted, and the deploy state is unchanged. Every clashing variable is reported in one run, including a chain (`shop.x`, `shop.shop.x`, `shop.shop.shop.x`). The error names the variable, the node that owns it under the old format and the node that takes it over, and the fix: delete that one variable (`prisma project env delete --project --role production`, or `--branch `, or in the Console), then deploy again. Nothing is lost, because the deploy writes every value under its new key and running deployments keep their own copy. A new stage, or one that has moved, never fails this check. +During the move a new key can equal a key the previous release wrote for a different row, because every key is upper-cased and `-` becomes `_`. That happens when a module or service directly below the root has the app's name in any letter case (in the app `shop`, `shop.x` gets `COMPOSER_SHOP_X_…`, the old key of `shop.shop.x` or of the service `shop.shop`'s input `x`), or when modules spell an app name that contains `-` or `_` (`my-shop.x` and `my-shop.my.shop.x`). Releases from 0.35.0 to 0.39.0 wrote rows and refused such a deploy in preflight until the old row was deleted. This release writes no rows, so nothing collides, and the check is gone. One case remains for an app that upgrades straight from a release before full addresses: a service whose new key equals another service's old key, and which has no value for that key, receives the other service's old row once, until Alchemy deletes the row at the end of that deploy. Such an app deploys once with a release from 0.35.0 to 0.39.0 first. Local dev creates no platform rows. Its per-directory record of which emulator instance backs each node (ADR-0052) is keyed by address, and the local providers find each node's instance by its main resource ID, which is that address. The record now carries a format version. A record without it was written before this decision: on the first `prisma dev` after upgrading, Composer puts the app name in front of every one of its keys and writes the record back with the version, so local services, databases and buckets keep their instances, ports and data. A bucket's objects stay in the folder named by its address without the app name, which is already inside the app's own folder, so nothing moves. Alchemy's local deploy state goes through the same rename declarations as the hosted state. @@ -135,8 +135,8 @@ Local dev creates no platform rows. Its per-directory record of which emulator i - A stage migrated by this decision and then deployed by an older Composer has its resources deleted and recreated under the old IDs, losing their data. Nothing protects against this. - Each platform name is checked against that kind's limit: a Connection name at most 52 characters (the platform allows 65, and upstream's suffix takes 13, so the address is never cut), a Bucket name 100, an App name 256; an access key name has none. A long app name counts against every one of them. A name over its limit fails the deploy with a message naming the node's address; Composer never shortens a name. Fixing it means changing the address, which makes the node a different entity. - Anything outside Composer that used the old Connection string or access key of a Composer resource stops working after the upgrade, because those credentials are deleted. -- An app whose move gives one row's new `COMPOSER_` key to another row's old key stops at deploy preflight, before any resource is created, changed or deleted (the Branch's topology has already been replaced), until each old variable it names is deleted. Renaming a node instead would give it a new identity and delete its rows. -- A `logicalId` says which node a row is, so on the app's own Project and Branch the row holding a node's `logicalId` is that node's row. A deploy uses that row even when its deploy state has no record of it. The usual case is resuming a create that was interrupted after the platform created the row but before Alchemy recorded its ID. Composer therefore declares its App, Database and Bucket resources, and its `COMPOSER_` environment variables, as its own (Alchemy's per-resource `adopt(true)`), so Alchemy does not refuse a row it cannot otherwise prove it created. The Project is found the same way, by `logicalId`, in container resolution. +- An app that upgrades from a release before full addresses deploys once with a release from 0.35.0 to 0.39.0 first, so that no old row holds a key another service now owns. +- A `logicalId` says which node a row is, so on the app's own Project and Branch the row holding a node's `logicalId` is that node's row. A deploy uses that row even when its deploy state has no record of it. The usual case is resuming a create that was interrupted after the platform created the row but before Alchemy recorded its ID. Composer therefore declares its App, Database and Bucket resources as its own (Alchemy's per-resource `adopt(true)`), so Alchemy does not refuse a row it cannot otherwise prove it created. The Project is found the same way, by `logicalId`, in container resolution. - Using a row means owning it: Composer updates it to the declared configuration, and deletes it when the node is removed, when its address changes, or when the stage is destroyed. A row created outside Composer with one of the app's addresses on its Branch is treated as that node's row. Two apps with the same name in one workspace share one Project and share rows instead of failing. - A stage whose Branch holds rows but which has no deploy state at all is still refused before the deploy starts (ADR-0045). The rows could be identified, but the rest of the state could not be rebuilt from them: generated parameter values would be minted again, Connections would not be recognized, and Deployments and bucket access keys would be created twice. - Destroy does not use rows it has no record of. Destroying a stage right after an interrupted deploy leaves the half-created row: for a named stage, deleting its Branch removes it; for production, deploy once more before destroying, or delete the row by hand. @@ -151,6 +151,7 @@ Local dev creates no platform rows. Its per-directory record of which emulator i - **Resolve `serviceOrigin`'s argument relative to the module the call is written in.** That is a second way to write an address, and it means different things in different files. - **Let the first deploy after upgrading recreate everything under the new IDs.** It deletes every database's and bucket's data, regenerates secrets and rotates service keys. - **Keep the address without the app name as the platform name of Apps, Connections, Buckets and access keys**, to avoid recreating Connections and access keys on the upgrade. That is a second form of a node's name. +- **Refuse the deploy in preflight while an old row holds a key another node now owns**, and tell the operator to delete it. The position until ADR-0069; with no rows written, two rows cannot collide. - **Use Alchemy's default `logicalId` (its resource ID).** It happens to equal the address for a node's main resource now, but it would then depend on Composer's internal naming and on upstream's defaulting rule. Composer passes the address explicitly so the topology and the row are written from the same value. - **Write `logicalId` with a separate Composer resource after the row is created.** Duplicates what the upstream resource does (ADR-0048), and puts two resources in charge of one field. When they disagree, they fight on every deploy. - **Put platform `id`s in the topology.** The `id`s don't exist when the topology is written, before the apply. They also differ on every branch, so they can't say "the same service on `main`". diff --git a/docs/design/90-decisions/ADR-0064-an-app-declares-its-platform-variables-in-its-root-and-the-deploy-copies-no-local-values.md b/docs/design/90-decisions/ADR-0064-an-app-declares-its-platform-variables-in-its-root-and-the-deploy-copies-no-local-values.md index ae92b8c41..124e26ffd 100644 --- a/docs/design/90-decisions/ADR-0064-an-app-declares-its-platform-variables-in-its-root-and-the-deploy-copies-no-local-values.md +++ b/docs/design/90-decisions/ADR-0064-an-app-declares-its-platform-variables-in-its-root-and-the-deploy-copies-no-local-values.md @@ -45,7 +45,7 @@ The environment's facts, such as `environment.name`, and the values Composer cre ### What Prisma Cloud does - **A variable is a row in a project.** A row has `projectId`, `class` (`production` or `preview`), an optional `branchId`, a `key` and a `value`. A row with no `branchId` is the class's shared value. A row with one is that preview branch's override. Prisma Cloud calls these rows environment variables. -- **A deployment receives the rows of its class, with its branch's overrides on top.** A **scope** is a level at which a row can be set and at which a reader looks it up. Today there are two: the class and the branch. When a name has a row at both, the more local one, the branch row, wins. The platform copies the rows into the deployment when it creates it and never reads them again, so a value set later reaches a service only at its next deployment. There is no service scope: every deployment receives every row of its class, its own and other services' alike. The list filter accepts only `projectId`, `class`, `key` and `branchId`. +- **A deployment receives the rows of its class, with its branch's overrides on top.** A **scope** is a level at which a row can be set and at which a reader looks it up. Today there are two: the class and the branch. When a name has a row at both, the more local one, the branch row, wins. The platform copies the rows into the deployment when it creates it and never reads them again, so a value set later reaches a service only at its next deployment. A third scope, the service, holds values stored on one service and wins over both; Composer sends its own `COMPOSER_` keys there ([ADR-0069](ADR-0069-a-services-composer-keys-travel-with-its-deployment-as-service-variables.md)), and preflight does not look there. Every deployment receives every row of its class, its own and other services' alike. The list filter accepts only `projectId`, `class`, `key` and `branchId`. - **A key is upper case or it does not exist.** The platform refuses a key that does not match `[A-Z_][A-Z0-9_]*`, on write and in the list filter. - **A value is never empty.** The platform refuses an empty value, so a variable is either present with text or absent. - **A read returns metadata, never a value.** It returns `updatedAt`, and `isManagedBySystem` for a row the platform owns. @@ -264,7 +264,7 @@ The local target plays the platform's part. **The schema decides, as a black box.** [ADR-0042](ADR-0042-service-input-is-one-standard-schema.md) forbids reading a schema's internals. Leaving variables out and calling `validate` asks the schema exactly whether it can do without them, with no value and no introspection. -**One call per name, not per scope.** The list filter by class and key already returns the class row and every branch row. Listing the whole class would return every branch's `COMPOSER_` rows on a preview project. +**One call per name, not per scope.** The list filter by class and key already returns the class row and every branch row. Listing the whole class would also return every branch's overrides on a preview project, including `COMPOSER_` rows an older Composer wrote. **Upper-case names.** The platform accepts no other key, and Composer compares pointer names without case while a process environment on Linux compares them with case. With upper-case names a row and a name never differ by case, so boot finds the row preflight saw. diff --git a/docs/design/90-decisions/ADR-0065-a-compute-services-input-document-travels-in-its-artifact.md b/docs/design/90-decisions/ADR-0065-a-compute-services-input-document-travels-in-its-artifact.md index 7e19e6ed1..67e7dc50b 100644 --- a/docs/design/90-decisions/ADR-0065-a-compute-services-input-document-travels-in-its-artifact.md +++ b/docs/design/90-decisions/ADR-0065-a-compute-services-input-document-travels-in-its-artifact.md @@ -6,7 +6,7 @@ Take the service `shop.web`, declared with an input schema and bound like this: provision(web, { input: { siteName: 'Shop', stripeKey } }); // stripeKey: the platform secret STRIPE_SECRET_KEY ``` -A deploy to Prisma Cloud writes these variables on the branch for it: +A deploy to Prisma Cloud sends these keys with the service's deployment, which stores them on the service ([ADR-0069](ADR-0069-a-services-composer-keys-travel-with-its-deployment-as-service-variables.md)): ```text COMPOSER_SHOP_WEB_PORT 3000 @@ -28,11 +28,11 @@ and this into the service's artifact, in `compute.bootstrap.json`: } ``` -A deploy that kept every value in a variable would also have written `COMPOSER_SHOP_WEB_INPUT` as a fourth variable, holding the same document as text, and the artifact would have had no `inputDocument` field. +A deploy that kept every value in a variable would also have sent `COMPOSER_SHOP_WEB_INPUT` as a fourth key, holding the same document as text, and the artifact would have had no `inputDocument` field. ## Decision -On Prisma Cloud, the deploy writes a Compute service's input document into the service's artifact, in the `inputDocument` field of `compute.bootstrap.json`, as nested JSON rather than as a string that holds JSON. It creates no variable for it. A service that declares no input has no `inputDocument` field. Every other value the service reads at boot stays a variable on the platform: `port`, each dependency's connection params, the provider params (the RPC accepted keys, the streams key, the service's origin) and each generated value. +On Prisma Cloud, the deploy writes a Compute service's input document into the service's artifact, in the `inputDocument` field of `compute.bootstrap.json`, as nested JSON rather than as a string that holds JSON. It sends no key for it. A service that declares no input has no `inputDocument` field. Every other value the service reads at boot is a key sent with its deployment and stored on the service ([ADR-0069](ADR-0069-a-services-composer-keys-travel-with-its-deployment-as-service-variables.md)): `port`, each dependency's connection params, the provider params (the RPC accepted keys, the streams key, the service's origin) and each generated value. The artifact is the input document's only source. At boot the artifact's `bootstrap.js` passes the document to the service's `run(address, boot, inputDocument)`, which puts it in place of any `COMPOSER_
_INPUT` variable in the environment it reads. Under `prisma dev`, the local target does not use such a variable for a service that runs its artifact. An app's author writes nothing differently: `service.input()`, `service.load()` and `service.port()` behave as before. @@ -48,26 +48,26 @@ So the document is neither secret nor issued by the platform, and it is final be - **It is not limited to a variable's size.** A Prisma Cloud variable's value is limited to 8 KB, and the input document grows with every field the service declares. In the artifact it is not limited to 8 KB. - **The settings stay with the code they were checked against.** The deploy checks the document against the service's schema and then packs both into one artifact. -- **One variable fewer per service** on the branch, and one resource fewer for the deploy to create and track. +- **One key fewer per service**, toward the platform's limit of 50 service variables. ### The other values cannot -Every other value a Compute service reads at boot is issued during the deploy or is a secret, except `port`: +Every other value a Compute service reads at boot is issued during the deploy or is a secret, except `port`, so each is a key sent with the deployment: -| Value | Why it stays a variable | +| Value | Why it is not in the artifact | | --- | --- | -| `port`, the only param a Compute service declares itself | It is not part of the input document: the app binds it at provision to a literal or a deploy-time value, or it takes its default ([ADR-0032](ADR-0032-params-bind-at-provision-to-a-literal-or-a-deploy-time-value.md)), and the deploy writes it as its own variable. Under `prisma dev` the Compute emulator assigns each instance its port and the local target writes this variable from it, so the artifact must not fix it. | +| `port`, the only param a Compute service declares itself | It is not part of the input document: the app binds it at provision to a literal or a deploy-time value, or it takes its default ([ADR-0032](ADR-0032-params-bind-at-provision-to-a-literal-or-a-deploy-time-value.md)), and the deploy sends it as its own key. Under `prisma dev` the Compute emulator assigns each instance its port and the local target lays it over this key, so the artifact must not fix it. | | Each dependency's connection params | The platform issues them during the deploy, and most are secrets. | | The provider params: the RPC accepted keys, the streams key, the service's origin | Issued or generated during the deploy; the keys are secrets. | | Each generated value, `COMPOSER_
__GENERATED` | A generated secret. | -The artifact is built before the values issued during the deploy exist. A secret has no place in a file that is uploaded and stored with the code. And `port` must stay a variable, so that under `prisma dev` the local target can give each instance the port the Compute emulator assigned it. Two things keep secrets out of the artifact. `serializeInput` keeps secret values out of the document. And `compute.bootstrap.json` has one field for one value, so the compute descriptor can put the input document there and nothing else. Core's contract for `package` says the same for every target: it must not write a secret, or a value the deploy has not resolved, into the artifact. +The artifact is built before the values issued during the deploy exist. A secret has no place in a file that is uploaded and stored with the code. And `port` must stay a key, so that under `prisma dev` the local target can give each instance the port the Compute emulator assigned it. Two things keep secrets out of the artifact. `serializeInput` keeps secret values out of the document. And `compute.bootstrap.json` has one field for one value, so the compute descriptor can put the input document there and nothing else. Core's contract for `package` says the same for every target: it must not write a secret, or a value the deploy has not resolved, into the artifact. ### How the document reaches the service The deploy builds each service in four steps, `provision`, `serialize`, `package` and `deploy` ([ADR-0056](ADR-0056-prisma-dev-runs-a-service-with-its-build-adapters-dev-server.md) describes each). The input document goes through them, and then through the bootstrap, like this: -1. `serialize` builds the input document and creates no variable for it. The document is on its result, in `input`, where the deploy report already reads it. +1. `serialize` builds the input document and sends no key for it. The document is on its result, in `input`, where the deploy report already reads it. 2. Core passes `serialize`'s result to `package`. Core does not look inside it. 3. `package` passes the document, as a JSON value, to the artifact packer, which writes it into `compute.bootstrap.json` as the nested value of `inputDocument`. The same document always gives the same bytes, so the artifact stays deterministic. 4. The printed `bootstrap.js` is constant code that reads `compute.bootstrap.json` and calls `main.run(boot.address, () => import(boot.appEntrypoint), boot.inputDocument)`. No text from the app is ever placed inside the JavaScript. @@ -86,27 +86,27 @@ The deploy writes the input document only into the artifact, so any `COMPOSER__INPUT` variable still exists on the branch. Alchemy, the deploy engine, deletes it only after the new deployment has been created, and the platform copies the branch's variables into a deployment when it creates it. So the new deployment starts with the old variable in its environment, and must not read it. The rules stay after the upgrade, because a variable left behind for any other reason must not win over the artifact either. +The upgrade from a version that wrote the document as a variable is the case that needs these rules. The first deploy with this decision runs while the previous deploy's `COMPOSER_
_INPUT` row still exists on the branch. Alchemy, the deploy engine, deletes it only after the new deployment has been created, and the platform copies the branch's variables into a deployment when it creates it. So the new deployment starts with the old row in its environment, and must not read it. The rules stay, because a variable left behind for any other reason, or one a user sets on the service, must not win over the artifact either. ### Under `prisma dev` `prisma dev` runs the same steps against the local target ([ADR-0041](ADR-0041-local-dev-runs-the-deploy-pipeline-against-local-providers.md)). -- **A service that runs its artifact** reads its input document from the artifact, as on Prisma Cloud. The local `Deployment` provider decides which platform variables the service's process receives from the `$platform` markers in its input document ([ADR-0058](ADR-0058-prisma-dev-reads-secrets-from-the-app-secrets-and-never-invents-them.md)). It reads the document for that from the unpacked artifact, with the reader `@internal/lowering` exports next to the packer, so the boot file's writer and reader are one package's code. A `COMPOSER_
_INPUT` entry in the local target's `env.json` is not used to choose the platform variables and is not put into the process's environment, whether or not the artifact holds a document. -- **A service that runs a dev server** has no artifact ([ADR-0056](ADR-0056-prisma-dev-runs-a-service-with-its-build-adapters-dev-server.md)). `reserve`, the step that stands in for `package` and `deploy`, creates the input document as a `Prisma.EnvironmentVariable`, with the resource ID `
.env.COMPOSER_
_INPUT`, that key, and the class and branch that `serialize` gives every variable of the environment. The local target keeps it in its `env.json`, so the dev server's environment is what a deployment's would be. +- **A service that runs its artifact** reads its input document from the artifact, as on Prisma Cloud. The local `Deployment` provider decides which platform variables the service's process receives from the `$platform` markers in its input document ([ADR-0058](ADR-0058-prisma-dev-reads-secrets-from-the-app-secrets-and-never-invents-them.md)). It reads the document for that from the unpacked artifact, with the reader `@internal/lowering` exports next to the packer, so the boot file's writer and reader are one package's code. Its other keys come from the deployment's `variables`; the local target's `env.json` is not read for it. +- **A service that runs a dev server** has no artifact ([ADR-0056](ADR-0056-prisma-dev-runs-a-service-with-its-build-adapters-dev-server.md)). `reserve`, the step that stands in for `package` and `deploy`, declares a local `Prisma.EnvironmentVariable` for the input document, with the resource ID `
.env.COMPOSER_
_INPUT` and that key, beside one for each of the service's other keys that is not `null`. The local target keeps them in its `env.json`, so the dev server's environment is what a deployment's would be. ### Upgrading No value is written in two places, and nothing is migrated. -- The first deploy with this decision gives every Compute service a new artifact, so every service gets a new deployment that reads its input document from the artifact. Alchemy then deletes the `COMPOSER_
_INPUT` variables, which no service declares any more. +- The first deploy with this decision gave every Compute service a new artifact, so every service got a new deployment that reads its input document from the artifact. Alchemy then deleted the `COMPOSER_
_INPUT` rows, which no service declares any more. An environment that skips from a version before this decision to one with [ADR-0069](ADR-0069-a-services-composer-keys-travel-with-its-deployment-as-service-variables.md) gets the same: its rows, this one included, are deleted after the new deployments exist. - A deployment made before the upgrade keeps running until it is replaced, with the environment it was created with. - Putting a deployment made before the upgrade back into service afterwards is not supported: its artifact holds no input document and its variable is gone. ## Consequences - An input document is not limited to a variable's 8 KB on Prisma Cloud. -- A Compute service has one variable fewer on the branch. The variables it keeps are the ones issued or generated during the deploy, and `port`. +- A Compute service has one key fewer. The keys it keeps are the ones issued or generated during the deploy, and `port`. - Changing an input document redeploys exactly the service that reads it, through the artifact's path rather than the deployment's triggers. - The artifact holds configuration. It holds no secret, but anyone who can read the artifact can read the literals the author wrote into the input document. - `ServiceLowering.package` receives `serialize`'s result, under a contract that forbids writing a secret or an unresolved value into the artifact. Core still knows nothing about what the result holds. diff --git a/docs/design/90-decisions/ADR-0069-a-services-composer-keys-travel-with-its-deployment-as-service-variables.md b/docs/design/90-decisions/ADR-0069-a-services-composer-keys-travel-with-its-deployment-as-service-variables.md new file mode 100644 index 000000000..160b6e319 --- /dev/null +++ b/docs/design/90-decisions/ADR-0069-a-services-composer-keys-travel-with-its-deployment-as-service-variables.md @@ -0,0 +1,103 @@ +# ADR-0069: A service's `COMPOSER_` keys travel with its deployment as service variables + +Take the app `shop`, where `shop.web` depends on the RPC interface `shop.auth` exposes. When a deploy creates a deployment of `shop.web`, its request to Prisma Cloud carries every key the service reads at boot: + +```http +POST /v1/services/svc_2/deployments +``` + +```json +{ + "portMapping": { "http": 3000 }, + "variables": { + "COMPOSER_SHOP_WEB_PORT": "3000", + "COMPOSER_SHOP_WEB_AUTH_URL": "https://svc_1.cdg.prisma.build", + "COMPOSER_SHOP_WEB_AUTH_SERVICEKEY": "…", + "COMPOSER_SHOP_WEB_ORIGIN": "\"https://svc_2.cdg.prisma.build\"", + "COMPOSER_SHOP_WEB_RPC_ACCEPTED_KEYS": null, + "COMPOSER_SHOP_WEB_STREAMS_API_KEY": null, + "COMPOSER_SHOP_WEB_BILLING_URL": null + } +} +``` + +The platform stores the values on the service, and every deployment of the service receives them. `shop.web` exposes nothing and serves no streams, so its accepted keys and its streams key are `null`. It depended on `billing` in an earlier deploy and no longer does, so that key is `null` too. The deploy writes no environment variable row. + +## Decision + +On Prisma Cloud the deploy sends a Compute service's `COMPOSER_` keys in the `variables` field of the request that creates the service's deployment. The platform stores them as **service variables**: a string sets a key, `null` deletes it, and a key not sent keeps its stored value. Keys keep their names, so nothing changes in how a service boots. The deploy writes no `Prisma.EnvironmentVariable` for a service on Prisma Cloud. + +- **Every key boot reads is sent, as a value or `null`.** That is each declared param (`port` and each dependency's connection params) and each reserved provider param (`RESERVED_PROVIDER_PARAMS`: the RPC accepted keys, the streams key, the origin), for every service, on every deploy, plus each generated value the input document names. A key with no value is `null`. +- **A name Composer no longer sends is deleted.** A Composer resource, `PrismaCloud.SentVariableNames`, one per service with the ID `
.sent-variable-names`, takes this deploy's variable names and keeps every name it has ever been given in deploy state. It holds names, never values. The deploy sends `null` for every recorded name it no longer sends. +- **At most 50.** `serialize` refuses a service with more than 50 keys that are not `null` before any resource is created, changed or deleted (the branch's application topology has already been replaced and the build recorded by then), naming the service, the count and the limit (`SERVICE_VARIABLE_LIMIT` in `descriptors/shared.ts`). `null` is not counted. +- **Only `COMPOSER_` keys.** The map never holds a platform variable's value or any other value the operator sets. +- **The deployment is replaced when the map changes.** `Prisma.Deployment` records a salted hash of the resolved map and plans a replacement when it changes, when a value is not resolved while planning, and when the prop is declared on a deployment that recorded no hash. The deployment's `triggers` keep only the `:updatedAt` member of each platform variable the service reads. +- **The input document stays in the artifact** ([ADR-0065](ADR-0065-a-compute-services-input-document-travels-in-its-artifact.md)). +- **A dev server keeps rows.** Under `prisma dev` a service that runs its artifact takes its keys from its deployment's `variables`, leaving out a `null`. A service that runs a dev server has no deployment, so `reserve` declares a local `Prisma.EnvironmentVariable` for each key that is not `null`, and one for the input document. `reserve` fails as a bug in any application other than the local, branchless one, so no row reaches Prisma Cloud. +- **The hosted `Prisma.EnvironmentVariable` provider stays registered**, so that Alchemy can delete the rows an older Composer wrote, on the first deploy and on `destroy` of an environment last deployed by an older version. + +The change can ship only when the platform accepts `variables` in production and both the upstream provider (`@alchemy.run/prisma`) and the generated client (`@distilled.cloud/prisma`) have released the field. Until then this repository adds the field with `pnpm` patches under `patches/`, and `check:patched-dependencies` fails, because a published package would install the unpatched provider, which drops `variables` without an error. + +## Reasoning + +### Why service variables + +The platform is removing branch overrides, which is how Composer wrote these keys on every preview deploy. A variable group is shared by every branch that receives it, and these values differ per branch, so the keys cannot move into a group. Service variables belong to one service, which is what every `COMPOSER_` key is: at boot a service reads only the keys under its own address (`stashRows` in `serializer.ts`), and a value it gets from another service is copied under its own key at deploy. The platform sets them only through the create-deployment request. + +### Why every key boot reads is sent + +With stored service variables, a key that is left out keeps whatever an earlier deploy stored. For most keys that would only be stale. For the streams key it would open a hole: a streams service with no consumer gets no key and refuses to boot, which is the fail-closed behaviour the streams module depends on. If the old key stayed stored, the service would keep booting and keep accepting it. So every key boot can read is sent on every deploy, and a missing value is `null`. A `null` is a literal known while planning and the same on every deploy, so it never replaces a deployment on its own. The platform accepts a `null` for a key it does not hold and does not count it. + +### Why a record of sent names + +A key the service's code no longer declares, such as a removed dependency's params or a renamed generated value, would otherwise stay stored: a stale secret readable by every later deployment, counted toward the limit, and left for the user to find and delete. `SentVariableNames` remembers every name, and the deploy sends `null` for each name it no longer sends, on that deploy and every later one. + +When a deploy sends the same names as the last one, the record's input is unchanged, the engine plans no change for it, and its output is known while planning. The map is then the same as last time and the deployment is reused. A test with the real Alchemy engine deploys twice with nothing changed and checks that no second deployment is created. When the names change, the record changes, its output is not known while planning, and the deployment is replaced, which a changed key set needs anyway. + +### Why the replacement rule differs from `triggers` + +Upstream records a `triggers` hash through a plain update the first time `triggers` is declared. An update creates no deployment, and the platform takes `variables` only when a deployment is created, so a deployment that gained `variables` through an update would never send them. A `variables` prop with no recorded hash therefore replaces. + +### What is in deploy state + +Alchemy writes every prop to deploy state, and it writes a `Redacted` value as its plain text. So the values in `variables` are stored in deploy state in plain text, as the rows and the trigger members that repeated them were before. This is no change in exposure: every value is one the deploy produced, never a platform variable's value, which the deploy never holds. `Redacted` keeps the values out of logs and error messages. + +### The limit + +A service has at most 50 service variables. The platform's own error arrives in the middle of a deploy, after other services have changed, and says only "Quota exceeded for service_variable". Composer counts its own keys first. It cannot see variables a user set on the service in Console, and those count too. + +## Consequences + +- **The first deploy of an existing app with this version** replaces each service's deployment once, because the deployment declares `variables` for the first time. The new deployment is created with every value. Alchemy then deletes the variable rows in its state that no deployment declares any more, on production and on preview, each after the old deployment it fed has stopped. A deployment still draining open connections holds its rows until a later deploy finds it stopped, so rows can stay visible in Console after the first deploy. While a row and a service variable both exist, the service variable wins. +- **A key that loses its value in the upgrade deploy is still read from its old row.** A `null` deletes a service variable, not a row, and the new deployment is created while the old rows still exist. So if the same deploy removes a dependency, or the last consumer of a streams service, the new deployment receives the old row's value for that key and keeps it until the deployment is next replaced. Composer releases before this one behave the same. Make the upgrade deploy on its own, or deploy that service once more with a changed artifact afterwards. +- **A row that cannot be deleted does not fail the deploy.** A row already deleted in Console, or one the platform manages, is skipped by the upstream provider. A row the platform refuses to delete because its recorded project, branch, class or key differ from the platform's is dropped from deploy state, and the deploy logs a warning naming the key and saying to delete it in Console. Composer's own provider layer (`providerForDeletingOldVariableRows()` in `lowering/src/providers.ts`) does this, around upstream's. Without it, one such row would fail this deploy and every later one. +- **An interrupted upgrade finishes on the next deploy** without replacing any deployment again. +- **The key-clash check is gone.** It refused a deploy while an old row held a key that a different node owned after the move to full addresses ([ADR-0057](ADR-0057-a-nodes-address-is-its-full-path-from-the-app-name.md)). With no rows written, two rows cannot collide. One case remains for an app that upgrades directly from a version before full addresses: a service whose new key equals another service's old key, and which has no value for it, would receive the other service's old row once. Such an app deploys once with any release from 0.35.0 to 0.39.0 first. +- **Going back to an older Composer is not possible.** After one deploy with this version, deploy state holds a `PrismaCloud.SentVariableNames` resource per service. An older Composer registers no provider for that type, and Alchemy stops while planning, before it changes anything, with "No provider is registered for resource type 'PrismaCloud.SentVariableNames'". A way back would need an older release that knows the type; no released version does. +- **A user can change a service's variables in Console**, `COMPOSER_` keys included. Every deploy that creates a deployment sets Composer's own keys again, and deletes the names Composer no longer sends. A change made in Console takes effect by creating a deployment, and the next `prisma deploy` makes Composer's own deployment live again: a value the user set under another name stays stored and reaches Composer's deployment from its next replacement on, and a `COMPOSER_` key the user changed is set back on that replacement. Composer reads none of them. +- **Destroy** deletes the App, and the platform deletes its service variables with it. + +## Alternatives considered + +- **Composer keeps writing rows, as branch overrides on preview and class rows on production.** The position before this record. Rejected: the platform rejects override writes three months after variable groups ship, which would fail every preview deploy. +- **Composer writes rows into the branch's variable group.** Rejected: a group is shared by every branch that receives it, and these values differ per branch. +- **Send a service's complete set and let the platform delete everything else stored on it.** Rejected: it would delete values a user set on the service in Console, on every deploy. +- **Leave behind the keys a service stops declaring.** Rejected: a stale secret reaches every later deployment, and a service that reached 50 could not be deployed or cleaned up by its user. +- **The provider reads the service's current keys before creating the deployment and sends `null` for those under Composer's prefix.** Rejected: a second prop on the upstream resource, one more call per deployment, and a dependency on the platform listing a service's keys correctly. +- **Composer reads every service's keys before the deploy and passes the stale ones as `null`.** Rejected: the `null`s disappear from the props once applied, which replaces each such deployment a second time on the following deploy. +- **The platform takes a "delete every key with this prefix that I did not send" flag.** Atomic, but a new request to the platform and nothing Composer can build against today. +- **The provider remembers the keys it sent.** Does not work: Alchemy creates a replacement without the old instance's props or outputs, and every value change here is a replacement. +- **Keep each value in `triggers` and pass `variables` with no hash of its own.** No new diff logic upstream, but every value would be stored twice in props. +- **One variable holding all of a service's keys as JSON.** Rejected: a value is limited to 8,192 characters, and it changes how every service boots. +- **A Composer-owned resource for service variables.** Not possible: the platform sets them only through the create-deployment request. +- **Hand the dev server its values without rows.** Rejected: core would have to pass every local target a new thing for one target's reason. Rows through the local provider need no core change. + +## Related + +- [ADR-0048](ADR-0048-prisma-cloud-resources-come-from-the-upstream-alchemy-provider.md): the upstream provider, the ordering edge and change propagation. +- [ADR-0065](ADR-0065-a-compute-services-input-document-travels-in-its-artifact.md): the input document travels in the artifact. +- [ADR-0041](ADR-0041-local-dev-runs-the-deploy-pipeline-against-local-providers.md): local dev runs the deploy pipeline against local providers. +- [ADR-0056](ADR-0056-prisma-dev-runs-a-service-with-its-build-adapters-dev-server.md): `reserve` and dev servers. +- [ADR-0057](ADR-0057-a-nodes-address-is-its-full-path-from-the-app-name.md): keys built from the full address. +- [ADR-0064](ADR-0064-an-app-declares-its-platform-variables-in-its-root-and-the-deploy-copies-no-local-values.md): platform variables, which the operator sets and the deploy never writes. +- [alchemy-lowering.md](../05-prisma-cloud/alchemy-lowering.md): the resources a compute service lowers to. diff --git a/docs/design/90-decisions/README.md b/docs/design/90-decisions/README.md index a24715f93..88adcde88 100644 --- a/docs/design/90-decisions/README.md +++ b/docs/design/90-decisions/README.md @@ -62,14 +62,14 @@ _Earlier drafts (ADR-0001, ADR-0002) were retired as the high-level design settl - [ADR-0038](ADR-0038-containers-are-an-extension-descriptor.md) — Container lifecycle (ensure/locate/remove) is an optional `container` descriptor on `ExtensionDescriptor`, the same pattern as `preflight`/`teardown`; the resolved instance is opaque to core and crosses the CLI parent→alchemy child boundary as one framework-named environment variable per extension, via the extension's own `serialize()`/`deserialize()`. `StateDescriptor` names its owning extension so core can hand it that extension's resolved container. Deletes the `crossDomainExceptions` entry that let the CLI import `@internal/lowering` directly — `0-framework` imports nothing again. *(Amended by ADR-0066: `deploy` hands containers and preflight payloads to `lower()` as values; the environment transport remains for `destroy` and `prisma dev`.)* *(Amended by ADR-0067: `prisma dev` sends containers to its worker thread in memory.)* *(Amended by ADR-0068: `destroy` hands containers to `lower()` as values too; the environment transport is deleted.)* - [ADR-0039](ADR-0039-a-compute-services-own-origin-is-a-target-resolved-property.md) — A compute service's own platform-assigned origin is a target-resolved property, read as the service's `origin()` — never a declared param, never operator config, never in `config()`. It rides ADR-0031's reserved provider-param channel as the first *service-derived* entry (`valueForService(provisioned, address)`, written for every compute service, exposing or not), sourced from the provisioned App's `appEndpointDomain` (ADR-0048) — made trustworthy pre-promote by the upstream PRO-200 fix. A plain platform variable node or a root input field remains correct for operator-known origins (custom domains). - [ADR-0040](ADR-0040-the-orm-binding-carries-the-url-and-a-lazy-client.md) — `postgres(contract)`'s dependency binding is `{ url, client }`: the raw connection string plus the typed client, constructed lazily and memoized on first `client` access — `hydrate` builds nothing. The contract remains the compatibility interface (hash check and deploy-time migration unchanged, ADR-0022); the binding becomes a strict superset of plain `rawPostgres()`'s `{ url }`, so an app that owns its database client still gets framework-run migrations. Contract validation cost and failure move from `load()` (where one bad input poisoned every input, unattributed) to the first `client` access. Cross-kind satisfaction (`'postgres'` satisfying `'postgres'`) rejected in its favor. *(Extended by ADR-0055: the binding also carries `connection` and `clientWith(options)`.)* -- [ADR-0041](ADR-0041-local-dev-runs-the-deploy-pipeline-against-local-providers.md) — `prisma-composer dev` runs the **same deploy pipeline** (Load → assemble → lower → Alchemy converge) against local implementations of the same Alchemy resource types, declared on an optional `localTarget` field of `ExtensionDescriptor` (a lazy thunk resolving a `LocalTargetDescriptor`; subpaths `@prisma/composer/local-target` and `@prisma/composer-prisma-cloud/local-target` — "dev" names only the user-facing command/prefix/state dir) (providers, container, preflight, emulators, attach, teardown — **no** `nodes`/`provisions`, so the lowering cannot diverge; no `state` either — dev uses Alchemy's own `localState()` through `LowerOptions.state`). The target runs **emulators per node kind**: Compute and buckets are machine-global, multi-tenant daemons (the Compute emulator owns the service child processes — deployment PUTs, crash supervision, logs; buckets serve the S3 wire over plain files on disk), while Postgres the Postgres emulator hosts one `@prisma/dev` server per database instance. Providers provision instances by communicating with the emulators during converge, and the dev command is a view through `attach`; `ServiceKey`/`S3Credentials`/`PgWarm`/`OrmMigration` are shared verbatim. Credential-free by requirement. Rejects a local Management API (reimplements another team's server-side semantics, drifts silently) and per-kind dev descriptors (an open-set parallel seam). *(Amended by ADR-0050: the command is `prisma dev`; logs are the `log` operation, not a command. Amended 2026-10-23: the entry is the `composer` section's `entry` or `--entry`, not a positional. Amended by ADR-0052: emulator instances are keyed by emulator-generated ids, not the app name, Composer maps each app's nodes to them per directory, and `prisma dev` stops the app's database servers when it ends.)* *(Amended by ADR-0056: a service runs the dev server its build adapter declares in place of its artifact, as a command deployment on the Compute emulator.)* *(Amended by ADR-0062: local dev runs as a named environment, `dev` by default.)* *(Amended by ADR-0067: each dev converge runs in a worker thread of the `prisma` process.)* +- [ADR-0041](ADR-0041-local-dev-runs-the-deploy-pipeline-against-local-providers.md) — `prisma-composer dev` runs the **same deploy pipeline** (Load → assemble → lower → Alchemy converge) against local implementations of the same Alchemy resource types, declared on an optional `localTarget` field of `ExtensionDescriptor` (a lazy thunk resolving a `LocalTargetDescriptor`; subpaths `@prisma/composer/local-target` and `@prisma/composer-prisma-cloud/local-target` — "dev" names only the user-facing command/prefix/state dir) (providers, container, preflight, emulators, attach, teardown — **no** `nodes`/`provisions`, so the lowering cannot diverge; no `state` either — dev uses Alchemy's own `localState()` through `LowerOptions.state`). The target runs **emulators per node kind**: Compute and buckets are machine-global, multi-tenant daemons (the Compute emulator owns the service child processes — deployment PUTs, crash supervision, logs; buckets serve the S3 wire over plain files on disk), while Postgres the Postgres emulator hosts one `@prisma/dev` server per database instance. Providers provision instances by communicating with the emulators during converge, and the dev command is a view through `attach`; `ServiceKey`/`S3Credentials`/`PgWarm`/`OrmMigration` are shared verbatim. Credential-free by requirement. Rejects a local Management API (reimplements another team's server-side semantics, drifts silently) and per-kind dev descriptors (an open-set parallel seam). *(Amended by ADR-0050: the command is `prisma dev`; logs are the `log` operation, not a command. Amended 2026-10-23: the entry is the `composer` section's `entry` or `--entry`, not a positional. Amended by ADR-0052: emulator instances are keyed by emulator-generated ids, not the app name, Composer maps each app's nodes to them per directory, and `prisma dev` stops the app's database servers when it ends.)* *(Amended by ADR-0056: a service runs the dev server its build adapter declares in place of its artifact, as a command deployment on the Compute emulator.)* *(Amended by ADR-0062: local dev runs as a named environment, `dev` by default.)* *(Amended by ADR-0067: each dev converge runs in a worker thread of the `prisma` process.)* *(Its text includes the change ADR-0069 made: a deployment's keys come from its `variables`, and only a dev server keeps rows.)* - [ADR-0042](ADR-0042-service-input-is-one-standard-schema.md) — A compute service declares all of its input, plain values and secrets together, as one Standard Schema (`input`), read back through `service.input()`. The binding at `provision()` is typed from the schema's input type, with the same type a module's binding has, so a wrong literal or a source in the wrong kind of field fails to compile. Secret fields are `secretString()`; a field that may receive a value known only at boot is wrapped in `field()`. The deploy checks the binding with the schema, each value known only at boot in place as a pointer, and writes one self-describing input document per service with `$platform` markers (with `secret: true` for a platform secret, and the variable's JSON Schema for a typed platform variable) and `$generated` markers; boot leaves out a field whose platform variable is unset or empty, boxes the secrets, decodes and validates each typed platform variable's text, and checks the input again. Composer never looks inside a library's schema; a platform variable's schema is read through Standard JSON Schema, the public form the library emits. *(Its current text includes ADR-0061's extension to modules.)* - [ADR-0043](ADR-0043-the-control-subpath-is-the-programmatic-deploy-surface.md) — `@prisma/composer/control` is the programmatic deploy surface: typed `deploy`/`destroy`/`dev`/`log` operations (structured inputs/results, no argv/console/exit) implemented in `@internal/cli`'s `src/operations/` and re-exported per ADR-0035; the CLI is a thin renderer over them. The entry's static graph stays import-light — each operation lazily imports its executor, so importing the subpath executes nothing, and a tree that cannot load the deploy stack surfaces as a structured `pipeline` failure — and `PRISMA_COMPOSER_DEPLOYMENT_RESULT_FILE` carries the deploy result across the process boundary: the alchemy child's report hook writes a serializable `DeploymentSummary` to the named file, the operation reads it back best-effort (absent/malformed = undefined summary, never a failure). Distinct from an extension's ADR-0017 `/control` entry. *(Amended by ADR-0049: each operation takes a required `config: { value, file }`, and the effect-conflict diagnosis is retired.)* *(Amended by ADR-0050: the `prisma` CLI renders two of the four operations, as `prisma deploy` and `prisma dev`; `destroy` and `log` are called from scripts.)* *(Amended by ADR-0053: `devUrl` and `devStop` join the operations.)* *(Amended by ADR-0059: `deploy` and `destroy` take `environment`, which `destroy` requires.)* *(Amended 2026-10-28: `devUrl` and `devStop` act on the app and environment in their input; `dev` and `log` take `environment`.)* *(Amended by ADR-0066: `deploy` returns the summary as a value; it uses no result file.)* *(Amended by ADR-0068: `destroy` runs in the calling process, reports deploy's step events except `preflight` and takes a `signal`; no diagnostics and no result file.)* - [ADR-0044](ADR-0044-errors-are-structural-envelopes-with-dotted-namespace-codes.md) — Errors are structural envelopes with dotted `NAMESPACE.SUBCODE` codes from a closed registry, structured at origin with why/fix splits, no catch-all codes; bugs carry no code (exit 1); recognition is structural; operation results ride the `Result` `ok` discriminator; expected failures exit 2, with the deploy engine's status passed through. The one change between origin and consumer is that the operation redacts known secrets and drops the cause. *(Amended by ADR-0066: the child exit-status passthrough no longer applies to `deploy`, whose failures exit 2; `DEPLOY.INTERRUPTED`, `DEPLOY.CONVERGE_RUNNING`, `DEPLOY.WORKER_THREAD`, `DEPLOY.MANAGEMENT_API_URL_CONFLICT`, `DEPS.CONVERGE_UNRESOLVABLE` and `DEPS.CONVERGE_CONTRACT_MISMATCH` are added; an interrupted `prisma deploy` ends as `CLI.ABORTED` with exit 130.)* *(Amended by ADR-0067: `prisma dev` has no Alchemy child.)* *(Amended by ADR-0068: no command passes a child's exit status through; `DEPLOY.ALCHEMY_BIN_MISSING`, `DEPLOY.NODE_MISSING` and `DEPLOY.STACK_WRITE_FAILED` are retired.)* - [ADR-0045](ADR-0045-deploy-state-lives-behind-the-platform-state-api.md) — Deploy state lives behind the platform state API (the Management API implements Alchemy's stock `HttpStateApi` wire contract per Branch; composer's state layer is Alchemy's stock HTTP client), and deploys hold a server-side per-`(stack, stage)` lease (TTL 60s, heartbeated, released on exit; contention fails fast naming the holder; state operations without a live lease fail 409). Supersedes ADR-0010 (lock → lease) and the storage half of ADR-0034 (Branch scoping and lifetime stand; the visible per-stage database is gone); closes ADR-0012 as obsolete. No migration: legacy stages are refused until destroyed or deleted. - [ADR-0046](ADR-0046-the-orm-facade-is-a-peer-dependency.md) — `@prisma/composer-prisma-cloud` takes the Prisma ORM postgres facade (`@prisma/orm-postgres`) as a **peer** dependency at one exact version, not a regular dependency: Composer registers an extension pack against the application's copy of the target, and two copies of a shell in one tree means two codec/operation registries and two class identities — a value from one is rejected by the other, silently. As a peer, that combination fails at install instead. Every `@prisma/orm-*` spec in the workspace is one exact version and all name the same one (`scripts/lint-orm-pins.mjs`). `@prisma/orm-toolchain`, which Composer drives rather than extends, stays a regular dependency. Replaces ADR-0022's consequence bullet on how the ORM is installed. - [ADR-0047](ADR-0047-compute-assembly-preserves-safe-runtime-topology.md) — Compute assembly traces runtime files from the author-declared Node entry without rebundling app code, preserves only symlinks whose resolved targets remain inside the staged bundle, and installs narrowly runtime-gated bootstrap compatibility when a framework needs Node semantics. Each local mechanism is removed once the upstream Alchemy Compute provider owns the equivalent guarantee. Supersedes ADR-0005's blanket ban on symlinks and its assumption that directory output is already self-contained. -- [ADR-0048](ADR-0048-prisma-cloud-resources-come-from-the-upstream-alchemy-provider.md) — The six Management-API resource families (project, database, connection, app, deployment, environment variable) are the upstream Prisma provider's classes (`@alchemy.run/prisma`), registered in Composer's `PrismaComposer` collection; Composer defines resources only where the upstream provider has no support yet (buckets) or no Management API exists behind them. Compute binds the low-level App/Deployment/EnvironmentVariable trio (the `COMPOSER_*_ORIGIN` self-edge and ADR-0005 rule out composite `Compute`); the env→deployment ordering edge rides the deployment's `app` prop, and a deployment is replaced exactly when its artifact or environment fingerprint changes — unchanged services are reused. Legacy rows in the platform state API (retired type-ids and shapes) migrate on read — the older retired SQL state stores stay destroy-only under ADR-0045 — branch-stage databases take generated physical names, and the platform's `DATABASE_URL`, which the platform writes only for a project's default database, is left to the platform: Composer creates no default database and neither writes nor tracks the variable. *(Amended by ADR-0057: resource IDs are the node's full address, or the address plus `.` and a role, each declaring its previous ID with `renamedFrom`. Amended 2026-10-30: the provider is the `@alchemy.run/prisma` package from Alchemy beta.84 (formerly the `alchemy/Prisma` module); resource type ids are unchanged. Amended 2026-11-20: a compute service's published `url` is its App's endpoint domain, and a consumer's deployment waits for its producers' promotion through the deployment's `app` prop, never through `triggers`.)* +- [ADR-0048](ADR-0048-prisma-cloud-resources-come-from-the-upstream-alchemy-provider.md) — The six Management-API resource families (project, database, connection, app, deployment, environment variable) are the upstream Prisma provider's classes (`@alchemy.run/prisma`), registered in Composer's `PrismaComposer` collection; Composer defines resources only where the upstream provider has no support yet (buckets) or no Management API exists behind them. Compute binds the low-level App and Deployment (the `COMPOSER_*_ORIGIN` self-edge and ADR-0005 rule out composite `Compute`); a compute service's published `url` is its App's endpoint domain, a consumer's deployment waits for its producers' promotion through the deployment's `app` prop, and a deployment is replaced exactly when its artifact, its `variables` or its platform variables' `updatedAt` triggers change — unchanged services are reused. The hosted EnvironmentVariable provider stays registered to delete rows an older Composer wrote (ADR-0069). Legacy rows in the platform state API (retired type-ids and shapes) migrate on read — the older retired SQL state stores stay destroy-only under ADR-0045 — branch-stage databases take generated physical names, and the platform's `DATABASE_URL`, which the platform writes only for a project's default database, is left to the platform: Composer creates no default database and neither writes nor tracks the variable. *(Amended by ADR-0057: resource IDs are the node's full address, or the address plus `.` and a role, each declaring its previous ID with `renamedFrom`. Amended 2026-10-30: the provider is the `@alchemy.run/prisma` package from Alchemy beta.84 (formerly the `alchemy/Prisma` module); resource type ids are unchanged. Its text includes the changes ADR-0069 made: no row ordering edge, and change propagation through `variables`.)* - [ADR-0049](ADR-0049-composers-configuration-is-the-composer-section-of-prisma-config.md) — Composer's configuration is the `composer` section of `prisma.config.ts`, loaded by the Prisma CLI engine: `extensions`, `state`, and optional `entry`, `config` and `secrets` adapter lists. The validator checks only what identifies each value, passes the file's own objects through, never calls an adapter, rejects unknown keys, takes the nearest declaring file's section whole, and returns `{ value, file }`; the programmatic operations take the same input. The old config file is refused, not migrated. Only the first process runs adapters; the second process imports the file for its descriptors and reads what Load read from the app configuration file. *(Amended by ADR-0066: the child-process reason for one declaring file now holds for `destroy` and `prisma dev`; the decision stands.)* *(Amended by ADR-0067: the dev worker thread imports the config; no dev stack file.)* *(Amended by ADR-0068: `destroy` has no second process; no command hands the config to a second process.)* - [ADR-0050](ADR-0050-composer-runs-as-prisma-deploy-and-prisma-dev.md) — Composer has no binary of its own: the `prisma` CLI mounts exactly two Composer commands, `prisma deploy` and `prisma dev`, mounted at the root as bare verbs on purpose rather than under a noun. `destroy` and `log` are operations on `@prisma/composer/control`, called from a script; a teardown script reads `PRISMA_SERVICE_TOKEN` and `PRISMA_WORKSPACE_ID`. Where teardown and logs belong in the `prisma` command tree is not decided; until it is, agents and users need a script for both. A `destroy` command was rejected: the CLI's destructive verb is `delete`, and no Composer command takes `--production`. Retires the `prisma-composer` binary; a CI lint keeps its name out of user-facing files. *(Amended by ADR-0053: the family also ships `dev url`, `dev stop` and `emulator list`, and `prisma dev` gains `--detach`. Amended 2026-10-23: neither command takes a positional entry; both take `--entry` over the config's `entry`. Amended 2026-10-27: the family also ships `deploy list`.)* *(Amended by ADR-0062: the flag is `--environment`, defaulting per command; `destroy` targets an environment by name.)* - [ADR-0051](ADR-0051-a-nodes-address-is-its-logical-id-on-the-platform.md) — A node's address is its identity on Prisma Cloud: Composer writes it, byte for byte, as the `logicalId` of the node's one platform row (Project, App, Database, Bucket) and as the node's `logicalId` in the application topology, so the platform joins topology nodes to rows, and one node across branches, by string equality. A provision ID defaults to the node's name, so changing a name changes identity. The value is never an Alchemy resource ID, a display name or a platform `id`; App, Database and Bucket rows get it as a prop on the upstream resource that creates them, and the Project from container resolution; no separate resource writes it. Changing an address changes the entity's identity; changing a display name changes nothing. *(Amended 2026-10-16: on the app's own Project and Branch, the row holding a node's `logicalId` is that node's row, so a deploy resuming an interrupted create uses it. Superseded by ADR-0057: addresses start with the app name, and resource IDs, env keys and `serviceOrigin()` are built from them; the identity rules here are carried forward.)* @@ -78,7 +78,7 @@ _Earlier drafts (ADR-0001, ADR-0002) were retired as the high-level design settl - [ADR-0054](ADR-0054-raw-http-is-the-untyped-tier-of-service-connections.md) — `@prisma/composer/http` ships `rawHttp()` and `rawHttpContract` (kind `http`, compared by kind only): the untyped tier of service-to-service connections, as `rawPostgres()` is for data. The provider declares its HTTP port; there is no service key, retry or idempotency, because the far end is the app's own server. The auth module's `api` port becomes a raw HTTP port and the provider-named `auth-api` kind is removed, because contracts describe interfaces, not providers. A `Contract` declares its own communication `style`, which the application topology reads. The untyped `http({ name })` is removed. A more specific HTTP kind filling a raw slot is the intended design but is not built, because contract kinds have no parent kinds. - [ADR-0055](ADR-0055-the-postgres-binding-builds-clients-with-the-apps-options.md) — The `postgres(contract)` binding gains `clientWith(options)`, which builds a typed Prisma ORM client with the runtime's own options (less `poolOptions`), such as pgvector's runtime extension or `middleware`, and `connection`, the pool every client shares, for an app that builds its client itself. The dependency declaration takes no options: they are how the service consumes the database, not what it requires, and passing the runtime's option type through means a new option needs no Composer change. `client` is unchanged. Composer never discovers an extension package from the contract's pack ids; a missing one still fails when the client is built, with the runtime's error. Rejected: options on the declaration, extensions on the contract. Amends ADR-0022, extends ADR-0040. - [ADR-0056](ADR-0056-prisma-dev-runs-a-service-with-its-build-adapters-dev-server.md) — Under `prisma dev`, a service runs the dev server its build adapter declares, in place of its built artifact: `nextjs()` declares `next dev`; `node()` declares none unless the author writes `dev: [...]` on it. No flag. The build descriptor gains `serve(input) → DevServer | undefined` (`cwd`, `argv({ port, host })`, `display`), called before assembly; such a service is not assembled and lowers without its `Deployment` (`LowerOptions.unassembled` + the service descriptor's `reserve`), so its rows, instance, port and dependents' URLs stay. The Compute emulator runs the dev server as a *command deployment* (`{ command: { cwd, argv }, env, listens }`) on the service's instance, with the deployment's materialized env re-stashed address-free by `stashRows`, the pure function `run()` now uses, plus `PORT`/`HOST`, over the shell's env; readiness, logs, crash supervision, restart on env change, `--detach`, `dev stop` and session resume are unchanged and the dev session owns no processes. The session streams dev servers' logs inline; `prisma dev` also watches the entry and every service's authoring module; `devUrl` gains `runs`. New codes `DEV.DEV_SERVER_UNAVAILABLE`, `DEV.DEV_SERVER_UNSUPPORTED`. Amends ADR-0041 and ADR-0053; extends ADR-0005. *(Amended by ADR-0067: a definition edit rebuilds and converges; three kinds of edit, listed there, need a restart.)* -- [ADR-0057](ADR-0057-a-nodes-address-is-its-full-path-from-the-app-name.md) — A node's address is the path of provision IDs starting at the root, whose address is the deployed app name (letters, digits, `-` and `_`; `shop`, `shop.catalog`, `shop.auth.api`), and it is the node's only identity. It is the `logicalId` of the node's platform row and topology node; a node that names something Composer does not own, such as a platform variable node, records no platform row and no topology node, and the thing it names keeps its owner's handle, such as the variable's name; Alchemy resource IDs are `
` for the main resource and `
.` for other pieces, which cannot collide because a module has children and no resources and a service or resource has resources and no children; `COMPOSER_` env keys are built from the full address with `-` turned into `_`; `serviceOrigin()` takes the full address. Every platform name Composer writes is the address, a label; the upgrade recreates Composer's Connections and bucket access keys with new credentials. Existing stages migrate on their next deploy: every resource declares `renamedFrom` its previous ID, and generated values, service keys and stream keys are renamed, not recreated; local dev's record is rewritten on first run. An older Composer deploying a migrated stage is not protected against. Rejected: unqualified child addresses, a second shorter "path" form, `-` suffixes on resource IDs, relative `serviceOrigin()`. Supersedes ADR-0051, carrying forward its identity rules. +- [ADR-0057](ADR-0057-a-nodes-address-is-its-full-path-from-the-app-name.md) — A node's address is the path of provision IDs starting at the root, whose address is the deployed app name (letters, digits, `-` and `_`; `shop`, `shop.catalog`, `shop.auth.api`), and it is the node's only identity. It is the `logicalId` of the node's platform row and topology node; a node that names something Composer does not own, such as a platform variable node, records no platform row and no topology node, and the thing it names keeps its owner's handle, such as the variable's name; Alchemy resource IDs are `
` for the main resource and `
.` for other pieces, which cannot collide because a module has children and no resources and a service or resource has resources and no children; `COMPOSER_` env keys are built from the full address with `-` turned into `_`; `serviceOrigin()` takes the full address. Every platform name Composer writes is the address, a label; the upgrade recreates Composer's Connections and bucket access keys with new credentials. Existing stages migrate on their next deploy: every resource declares `renamedFrom` its previous ID, and generated values, service keys and stream keys are renamed, not recreated; local dev's record is rewritten on first run. Since ADR-0069 an app from before this decision deploys once with a release from 0.35.0 to 0.39.0 first, because the preflight check for clashing keys is gone. An older Composer deploying a migrated stage is not protected against. Rejected: unqualified child addresses, a second shorter "path" form, `-` suffixes on resource IDs, relative `serviceOrigin()`. Supersedes ADR-0051, carrying forward its identity rules. - [ADR-0058](ADR-0058-prisma-dev-reads-secrets-from-the-app-secrets-and-never-invents-them.md) — Under `prisma dev` a platform secret comes from the app secrets and a plain platform variable from the app configuration, read by the target's dev preflight when `dev` starts; Composer never invents a value or reuses one. A required one that is missing stops dev; an optional one arrives absent, decided by validation. The root's input and the text of each plain platform variable are checked against the known secrets before each converge. They reach the local target in memory, as do the named secrets, the values of the graph's platform secrets; no file and no environment variable carries them. An HMAC fingerprint of each value redeploys exactly the services whose value changed. A changed value, or a change to what the app reads, pauses rebuilds until restart. Each local service receives only its own variables; that isolation is a requirement of the local target. *(Amended by ADR-0068: the preflight environment transport is deleted; payloads reach the lowering as values.)* - [ADR-0059](ADR-0059-a-deployment-environment-is-called-an-environment.md) — A place the app runs is an **environment**: a target-neutral concept of Composer's core, used on every public surface (`--environment`, `destroy`'s target, guides, errors, skill), replacing "stage". Every environment has a name and none is special: `prisma deploy` defaults to `production`, `prisma dev` to `dev`. On Prisma Cloud, `production` is the Project's default Branch and any other environment is the Branch of that `gitName`; `dev` has no Branch. "Branch" is Prisma Cloud's term and its git-shaped workflow, and appears only where Composer reports what the target did. - [ADR-0060](ADR-0060-public-traffic-reaches-a-service-through-a-public-url.md) — Traffic from the internet reaches a service only through a **public URL** the author declares: `publicUrl({ id, url, target })`, a driver wired to the HTTP connection a service exposes, as `cron` is wired to what it calls. `url` is one of two explicit strategies, a named hostname or the prisma.build URL the platform gives every service, usually computed per environment with `resolve()`. One hostname per public URL. A reusable module decides what can be public by exposing connections; the app decides what is. Services stay publicly reachable underneath until the platform can address them privately. On Prisma Cloud a named hostname lowers to the platform's RoutingUrl record, covered by a domain ownership claim the workspace has verified; a prisma.build URL lowers to nothing, because every service keeps the platform's own hostname. *(Amended 2026-10-29: the public URL node is a resource by kind and a driver by role, with a slot wired at construction and `props`; see the note at its top.)* *(Amended 2026-11-02: `publicUrl()` takes its identity as `id`, not `name`.)* @@ -86,7 +86,8 @@ _Earlier drafts (ADR-0001, ADR-0002) were retired as the high-level design settl - [ADR-0062](ADR-0062-environment-values-come-from-resolve-and-config-adapters.md) — The graph's structure is the same whatever inputs Composer is given; only values differ per environment. A module body holds values (`Value`), opaque stand-ins for data known later: deploy-time values, whose data the deploy has by the end of Load, and runtime values (`RuntimeValue`, which is `Value>`), whose data only the platform holds. A runtime value comes from a target's source, from a value resource (a resource node that is also a value, which only the app root can provision, enforced by the compiler), or from a module input bound to one; `provision()` returns the value with the node's address on it, and the graph's `valueReads` lists each service that reads each value resource. `resolve(dependencies, fn)` computes a value from deploy-time values only; `fn` never sees a pointer. Config adapters produce the app configuration, which fills the root's input; no source reads it, so a value the deploy reads is a root input field. Secrets adapters produce the app secrets, which `prisma dev` gives its services and which Composer redacts; the deploy does not copy either to platform variables, which the operator sets on the platform. Both lists default to `[environmentVariables()]`; `dotenv()` reads `.env` files through `dotenv-flow`. Only the first process runs adapters, once per deploy; the second reads the app configuration file and refuses a graph whose node addresses differ. Secrets stay out through pointers and redaction. Every environment has a name and none is special. *(Amended by ADR-0066: `deploy` runs Alchemy in its first process and writes no app configuration file; the second process applies to `prisma dev` and `destroy`.)* *(Amended by ADR-0067: `prisma dev` writes no app configuration file.)* *(Amended by ADR-0068: no command starts a second process or writes an app configuration file.)* - [ADR-0063](ADR-0063-a-node-depends-on-an-interface-or-exposes-one.md) — The two ends of a connection are named by what the node does with them: a node **depends on** an interface (`deps`) or **exposes** one (`expose`); an interface is a `Contract` in code; Input and Output are retired as port words, because the dataflow and ports-and-adapters traditions give the same two ends opposite names; the module body's `inputs` becomes `deps`; the topology's `in`/`out` stay, defined as the dependency end and the exposed end. A service also reads a platform variable, a third relationship recorded in `valueReads`, not as an edge. - [ADR-0064](ADR-0064-an-app-declares-its-platform-variables-in-its-root-and-the-deploy-copies-no-local-values.md) — A platform variable is a variable on the platform that a service reads by name at boot, declared by a node the app root provisions: `variable({ name })` or `variable.secret({ name })`. A value the operator supplies reaches the app in two ways: a root input field for a value the deploy reads, a platform variable node for a value the service reads at boot. The node creates nothing and stays out of the application topology and the deploy report; the graph check refuses two nodes with one name, a plain node and a root input field with one name, and a node bound as a service's whole input. The deploy does not copy local values (by default `.env` and the shell) to platform variables, because an implicit copy can push a local value into a remote environment; for now the operator sets each with `prisma project env add`, and an explicit way through `deploy` is expected later. Before Alchemy runs, the deploy checks that every variable a service needs has a value, and fails with the commands that set the missing ones. Under `prisma dev` a plain variable comes from the app configuration. `variable({ name, schema })` types a plain variable's value by a Standard JSON Schema such as ArkType's or Zod's: the node keeps the reduced JSON Schema, and boot and `prisma dev` decode and validate the variable's text with it, with messages that never hold the text. Variable names match `^[A-Z][A-Z0-9_]*$`, and a few names are reserved for Composer and the platform. *(Amended by ADR-0067: plain platform variable text reaches the local target in memory.)* -- [ADR-0065](ADR-0065-a-compute-services-input-document-travels-in-its-artifact.md) — On Prisma Cloud the deploy writes a Compute service's input document into its artifact, in the `inputDocument` field of `compute.bootstrap.json`, and creates no variable for it; every other value the service reads at boot (`port`, connection params, provider params, generated values) stays a variable, because each is issued during the deploy or is a secret, except `port`, which the Compute emulator has to be able to set under `prisma dev`. The printed `bootstrap.js` passes the document to the Prisma Cloud service's `run(address, boot, inputDocument)`; core's `run` keeps two parameters. The artifact is the document's only source: `run()` ignores a `COMPOSER_
_INPUT` variable when the artifact holds the document, which the upgrade needs today, and the local target ignores one for every service that runs its artifact. A changed document changes the artifact's path and replaces the deployment; the document is not a trigger member, a platform variable it names still is. Under `prisma dev` the local `Deployment` provider reads the document with the packer's own reader to decide which platform variables a service receives, and `reserve` writes it as a variable for a dev server. `package` must not write a secret or an unresolved value into an artifact. A deployment made before the upgrade cannot be put back into service. Rejected: keeping every value a variable (8 KB limit), a general map of keys in the boot file, the document as parsed JSON, the environment winning, and writing both places for one release. +- [ADR-0065](ADR-0065-a-compute-services-input-document-travels-in-its-artifact.md) — On Prisma Cloud the deploy writes a Compute service's input document into its artifact, in the `inputDocument` field of `compute.bootstrap.json`, and creates no variable for it; every other value the service reads at boot (`port`, connection params, provider params, generated values) is a key sent with the deployment (ADR-0069), because each is issued during the deploy or is a secret, except `port`, which the Compute emulator has to be able to set under `prisma dev`. The printed `bootstrap.js` passes the document to the Prisma Cloud service's `run(address, boot, inputDocument)`; core's `run` keeps two parameters. The artifact is the document's only source: `run()` ignores a `COMPOSER_
_INPUT` variable when the artifact holds the document, which the upgrade needs today, and the local target ignores one for every service that runs its artifact. A changed document changes the artifact's path and replaces the deployment; the document is not a trigger member, a platform variable it names still is. Under `prisma dev` the local `Deployment` provider reads the document with the packer's own reader to decide which platform variables a service receives, and `reserve` writes it as a local row for a dev server. `package` must not write a secret or an unresolved value into an artifact. A deployment made before the upgrade cannot be put back into service. Rejected: keeping every value a variable (8 KB limit), a general map of keys in the boot file, the document as parsed JSON, the environment winning, and writing both places for one release. - [ADR-0066](ADR-0066-deploy-runs-alchemy-in-process.md) — `prisma deploy` and the `deploy` operation run Alchemy's plan and apply in the `prisma` process through `alchemy/Alchemist`: no generated stack file, no Alchemy child. `lower()` takes containers, preflight payloads, the preflight findings and the report hook as values, the summary comes back as a value, Alchemy's events become engine step events, failures are `DEPLOY.ENGINE_FAILED` or `DEPLOY.INTERRUPTED`, and Ctrl-C releases the state lease. Every Management API request, Alchemy's and Composer's, goes through the engine's `ctx.api`, which `lower()` receives as `LowerOptions.credentials`, so a `prisma login` session deploys with no `PRISMA_SERVICE_TOKEN` and no credential enters `process.env`. Lowering and Alchemy load from the app's own install of `@prisma/composer`, which must speak the host's converge contract. Supersedes ADR-0007 for `deploy`; amends ADR-0038, ADR-0043, ADR-0044, ADR-0049, ADR-0062 and ADR-0064. *(Extended to `prisma dev` by ADR-0067.)* *(Extended to `destroy` by ADR-0068: `containers` and `preflightPayloads` are required, with no environment fallback.)* - [ADR-0067](ADR-0067-prisma-dev-converges-in-a-worker-thread.md) — Each converge of `prisma dev` runs in a new worker thread of the `prisma` process: no dev stack file, no app configuration file, no Alchemy child. The worker imports the config and the app as they are on disk, so an edit to an app definition file applies on the next rebuild; a loaded app is made of functions and cannot be handed between threads, so the import and the converge run in the same place. The main thread sends plain data in memory (values, named secrets, containers), holds the one-converge flag and the working directory for the worker, and reports its events and redacted output. Three kinds of edit still need a restart: adding or removing a node, passing on a root input field the root did not pass on at start, and changing which platform variables the app reads; under Bun, so does a directory import written before its `index.ts` exists. `destroy` keeps the stack file and the child. *(Amended by ADR-0068: `destroy` runs in process too.)* - [ADR-0068](ADR-0068-destroy-runs-alchemy-in-process.md) — The `destroy` operation runs Alchemy's plan and apply in the calling process through the app's converge entry, as `deploy` does: no generated stack file, no app configuration file, no Alchemy child, so no command starts the Alchemy CLI. Destroy reports deploy's step events except `preflight`, takes a `signal`, and fails with deploy's codes. The stack file generator, the bin lookup, the child runner and core's environment transports are deleted; `LowerOptions.containers` and `preflightPayloads` are required; `firstProcessNodeAddresses` is `preparedNodeAddresses`. Extends ADR-0066, supersedes ADR-0007. +- [ADR-0069](ADR-0069-a-services-composer-keys-travel-with-its-deployment-as-service-variables.md) — On Prisma Cloud a Compute service's `COMPOSER_` keys go in the `variables` field of the request that creates its deployment, and the platform stores them as service variables; the deploy writes no variable row. Every key boot reads is sent as its value or `null`, so a stored value such as a streams key with no consumer is deleted. A `PrismaCloud.SentVariableNames` record per service keeps every key name ever sent, and each name Composer no longer sends goes as `null`. A service with more than 50 values is refused before any resource is created, changed or deleted. The values are in deploy state in plain text and are only `COMPOSER_` keys. A changed map, an unresolved value or a first declaration replaces the deployment. Under `prisma dev` a deployment's keys come from `variables`, and a dev server keeps local rows from `reserve`, which fails outside the local application. The hosted row provider stays registered to delete old rows; the first deploy replaces each deployment once and deletes the rows, and a row whose recorded identity no longer matches is dropped with a warning. An older Composer cannot deploy an environment this version has deployed: it stops while planning, because it has no provider for `PrismaCloud.SentVariableNames`. It ships only once the platform accepts `variables` in production and both upstream packages release the field; until then they are local patches and `check:patched-dependencies` fails. Rejected: rows in branch overrides or groups, sending a complete set, leaving old keys, reading a service's keys before deploying, a platform flag, keeping values in `triggers`, one JSON variable. diff --git a/docs/guides/deploying.md b/docs/guides/deploying.md index 974f7d37b..b3778de08 100644 --- a/docs/guides/deploying.md +++ b/docs/guides/deploying.md @@ -551,10 +551,9 @@ What deployed apps actually run into, and what to do about it: authenticated for you, and your `curl` isn't one of the services the app connected to it — so it's turned away, and a provider with no consumers turns away everyone. Reach it through a consumer instead. -- **The `COMPOSER_*` variables in your project belong to the deploy.** Ports, - connection settings, generated values and service keys all land there, and - every deploy rewrites them — editing one by hand doesn't survive. A service's - input document is not among them: it travels in the service's artifact. +- **A service's `COMPOSER_*` variables belong to the deploy.** Its port, connection settings, generated values and service keys are sent with each new deployment of the service and stored on the service as service variables. You can change them in the Console, but every deploy that creates a deployment sets them again and deletes each name Composer no longer sends. A service's input document is not among them: it travels in the service's artifact. +- **A service holds at most 50 variables.** The deploy refuses a service that would send more than 50 values. Today the refusal appears as a reason inside a `DEPLOY.ENGINE_FAILED` result ("Alchemy could not deploy the app"), with the code `DEPLOY.SERVICE_VARIABLE_LIMIT` and a message naming the service, the count and the limit; `prisma dev` refuses the same service the same way. The deploy stops before any resource is created, changed or deleted; by then the branch's application topology has been replaced and the build recorded. Variables you set on a service in the Console count toward the platform's limit too, so a service close to 50 can still fail mid-deploy with "Quota exceeded for service_variable". +- **A change you make in the Console lasts until the next `prisma deploy`.** Saving a service's variables in the Console creates a deployment the deploy doesn't know; the next `prisma deploy` makes the deploy's own deployment live again. A variable you added under your own name stays stored on the service and reaches that deployment the next time the deploy replaces it; a `COMPOSER_*` variable you changed is set back then. - **Calls into a sleeping service can get `ECONNRESET`** while it cold-starts. Retry them. - **The `cron` scheduler stays awake on purpose.** It holds Compute's @@ -574,6 +573,21 @@ When something misbehaves in ways these don't explain, check [`gotchas.md`](../../gotchas.md) at the repo root — the catalogue of platform footguns with diagnoses, kept current as we hit them. +## Upgrading to service variables + +Earlier versions wrote each service's `COMPOSER_*` values as environment variables in the project: on production in the production class, on any other environment as overrides on its branch. This version sends them with each new deployment, and Prisma Cloud stores them on the service as service variables. The platform is removing branch overrides, so earlier versions' preview deploys stop working once it rejects them. + +The first deploy with this version: + +- **replaces each service's deployment once.** The new deployment is created with every value, and your service's URL does not change. +- **deletes the old variables afterwards.** Each one is deleted after the old deployment that read it has stopped. A deployment still finishing open connections keeps its variables until a later deploy finds it stopped, so some can stay visible in the Console after the first deploy. While both exist, the service's own value wins. On production the `COMPOSER_*` variables leave your project's production variables. +- **still hands a value to a key that loses it in the same deploy.** The new deployment is created while the old variables exist, and the deploy's `null` deletes only the service's own value. So if this deploy also removes a dependency, or the last consumer of a streams service, the new deployment still receives the old variable's value for that key, until the deploy next replaces it. Earlier versions behave the same. Make the upgrade deploy on its own, or deploy that service once more with a changed build afterwards. +- **skips a variable you already deleted.** A variable the platform refuses to delete because it no longer matches what the deploy recorded is dropped from the deploy's records, and the deploy prints a warning naming it. Delete it in the Console if it is still listed. + +If the first deploy is interrupted after the new deployments exist, the next deploy finishes deleting without replacing anything again. + +**Going back to an older version is not possible.** Once an environment has been deployed with this version, an older version stops while it plans the deploy, before it changes anything, with "No provider is registered for resource type 'PrismaCloud.SentVariableNames'": this version's deploy state holds a record that older versions do not know. Keep deploying the environment with this version or a newer one. + ## Upgrading to input documents in the artifact Earlier versions wrote each service's input document as an environment @@ -608,16 +622,7 @@ production has a name, `production`: ## Upgrading to addresses that start with the app name -Earlier versions left the app name out of every address below the root -(`auth.database` instead of `storefront-auth.auth.database`), and named the -deploy engine's resources `auth.database-db`, `auth.database-conn` and so on. -The first deploy with this version moves every resource of an existing -environment to its new name in place. Databases keep their rows, buckets keep -their objects, and generated secrets and service keys keep their values. The -platform resources' `logicalId`s change to the full address in the same deploy. -Environment variable keys gain the app name (`COMPOSER_STOREFRONT_AUTH_…`): each -variable is replaced by one with the same value under the new key, and services -get a new deployment. +Earlier versions left the app name out of every address below the root (`auth.database` instead of `storefront-auth.auth.database`), and named the deploy engine's resources `auth.database-db`, `auth.database-conn` and so on. The first deploy with this version moves every resource of an existing environment to its new name in place. Databases keep their rows, buckets keep their objects, and generated secrets and service keys keep their values. The platform resources' `logicalId`s change to the full address in the same deploy. Configuration keys gain the app name (`COMPOSER_STOREFRONT_AUTH_…`), and services get a new deployment. Every name Composer gives a platform resource becomes the full address too: apps, buckets and Composer's database connections and bucket access keys are @@ -641,25 +646,7 @@ Two things to do yourself: - **Don't deploy an environment with an older version afterwards.** It would look for the old names and recreate every resource, losing their data. -An app with a module or a service directly below the root named like the app -(`shop.shop.x` beside `shop.x`, in any letter case), or with modules that spell -an app name containing `-` or `_` (`my-shop.my.shop.x` beside `my-shop.x`), can -hit one more step. There, one node's new variable key is the key an earlier -version wrote for another node. The deploy stops before any resource is created, changed or deleted, and -names the variable and both nodes. The Branch's topology in the Console already -shows the new addresses by then. It lists every such variable at once. Delete each, -then deploy again: - -```sh -prisma project env delete 'COMPOSER_SHOP_X_ORIGIN' --project '' --role production -prisma project env delete 'COMPOSER_SHOP_X_ORIGIN' --project '' --branch '' -``` - -The first form is for production, the second for any other environment; the -Console's Environment variables page works too. Nothing is lost: the deploy -writes every value under its new key, and running services keep their own copy -until then. Don't rename either node to get around it: a new address is a new -entity, and its old rows, and a database's or bucket's data, are deleted. +**Deploy once with a release from 0.35.0 to 0.39.0 first** if your app is on a release before 0.35.0. Those releases make this move while the old variables can still be checked: an app with a module or a service directly below the root named like the app (`shop.shop.x` beside `shop.x`, in any letter case), or with modules that spell an app name containing `-` or `_` (`my-shop.my.shop.x` beside `my-shop.x`), can give one node's new key to the key an earlier version wrote for another node, and those releases stop and name it. The current version writes no variable rows and does not check, so a service that has no value for such a key would receive the other node's old value once. `prisma dev` keeps its local services, databases and buckets: on its first run it rewrites the directory's record to the new addresses. `prisma dev url` takes @@ -690,7 +677,7 @@ Legacy leftovers are inert and safe to remove whenever convenient — nothing re Framework versions that manage databases, apps, deployments, and environment variables through upstream alchemy's Prisma provider adopt each environment's existing resources in place — deploy state already in the platform state API is migrated automatically on read (rows written under retired type-ids), and existing databases and connections are adopted, never replaced. The first redeploy can still converge database *properties* in place — Branch attachment and display name — as the one-time effects below describe. Environments still on the older SQL state store are not migrated — destroy and redeploy them, as the section above describes. -**A service's deployment is replaced exactly when its artifact or environment changed, and reused otherwise.** The platform freezes a deployment's environment when the deployment is created, so a changed value only takes effect through a new one — the framework declares each service's environment values as the deployment's replacement triggers (alchemy's `Prisma.Deployment.triggers`), so a changed variable, a value re-issued in place (a connection rotated in place, a re-minted service key), or an out-of-band rotation of a platform variable a service's input document names all ship a new deployment, and an unchanged service redeploys nothing. No plaintext lands in deploy state — alchemy persists only a salted fingerprint of the trigger values. A replacement uploads the artifact, starts it, moves the stable endpoint over, and removes the old deployment; your service's URL does not change. +**A service's deployment is replaced exactly when its artifact or environment changed, and reused otherwise.** The platform copies a deployment's environment when the deployment is created, so a changed value only takes effect through a new one. A changed value of the service's own (including one re-issued in place: a connection rotated in place, a re-minted service key), a key added or removed, or an out-of-band change to a platform variable the service's input document names all ship a new deployment, and an unchanged service redeploys nothing. The service's own values are stored in deploy state as text, as the deployment's `variables`; your platform variables' values never are. A replacement uploads the artifact, starts it, moves the stable endpoint over, and removes the old deployment; your service's URL does not change. **The framework never writes, modifies or deletes `DATABASE_URL` or `DATABASE_URL_POOLED`.** Prisma Cloud writes them only when a project is created with a database, or when a database is created as the project's default. The framework creates your project without one, so on a project it created neither variable exists unless you set it. On a project created outside the framework with a default database, both hold live values, and every service on production receives them, as on any Prisma Cloud project. Nothing you declare can carry those names (`variable()` and `variable.secret()` reject them), and every database URL your services use comes from the connection they declare. diff --git a/docs/guides/running-locally.md b/docs/guides/running-locally.md index ed7907d5c..844df914b 100644 --- a/docs/guides/running-locally.md +++ b/docs/guides/running-locally.md @@ -43,6 +43,8 @@ catalog.service: http://localhost:3000 orders.service: http://localhost:3003 ``` +**Where a service's environment comes from.** A service that runs its built artifact gets its `COMPOSER_*` values from its deployment, as on Prisma Cloud: the deploy pipeline computes them, and the local target hands them to the process without writing them anywhere, with the port the emulator gave the service in place of its own. A value that changes restarts exactly the service that reads it. A service that runs a dev server has no deployment, so its values are kept in `env.json` in the environment's folder, where the dev server reads them. Platform variables come from your app configuration and secrets, for both. + `dev` prints `ready` only once every service accepts connections on its port, so a request to a printed URL right away connects. After a rebuild, `dev` waits the same way before it prints the URLs again. A service must listen on the port Composer gives it, unless it is declared with `compute({ ..., listens: false })`: such a service, like the cron module's scheduler, is running as soon as its process starts. If a service exits before it listens, or does not listen within 30 seconds, `dev` fails instead of printing `ready`, and stops the app's other services. The message names the service, its port, and its log file, for example `service "my-app.gateway" exited (code 1) before it accepted connections on its port 3001. Its log: …/svc_….log`. On a first start it is in the message of `prisma dev`'s error that the app could not be converged (`DEV.CONVERGE_FAILED` from the `dev` operation in `@prisma/composer/control`). On a warm start it is the message of the `DEV.SERVICE_START_FAILED` error. @@ -237,11 +239,7 @@ prisma dev url my-app.gateway --environment test # test's URL prisma dev stop --environment test ``` -`--fresh` wipes only the environment it runs in. Everything local to one copy -lives in `.prisma-composer/dev//`: the record of its instances, -its environment variable values, the key `prisma dev` hashes secret values with, the generated stack -file, the unpacked artifacts and the bucket objects. The deploy engine keeps -each copy's state in `.alchemy/state//`. +`--fresh` wipes only the environment it runs in. Everything local to one copy lives in `.prisma-composer/dev//`: the record of its instances, its dev servers' `COMPOSER_*` values (`env.json`), the key `prisma dev` hashes secret values with, the generated stack file, the unpacked artifacts and the bucket objects. The deploy engine keeps each copy's state in `.alchemy/state//`. Environment names are case-sensitive, but on a case-insensitive filesystem, such as the default on macOS, `Dev` and `dev` would share one folder. So the diff --git a/package.json b/package.json index b8372bda8..208039504 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,7 @@ "check:cli-engine-pin": "node scripts/check-cli-engine-pin.mjs", "check:skill-packaging": "node scripts/check-skill-packaging.mjs", "check:orm-pins": "node scripts/check-orm-pins.mjs", + "check:patched-dependencies": "bun scripts/check-patched-dependencies.ts", "contracts:emit": "node scripts/emit-contracts.mjs", "check:contracts-emitted": "node scripts/emit-contracts.mjs --check", "check:family-static-graph": "node scripts/check-family-static-graph.mjs", @@ -58,7 +59,11 @@ "onlyBuiltDependencies": [ "prisma", "@prisma/engines" - ] + ], + "patchedDependencies": { + "@alchemy.run/prisma@2.0.0-beta.87": "patches/@alchemy.run__prisma@2.0.0-beta.87.patch", + "@distilled.cloud/prisma@1.0.0-rc.20": "patches/@distilled.cloud__prisma@1.0.0-rc.20.patch" + } }, "version": "0.39.0" } diff --git a/packages/1-prisma-cloud/0-lowering/local-target/src/__tests__/compute-materialize-env.test.ts b/packages/1-prisma-cloud/0-lowering/local-target/src/__tests__/compute-materialize-env.test.ts index acfd05a27..8e872d476 100644 --- a/packages/1-prisma-cloud/0-lowering/local-target/src/__tests__/compute-materialize-env.test.ts +++ b/packages/1-prisma-cloud/0-lowering/local-target/src/__tests__/compute-materialize-env.test.ts @@ -3,7 +3,8 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { readDocument } from '@internal/input-document'; -import { materializeEnv } from '../compute.ts'; +import * as Redacted from 'effect/Redacted'; +import { deploymentRows, devServerRows, materializeEnv } from '../compute.ts'; import { envStore } from '../dev-store.ts'; const NAMES = ['STRIPE_SECRET_KEY', 'APP_ORIGIN']; @@ -39,8 +40,14 @@ test('each service gets the current values of only the variables its own rows po UNRELATED_SECRET: 'not for any service', }; - const billing = await materializeEnv(devDir, 'billing', 4000, {}, secrets); - const mailer = await materializeEnv(devDir, 'mailer', 4001, {}, secrets); + const billing = materializeEnv( + await devServerRows(devDir, 'billing'), + 'billing', + 4000, + {}, + secrets, + ); + const mailer = materializeEnv(await devServerRows(devDir, 'mailer'), 'mailer', 4001, {}, secrets); expect(billing['STRIPE_SECRET_KEY']).toBe('sk_test_1'); expect(billing['APP_ORIGIN']).toBe('http://localhost:3000'); @@ -56,10 +63,16 @@ test('a value changed in the app secrets reaches the service on the next materia stripeKey: { $platform: { name: 'STRIPE_SECRET_KEY', secret: true } }, }), }); - await materializeEnv(devDir, 'billing', 4000, {}, { STRIPE_SECRET_KEY: 'sk_test_old' }); + materializeEnv( + await devServerRows(devDir, 'billing'), + 'billing', + 4000, + {}, + { STRIPE_SECRET_KEY: 'sk_test_old' }, + ); - const billing = await materializeEnv( - devDir, + const billing = materializeEnv( + await devServerRows(devDir, 'billing'), 'billing', 4000, {}, @@ -77,7 +90,13 @@ test('a platform variable that is unset or empty is not given to the service', a }), }); - const billing = await materializeEnv(devDir, 'billing', 4000, {}, { MAILER_KEY: '' }); + const billing = materializeEnv( + await devServerRows(devDir, 'billing'), + 'billing', + 4000, + {}, + { MAILER_KEY: '' }, + ); expect('STRIPE_SECRET_KEY' in billing).toBe(false); expect('MAILER_KEY' in billing).toBe(false); @@ -93,8 +112,8 @@ test('a local deployment takes its secrets from the app secrets and its plain pl process.env['STRIPE_SECRET_KEY'] = 'shell'; process.env['APP_ORIGIN'] = 'shell'; - const billing = await materializeEnv( - devDir, + const billing = materializeEnv( + await devServerRows(devDir, 'billing'), 'billing', 4000, { APP_ORIGIN: 'https://pool.example' }, @@ -110,7 +129,13 @@ test('a plain platform variable whose value is not text is left out', async () = COMPOSER_WEB_INPUT: JSON.stringify({ origin: { $platform: { name: 'APP_ORIGIN' } } }), }); - const web = await materializeEnv(devDir, 'web', 4000, { APP_ORIGIN: { host: 'x' } }, {}); + const web = materializeEnv( + await devServerRows(devDir, 'web'), + 'web', + 4000, + { APP_ORIGIN: { host: 'x' } }, + {}, + ); expect('APP_ORIGIN' in web).toBe(false); }); @@ -121,7 +146,13 @@ test('a dev server reads a typed variable from its env.json document, schema inc }); await writeRows({ COMPOSER_MAILER_INPUT: document }); - const mailer = await materializeEnv(devDir, 'mailer', 4000, { SMTP_PORT: '587' }, {}); + const mailer = materializeEnv( + await devServerRows(devDir, 'mailer'), + 'mailer', + 4000, + { SMTP_PORT: '587' }, + {}, + ); expect(mailer['SMTP_PORT']).toBe('587'); const input = mailer['COMPOSER_MAILER_INPUT'] ?? ''; @@ -136,14 +167,7 @@ test("a service that runs its artifact gets a typed variable's text, and decodes port: { $platform: { name: 'SMTP_PORT', schema: { type: 'number' } } }, }; - const mailer = await materializeEnv( - devDir, - 'mailer', - 4000, - { SMTP_PORT: '587' }, - {}, - { inputDocument }, - ); + const mailer = materializeEnv({}, 'mailer', 4000, { SMTP_PORT: '587' }, {}, { inputDocument }); expect(mailer['SMTP_PORT']).toBe('587'); expect('COMPOSER_MAILER_INPUT' in mailer).toBe(false); @@ -153,14 +177,13 @@ test("a service that runs its artifact gets a typed variable's text, and decodes }); test("a service gets the variables its artifact's input document names, and not the document itself", async () => { - await writeRows({ COMPOSER_WEB_PORT: '3000' }); const inputDocument = { stripeKey: { $platform: { name: 'STRIPE_SECRET_KEY', secret: true } }, origin: { $platform: { name: 'APP_ORIGIN' } }, }; - const web = await materializeEnv( - devDir, + const web = materializeEnv( + {}, 'web', 4000, { APP_ORIGIN: 'http://localhost:3000', UNREAD_NAME: 'not read' }, @@ -175,39 +198,35 @@ test("a service gets the variables its artifact's input document names, and not expect('COMPOSER_WEB_INPUT' in web).toBe(false); }); -test('a stale input document in env.json gives the service nothing when its artifact carries one', async () => { - await writeRows({ - COMPOSER_WEB_INPUT: JSON.stringify({ - old: { $platform: { name: 'OLD_SECRET', secret: true } }, - }), +test('a deployment gives its service the keys in its variables, and leaves out a key sent as null', () => { + const rows = deploymentRows({ + COMPOSER_WEB_DB_URL: Redacted.make('postgres://local'), + COMPOSER_WEB_STREAMS_API_KEY: null, }); - const inputDocument = { - stripeKey: { $platform: { name: 'STRIPE_SECRET_KEY', secret: true } }, - }; - const web = await materializeEnv( - devDir, + expect(rows).toEqual({ COMPOSER_WEB_DB_URL: 'postgres://local' }); +}); + +test("a service that runs its artifact gets its deployment's keys, the emulator's port over its own, and not env.json", async () => { + await writeRows({ COMPOSER_WEB_STALE: 'a row an older Composer wrote' }); + const inputDocument = { stripeKey: { $platform: { name: 'STRIPE_SECRET_KEY', secret: true } } }; + + const web = materializeEnv( + deploymentRows({ + COMPOSER_WEB_PORT: Redacted.make('3000'), + COMPOSER_WEB_DB_URL: Redacted.make('postgres://local'), + COMPOSER_WEB_STREAMS_API_KEY: null, + }), 'web', 4000, {}, - { OLD_SECRET: 'sk_old', STRIPE_SECRET_KEY: 'sk_test_1' }, + { STRIPE_SECRET_KEY: 'sk_test_1' }, { inputDocument }, ); - expect('OLD_SECRET' in web).toBe(false); + expect(web['COMPOSER_WEB_PORT']).toBe('4000'); + expect(web['COMPOSER_WEB_DB_URL']).toBe('postgres://local'); expect(web['STRIPE_SECRET_KEY']).toBe('sk_test_1'); - expect('COMPOSER_WEB_INPUT' in web).toBe(false); -}); - -test('a stale input document in env.json gives the service nothing when its artifact carries none', async () => { - await writeRows({ - COMPOSER_WEB_INPUT: JSON.stringify({ - old: { $platform: { name: 'OLD_SECRET', secret: true } }, - }), - }); - - const web = await materializeEnv(devDir, 'web', 4000, {}, { OLD_SECRET: 'sk_old' }, {}); - - expect('OLD_SECRET' in web).toBe(false); - expect('COMPOSER_WEB_INPUT' in web).toBe(false); + expect('COMPOSER_WEB_STREAMS_API_KEY' in web).toBe(false); + expect('COMPOSER_WEB_STALE' in web).toBe(false); }); diff --git a/packages/1-prisma-cloud/0-lowering/local-target/src/compute.ts b/packages/1-prisma-cloud/0-lowering/local-target/src/compute.ts index 6e2865b6d..6e7c627e2 100644 --- a/packages/1-prisma-cloud/0-lowering/local-target/src/compute.ts +++ b/packages/1-prisma-cloud/0-lowering/local-target/src/compute.ts @@ -78,7 +78,7 @@ async function artifactSha256(artifactPath: string): Promise { const COMPOSER_NAMESPACE_PREFIX = 'COMPOSER_'; /** - * Scopes `env.json` to what THIS service may see: rows it owns + * Scopes `env.json` to what THIS dev server may see: rows it owns * (`COMPOSER__*`) plus every unprefixed (platform-owned, * app-wide) row. Materializing the app-wide set locally causes spurious * restarts — an early service's snapshot "completes" on the second converge @@ -169,23 +169,38 @@ export function readComputeManifest(artifactDir: string): { return { address: parsed.address, listens: parsed.listens !== false }; } +/** A deployment's own `COMPOSER_` keys, from its `variables` prop. A key sent as `null` is left out, so the service reads it as never provided. */ +export function deploymentRows( + variables: Readonly | null>> | undefined, +): Record { + const rows: Record = {}; + for (const [key, value] of Object.entries(variables ?? {})) { + if (value !== null) rows[key] = Redacted.value(value); + } + return rows; +} + +/** A dev server's own rows, which `reserve` wrote to `env.json` (ADR-0056). */ +export async function devServerRows( + devDir: string, + address: string, +): Promise> { + return scopedEnvRows(await envStore(devDir).read(), address); +} + /** - * A deployment's environment: its own rows, its port, the platform variables its input document names, and `PATH` and `HOME`. - * For a service that runs its `artifact`, the `env.json` input entry is stale and left out, and the - * platform variables come from the artifact's `inputDocument`. A dev server has no `artifact` and is - * given the same otherwise (ADR-0056). + * A service's environment: its own rows, its port, the platform variables its input document names, and `PATH` and `HOME`. + * For a service that runs its `artifact`, the platform variables come from the artifact's + * `inputDocument`; for a dev server, from the input document among its rows (ADR-0056). */ -export async function materializeEnv( - devDir: string, +export function materializeEnv( + rows: Readonly>, address: string, port: number, configuration: Readonly>, secrets: Readonly>, artifact?: { readonly inputDocument?: unknown }, -): Promise> { - const rows = scopedEnvRows(await envStore(devDir).read(), address); - const inputKey = composerKey(address, INPUT_KEY_NAME); - if (artifact !== undefined) delete rows[inputKey]; +): Record { const env: Record = { ...rows }; env[composerKey(address, 'PORT')] = JSON.stringify(port); const named = @@ -311,9 +326,9 @@ export function LocalEnvironmentVariableProvider( /** * `Prisma.Deployment` → unpacks the artifact once per hash, finds the * service's emulator instance and its port, builds the child's env with - * `materializeEnv` from the input document the artifact carries, and puts the - * deployment — the - * emulator (re)starts the child only when the hash or env actually changed. + * `materializeEnv` from the deployment's `variables` and the input document + * the artifact carries, and puts the deployment — the emulator (re)starts the + * child only when the hash or env actually changed. * `portMapping` is ignored on purpose: the emulator owns port allocation, and * the child learns its port from `COMPOSER_
_PORT` in the env this * provider materializes. @@ -339,8 +354,8 @@ export function LocalDeploymentProvider( const { address, listens } = readComputeManifest(artifactDir); const { instance } = await ensureServiceInstance(appScopeOf(input), appId); - const env = await materializeEnv( - input.devDir, + const env = materializeEnv( + deploymentRows(news.variables), address, instance.port, input.plainVariableText, diff --git a/packages/1-prisma-cloud/0-lowering/lowering/src/compute/__tests__/deployment-edge.test.ts b/packages/1-prisma-cloud/0-lowering/lowering/src/compute/__tests__/deployment-edge.test.ts index c5dfe6b57..5bfd38ac6 100644 --- a/packages/1-prisma-cloud/0-lowering/lowering/src/compute/__tests__/deployment-edge.test.ts +++ b/packages/1-prisma-cloud/0-lowering/lowering/src/compute/__tests__/deployment-edge.test.ts @@ -1,11 +1,7 @@ /** - * The environment→deployment ordering edge, against the REAL Output machinery - * and upstream's REAL `Prisma.Deployment` provider (an eager-collapse stub - * cannot represent the unresolved half of planning). Two properties on the - * deploy that adds a variable and changes code in one run: every variable - * write and the app are upstream of the deployment, and the artifact - * comparison still runs while the new variable is unresolved (see - * deployment-edge.ts for why only the `app` prop keeps that true). + * The deployment's ordering edge and its replacement rules, against the REAL + * Output machinery and upstream's REAL `Prisma.Deployment` diff (an + * eager-collapse stub cannot represent the unresolved half of planning). */ import { afterAll, describe, expect, test } from 'bun:test'; @@ -35,27 +31,11 @@ const app = registered( Prisma.App('auth-svc', { project: 'proj-1', displayName: 'auth', regionId: 'us-east-1' }), ); -/** Two variables: one this deploy already had, one it is adding. */ -const persistedVariable = registered( - Prisma.EnvironmentVariable('COMPOSER_AUTH_PORT-var', { - project: 'proj-1', - class: 'production', - key: 'COMPOSER_AUTH_PORT', - value: Redacted.make('3000'), - }), +/** A resource the same deploy may be changing, so its attributes are unresolved while planning. */ +const generated = registered( + Prisma.App('generated-svc', { project: 'proj-1', displayName: 'gen', regionId: 'us-east-1' }), ); -const newVariable = registered( - Prisma.EnvironmentVariable('COMPOSER_AUTH_DB_URL-var', { - project: 'proj-1', - class: 'production', - key: 'COMPOSER_AUTH_DB_URL', - value: Redacted.make('postgres://db'), - }), -); - -const environment = [persistedVariable, newVariable]; - const artifactDir = fs.mkdtempSync(path.join(os.tmpdir(), 'deployment-edge-')); const artifactPath = path.join(artifactDir, 'auth.tar.gz'); fs.writeFileSync(artifactPath, 'artifact-generation-2'); @@ -65,12 +45,16 @@ afterAll(() => { }); /** The deploy hook's props, built by the same helper the descriptor uses. */ -const deploymentProps = (triggers?: Record) => ({ - app: appAfter(app.appId, environment, []), +const deploymentProps = ( + triggers?: Record, + variables?: Record, +) => ({ + app: appAfter(app.appId, []), artifactPath, artifactContentType: 'application/gzip', portMapping: { http: 8080 }, ...(triggers !== undefined ? { triggers } : {}), + ...(variables !== undefined ? { variables } : {}), start: true, promote: true, }); @@ -118,6 +102,7 @@ const deploymentService = () => const persistedOutput = ( artifactHash: string, triggersHash?: Redacted.Redacted | string, + variablesHash?: Redacted.Redacted | string, ) => ({ deploymentId: 'dep-1', appId: 'app-1', @@ -126,19 +111,16 @@ const persistedOutput = ( previewDomain: null, artifactHash, ...(triggersHash !== undefined ? { triggersHash } : {}), + ...(variablesHash !== undefined ? { variablesHash } : {}), appEndpointDomain: 'auth.prisma.app', createdAt: '2025-01-01T00:00:00.000Z', }); -/** - * `news` as the planner hands it over on the deploy that adds a variable: the - * combined `app` expression cannot resolve (the new variable has no state to - * resolve to), every other prop is a value. `olds` are the previous deploy's - * persisted props, where `app` had resolved to the app id. - */ +/** `olds` are the previous deploy's persisted props, where `app` had resolved to the app id. */ const diffAgainst = async ( output: Record, triggers: { old?: Record; new?: Record } = {}, + variables: { old?: Record; new?: Record } = {}, ) => { const service = await deploymentService(); if (service.diff === undefined) throw new Error('provider must expose diff'); @@ -148,8 +130,8 @@ const diffAgainst = async ( id: 'auth-deploy', fqn: 'auth-deploy', instanceId: 'inst-deploy', - olds: { ...deploymentProps(triggers.old), app: 'app-1' }, - news: deploymentProps(triggers.new), + olds: { ...deploymentProps(triggers.old, variables.old), app: 'app-1' }, + news: deploymentProps(triggers.new, variables.new), output, session: undefined, bindings: [], @@ -159,28 +141,8 @@ const diffAgainst = async ( }; describe('appAfter — the edge Alchemy actually plans on', () => { - test('every variable AND the app are upstream of the deployment', () => { - const upstream = Output.upstreamAny(deploymentProps()); - expect(Object.keys(upstream).sort()).toEqual( - ['COMPOSER_AUTH_DB_URL-var', 'COMPOSER_AUTH_PORT-var', 'auth-svc'].sort(), - ); - }); - - test('the combined expression still resolves to the app id — not a variable id or tuple', () => { - const resolved = Effect.runSync( - Output.evaluate(appAfter(app.appId, environment, []), { - 'auth-svc': { appId: 'app-123' }, - 'COMPOSER_AUTH_PORT-var': { environmentVariableId: 'var-1' }, - 'COMPOSER_AUTH_DB_URL-var': { environmentVariableId: 'var-2' }, - }) as Effect.Effect, - ); - expect(resolved).toBe('app-123'); - }); - - test('a service with no variables passes the app id straight through', () => { - expect(Object.keys(Output.upstreamAny({ app: appAfter(app.appId, [], []) }))).toEqual([ - 'auth-svc', - ]); + test('a service with no producers passes the app id straight through', () => { + expect(Object.keys(Output.upstreamAny({ app: appAfter(app.appId, []) }))).toEqual(['auth-svc']); }); test("a producer's outputs are upstream of the deployment, and it still resolves to the app id", () => { @@ -191,7 +153,7 @@ describe('appAfter — the edge Alchemy actually plans on', () => { regionId: 'us-east-1', }), ); - const edge = appAfter(app.appId, [], [producer.appId]); + const edge = appAfter(app.appId, [producer.appId]); expect(Object.keys(Output.upstreamAny({ app: edge })).sort()).toEqual( ['auth-svc', 'producer-svc'].sort(), @@ -210,13 +172,10 @@ describe('appAfter — the edge Alchemy actually plans on', () => { expect(Output.isOutput(props.artifactPath)).toBe(false); expect(Output.isOutput(props.artifactContentType)).toBe(false); expect(Output.isOutput(props.portMapping)).toBe(false); - // The unresolved half is confined to `app` and (possibly) `triggers` - // members, which is the point: upstream's replacement block stays resolved. - expect(Output.isOutput(props.app)).toBe(true); }); }); -describe('upstream Deployment.diff while the new variable is still unresolved', () => { +describe('upstream Deployment.diff compares the artifact', () => { test('a changed artifact plans a REPLACE — the code change is not dropped', async () => { const diff = await diffAgainst(persistedOutput('the-previous-generations-fingerprint')); expect(diff).toEqual({ action: 'replace' }); @@ -224,109 +183,135 @@ describe('upstream Deployment.diff while the new variable is still unresolved', test('an identical artifactPath plans no replacement', async () => { const diff = await diffAgainst(persistedOutput(await artifactFingerprint())); - // An update, not a replace: with the SAME path and bytes, upstream reuses - // the deployment and only re-asserts start/promote. The platform never - // re-reads environment rows into a reused deployment, so a real deploy may - // only reach this plan when its environment is unchanged too — which is - // what folding the environment into the path enforces. expect(diff).toEqual({ action: 'update' }); }); }); -/** - * What each environment declares as `triggers`, and what upstream plans for - * it. The environment-value-only change is the case that has no other signal - * at all: no other Deployment prop moves, and the platform never returns a - * value — so the triggers fingerprint is the ONLY thing that can tell - * upstream to ship a fresh deployment, which the platform requires because it - * materializes env rows only at deployment create (PRO-211). These members - * mirror the compute descriptor's: one Redacted member per env row, plus a - * `:updatedAt` member per platform variable the input document names. - */ -const envTriggers = (port: string, updatedAt = '2026-01-02T00:00:00.000Z') => ({ - COMPOSER_AUTH_PORT: Redacted.make(port), - COMPOSER_AUTH_INPUT: Redacted.make( - '{"apiKey":{"$platform":{"name":"STRIPE_KEY","secret":true}}}', - ), +/** The compute descriptor's triggers: one `:updatedAt` member per platform variable the input document names. */ +const platformTriggers = (updatedAt = '2026-01-02T00:00:00.000Z') => ({ 'STRIPE_KEY:updatedAt': updatedAt, }); -/** Upstream's recorded fingerprint for these triggers — its salt, its formula (`triggersHashOf`), so the diff compares against exactly what a prior apply persisted. */ -const recordedTriggersHash = (triggers: Record) => +/** Upstream's recorded fingerprint, by its own salt and formula, so the diff compares against exactly what a prior apply persisted. */ +const recordedHash = (field: 'triggers' | 'variables', value: Record) => Effect.runPromise( sha256Object({ - salt: 'alchemy/Prisma.Deployment/triggers/v1', - triggers: Object.fromEntries( - Object.entries(triggers).map(([key, value]) => [ + salt: `alchemy/Prisma.Deployment/${field}/v1`, + [field]: Object.fromEntries( + Object.entries(value).map(([key, item]) => [ key, - Redacted.isRedacted(value) ? Redacted.value(value) : value, + Redacted.isRedacted(item) ? Redacted.value(item) : item, ]), ), }), ); -describe('the environment triggers, against upstream diff', () => { - test('nothing changed — upstream reuses the deployment rather than replacing it', async () => { - const unchanged = envTriggers('3000'); +describe('the platform variable triggers, against upstream diff', () => { + test('nothing changed — upstream reuses the deployment', async () => { + const unchanged = platformTriggers(); const diff = await diffAgainst( - persistedOutput(await artifactFingerprint(), await recordedTriggersHash(unchanged)), + persistedOutput(await artifactFingerprint(), await recordedHash('triggers', unchanged)), { old: unchanged, new: unchanged }, ); - // An update, not a replace: same triggers, same bytes, so upstream keeps - // the running deployment and only re-asserts start/promote. expect(diff).toEqual({ action: 'update' }); }); - test('a changed environment VALUE plans a replace, though the bytes are identical', async () => { + test('a changed platform variable plans a replace, though the bytes are identical', async () => { + const diff = await diffAgainst( + persistedOutput( + await artifactFingerprint(), + await recordedHash('triggers', platformTriggers()), + ), + { old: platformTriggers(), new: platformTriggers('2026-06-30T09:15:00.000Z') }, + ); + expect(diff).toEqual({ action: 'replace' }); + }); +}); + +const serviceVariables = (port: string) => ({ + COMPOSER_SHOP_AUTH_PORT: Redacted.make(port), + COMPOSER_SHOP_AUTH_STREAMS_API_KEY: null, +}); + +describe('the service variables, against upstream diff', () => { + test('unchanged variables reuse the deployment', async () => { + const diff = await diffAgainst( + persistedOutput( + await artifactFingerprint(), + undefined, + await recordedHash('variables', serviceVariables('3000')), + ), + {}, + { old: serviceVariables('3000'), new: serviceVariables('3000') }, + ); + expect(diff).toEqual({ action: 'update' }); + }); + + test('a changed value plans a replace, though the bytes are identical', async () => { const diff = await diffAgainst( - persistedOutput(await artifactFingerprint(), await recordedTriggersHash(envTriggers('3000'))), - { old: envTriggers('3000'), new: envTriggers('8080') }, + persistedOutput( + await artifactFingerprint(), + undefined, + await recordedHash('variables', serviceVariables('3000')), + ), + {}, + { old: serviceVariables('3000'), new: serviceVariables('8080') }, ); expect(diff).toEqual({ action: 'replace' }); }); - test('a rotated POINTED platform variable plans a replace, though every row is identical', async () => { + test('a key deleted with null plans a replace', async () => { const diff = await diffAgainst( - persistedOutput(await artifactFingerprint(), await recordedTriggersHash(envTriggers('3000'))), + persistedOutput( + await artifactFingerprint(), + undefined, + await recordedHash('variables', serviceVariables('3000')), + ), + {}, { - old: envTriggers('3000'), - new: envTriggers('3000', '2026-06-30T09:15:00.000Z'), + old: serviceVariables('3000'), + new: { ...serviceVariables('3000'), COMPOSER_SHOP_AUTH_OLD: null }, }, ); expect(diff).toEqual({ action: 'replace' }); }); - test('a changed artifact plans a replace under unchanged triggers', async () => { - const unchanged = envTriggers('3000'); + test('declaring variables on a deployment created without them plans a replace', async () => { + const unchanged = platformTriggers(); const diff = await diffAgainst( - persistedOutput('the-previous-artifacts-fingerprint', await recordedTriggersHash(unchanged)), + persistedOutput(await artifactFingerprint(), await recordedHash('triggers', unchanged)), { old: unchanged, new: unchanged }, + { new: serviceVariables('3000') }, ); expect(diff).toEqual({ action: 'replace' }); }); - test('the FIRST deploy that declares triggers records the fingerprint without replacing', async () => { - // The persisted output predates triggers (no triggersHash recorded), so - // there is nothing to compare against: upstream lets the engine's plain - // update record the fingerprint instead of forcing a replacement. This is - // what makes adopting the seam free for already-deployed services. - const diff = await diffAgainst(persistedOutput(await artifactFingerprint()), { - new: envTriggers('3000'), - }); - expect(diff).toEqual({ action: 'update' }); + test('a value still unresolved at plan time plans a replace', async () => { + const diff = await diffAgainst( + persistedOutput( + await artifactFingerprint(), + undefined, + await recordedHash('variables', serviceVariables('3000')), + ), + {}, + { + old: serviceVariables('3000'), + new: { + ...serviceVariables('3000'), + COMPOSER_SHOP_AUTH_ORIGIN: Output.map(generated.appEndpointDomain, (domain) => + Redacted.make(String(domain)), + ), + }, + }, + ); + expect(diff).toEqual({ action: 'replace' }); }); - test('a trigger member still unresolved at plan time replaces conservatively', async () => { - // The member reads an attribute of a resource the same deploy is changing, - // so the diff cannot prove the fingerprint unchanged — upstream replaces - // rather than silently reusing a deployment with a possibly-stale value. - const unresolved = { - ...envTriggers('3000'), - COMPOSER_AUTH_DB_URL: Output.map(newVariable.environmentVariableId, (value) => value), - }; + test('a changed artifact still plans a replace while a variable is unresolved', async () => { const diff = await diffAgainst( - persistedOutput(await artifactFingerprint(), await recordedTriggersHash(envTriggers('3000'))), - { old: envTriggers('3000'), new: unresolved }, + persistedOutput('the-previous-artifacts-fingerprint'), + {}, + { new: { COMPOSER_SHOP_AUTH_ORIGIN: Output.map(generated.appId, Redacted.make) } }, ); expect(diff).toEqual({ action: 'replace' }); }); diff --git a/packages/1-prisma-cloud/0-lowering/lowering/src/compute/__tests__/deployment-environment-lifecycle.test.ts b/packages/1-prisma-cloud/0-lowering/lowering/src/compute/__tests__/deployment-environment-lifecycle.test.ts deleted file mode 100644 index a824fe4b9..000000000 --- a/packages/1-prisma-cloud/0-lowering/lowering/src/compute/__tests__/deployment-environment-lifecycle.test.ts +++ /dev/null @@ -1,294 +0,0 @@ -import { expect, test } from 'bun:test'; -import * as Prisma from '@alchemy.run/prisma'; -import * as Output from 'alchemy/Output'; -import * as Provider from 'alchemy/Provider'; -import * as Deferred from 'effect/Deferred'; -import * as Effect from 'effect/Effect'; -import * as Exit from 'effect/Exit'; -import * as Fiber from 'effect/Fiber'; -import * as Layer from 'effect/Layer'; -import * as Redacted from 'effect/Redacted'; -import { data, fakeManagementApi, page } from '../../fake-management-api.ts'; -import { runScratch, scratchStack } from '../../scratch-stack.ts'; -import { appAfter } from '../deployment-edge.ts'; - -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null; -} - -function field(body: unknown, name: string): string { - if (!isRecord(body) || typeof body[name] !== 'string') { - throw new Error(`Expected request field ${name}`); - } - return body[name]; -} - -const scenarios: { - name: string; - input: string; - addVariable?: boolean; - repairDrift?: boolean; - failUpdate?: boolean; -}[] = [ - { name: 'changed existing input', input: '{"required":"new"}' }, - { name: 'new required field', input: '{"required":"old","added":"new"}' }, - { name: 'unchanged input repaired after drift', input: '{"required":"old"}', repairDrift: true }, - { name: 'changed, unchanged, and new variables', input: '{"required":"new"}', addVariable: true }, - { name: 'failed input update', input: '{"required":"new"}', failUpdate: true }, -]; - -test.each(scenarios)( - 'deployment snapshots completed environment writes: $name', - async ({ input, addVariable = false, repairDrift = false, failUpdate = false }) => { - const variables = new Map(); - const values = new Map(); - const deployments = new Map(); - const snapshots: Record[] = []; - const events: string[] = []; - const updateStarted = Deferred.makeUnsafe(); - const releaseUpdate = Deferred.makeUnsafe(); - let generation = 0; - - const client = { - listEnvironmentVariables: ({ key } = {}) => - Effect.sync(() => - [...variables.values()].filter((variable) => !key || variable.key === key), - ), - getEnvironmentVariable: (id) => Effect.sync(() => variables.get(id)!), - createEnvironmentVariable: (props) => - Effect.sync(() => { - const variable: Prisma.Types.EnvironmentVariable = { - id: `var-${props.key}`, - type: 'environment-variable', - url: `https://api.example.test/environment-variables/${props.key}`, - projectId: props.projectId, - branchId: props.branchId ?? null, - class: props.class, - key: props.key, - valueKid: 'test-key', - isManagedBySystem: false, - createdAt: '2026-01-01T00:00:00.000Z', - updatedAt: '2026-01-01T00:00:00.000Z', - }; - variables.set(variable.id, variable); - values.set(variable.key, props.value); - events.push(`write:${variable.key}`); - return variable; - }), - updateEnvironmentVariable: (id, props) => - Effect.gen(function* () { - const variable = variables.get(id)!; - if (variable.key === 'COMPOSER_INPUT') { - events.push('input-update-started'); - yield* Deferred.succeed(updateStarted, undefined); - yield* Deferred.await(releaseUpdate); - if (failUpdate) { - events.push('input-update-failed'); - return yield* Effect.die(new Error('input update failed')); - } - } - const updated = { ...variable, updatedAt: '2026-01-02T00:00:00.000Z' }; - variables.set(id, updated); - values.set(variable.key, props.value); - events.push(`write:${variable.key}`); - return updated; - }), - listAppDeployments: () => Effect.sync(() => [...deployments.values()]), - getDeployment: (id) => Effect.sync(() => deployments.get(id)!), - createAppDeployment: () => - Effect.sync(() => { - const id = `deployment-${++generation}`; - const deployment: Prisma.Types.Deployment = { - id, - type: 'deployment', - url: `https://api.example.test/deployments/${id}`, - foundryVersionId: `version-${generation}`, - status: 'new', - previewDomain: null, - createdAt: '2026-01-01T00:00:00.000Z', - }; - deployments.set(id, deployment); - snapshots.push(Object.fromEntries(values)); - events.push('deployment-snapshot'); - return { ...deployment, uploadUrl: null }; - }), - deleteDeployment: (id) => - Effect.sync(() => { - events.push(`delete:${id}`); - deployments.delete(id); - }), - } satisfies Pick< - Prisma.PrismaManagementClient, - | 'listEnvironmentVariables' - | 'getEnvironmentVariable' - | 'createEnvironmentVariable' - | 'updateEnvironmentVariable' - | 'listAppDeployments' - | 'getDeployment' - | 'createAppDeployment' - | 'deleteDeployment' - >; - - const api = fakeManagementApi(({ method, path, body }) => - Effect.gen(function* () { - const url = new URL(path, 'https://api.prisma.test'); - if (method === 'GET' && url.pathname === '/v1/environment-variables') { - const key = url.searchParams.get('key'); - return page(yield* client.listEnvironmentVariables(key === null ? {} : { key })); - } - if (method === 'POST' && url.pathname === '/v1/environment-variables') { - const variableClass = field(body, 'class'); - if (variableClass !== 'production' && variableClass !== 'preview') { - throw new Error(`Unexpected variable class: ${variableClass}`); - } - return data( - yield* client.createEnvironmentVariable({ - projectId: field(body, 'projectId'), - ...(isRecord(body) && 'branchId' in body - ? { branchId: field(body, 'branchId') } - : {}), - class: variableClass, - key: field(body, 'key'), - value: field(body, 'value'), - }), - ); - } - const variable = url.pathname.match(/^\/v1\/environment-variables\/(.+)$/)?.[1]; - if (variable && method === 'GET') - return data(yield* client.getEnvironmentVariable(variable)); - if (variable && method === 'PATCH') { - return data( - yield* client.updateEnvironmentVariable(variable, { value: field(body, 'value') }), - ); - } - if (method === 'GET' && url.pathname === '/v1/services/app-1/deployments') { - return page(yield* client.listAppDeployments()); - } - if (method === 'POST' && url.pathname === '/v1/services/app-1/deployments') { - return data(yield* client.createAppDeployment()); - } - const deployment = url.pathname.match(/^\/v1\/deployments\/(.+)$/)?.[1]; - if (deployment && method === 'GET') return data(yield* client.getDeployment(deployment)); - if (deployment && method === 'DELETE') { - yield* client.deleteDeployment(deployment); - return new Response(null, { status: 204 }); - } - return Response.json( - { error: { code: 'unhandled', message: `${method} ${path}` } }, - { status: 400 }, - ); - }), - ); - - const providers = Layer.effect( - Prisma.Providers, - Provider.collection([Prisma.EnvironmentVariable, Prisma.Deployment]), - ).pipe( - Layer.provideMerge( - Layer.mergeAll(Prisma.EnvironmentVariableProvider(), Prisma.DeploymentProvider()), - ), - Layer.provideMerge(api), - ); - const options = { providers, dev: false }; - const stack = scratchStack(options, 'deployment-input-order'); - - const program = (inputValue: string, release: number, includeNewVariable: boolean) => - Effect.gen(function* () { - const desired = { - COMPOSER_INPUT: inputValue, - UNCHANGED: 'keep-me', - ...(includeNewVariable ? { NEW_VARIABLE: 'new-value' } : {}), - }; - const environment: Prisma.EnvironmentVariable[] = []; - for (const [key, value] of Object.entries(desired)) { - environment.push( - yield* Prisma.EnvironmentVariable(key, { - project: 'project-1', - class: 'preview', - branchId: 'branch-1', - key, - value: Redacted.make(value), - }), - ); - } - const deployment = yield* Prisma.Deployment('deployment', { - app: appAfter(Output.asOutput('app-1'), environment, []), - skipCodeUpload: true, - start: false, - // Environment values alone must replace the deployment. The drift case - // models a separate replacement reason while the desired input is unchanged. - triggers: { - ...Object.fromEntries( - Object.entries(desired).map(([key, value]) => [key, Redacted.make(value)]), - ), - ...(repairDrift ? { release } : {}), - }, - }); - return { deployment }; - }); - - await runScratch( - Effect.gen(function* () { - yield* stack.deploy(program('{"required":"old"}', 1, false)); - if (repairDrift) values.set('COMPOSER_INPUT', 'out-of-band-drift'); - events.length = 0; - - const plan = yield* stack.plan(program(input, 2, addVariable)); - const deploymentPlan = plan.resources['deployment']!; - expect(deploymentPlan.action).toBe('replace'); - if (deploymentPlan.action !== 'replace') throw new Error('Expected deployment replacement'); - expect(plan.resources['COMPOSER_INPUT']!.action).toBe('update'); - expect(plan.resources['UNCHANGED']!.action).toBe('update'); - if (addVariable) expect(plan.resources['NEW_VARIABLE']!.action).toBe('create'); - - const deploymentFiber = yield* Effect.forkChild( - stack.deploy(program(input, 2, addVariable)), - ); - yield* Deferred.await(updateStarted); - - expect(snapshots).toHaveLength(1); - expect(deployments.has('deployment-1')).toBe(true); - - yield* Deferred.succeed(releaseUpdate, undefined); - const result = yield* Effect.exit(Fiber.join(deploymentFiber)); - - if (failUpdate) { - expect(Exit.isFailure(result)).toBe(true); - expect(events).toContain('input-update-failed'); - expect(snapshots).toHaveLength(1); - expect([...deployments.keys()]).toEqual(['deployment-1']); - expect(events.some((event) => event.startsWith('delete:'))).toBe(false); - return; - } - - expect(Exit.isSuccess(result)).toBe(true); - expect(snapshots).toHaveLength(2); - - expect(snapshots[1]).toEqual({ - COMPOSER_INPUT: input, - UNCHANGED: 'keep-me', - ...(addVariable ? { NEW_VARIABLE: 'new-value' } : {}), - }); - expect(Object.keys(Output.upstreamAny(deploymentPlan.props)).sort()).toEqual( - ['COMPOSER_INPUT', 'UNCHANGED', ...(addVariable ? ['NEW_VARIABLE'] : [])].sort(), - ); - expect(events.indexOf('input-update-started')).toBeLessThan( - events.indexOf('write:COMPOSER_INPUT'), - ); - for (const key of [ - 'COMPOSER_INPUT', - 'UNCHANGED', - ...(addVariable ? ['NEW_VARIABLE'] : []), - ]) { - expect(events).toContain(`write:${key}`); - expect(events.indexOf(`write:${key}`)).toBeLessThan( - events.indexOf('deployment-snapshot'), - ); - } - - yield* stack.deploy(program(input, 2, addVariable)); - expect(snapshots).toHaveLength(2); - }), - ); - }, -); diff --git a/packages/1-prisma-cloud/0-lowering/lowering/src/compute/__tests__/deployment-variables.test.ts b/packages/1-prisma-cloud/0-lowering/lowering/src/compute/__tests__/deployment-variables.test.ts new file mode 100644 index 000000000..10f1ab0ce --- /dev/null +++ b/packages/1-prisma-cloud/0-lowering/lowering/src/compute/__tests__/deployment-variables.test.ts @@ -0,0 +1,168 @@ +// Upstream's `Prisma.Deployment` with its `variables` prop, under the real Alchemy engine against a fake Management API that records every request. +import { expect, test } from 'bun:test'; +import * as Prisma from '@alchemy.run/prisma'; +import * as Provider from 'alchemy/Provider'; +import * as Cause from 'effect/Cause'; +import * as Effect from 'effect/Effect'; +import * as Exit from 'effect/Exit'; +import * as Layer from 'effect/Layer'; +import * as Redacted from 'effect/Redacted'; +import { data, fakeManagementApi, page } from '../../fake-management-api.ts'; +import { runScratch, scratchStack } from '../../scratch-stack.ts'; + +interface Recorded { + readonly method: string; + readonly path: string; + readonly body: unknown; +} + +function fakePlatform(options: { failCreate?: boolean } = {}) { + const requests: Recorded[] = []; + const deployments = new Map>(); + const api = fakeManagementApi(({ method, path, body }) => + Effect.sync(() => { + requests.push({ method, path, body }); + if (method === 'GET' && path.startsWith('/v1/services/app-1/deployments')) { + return page([...deployments.values()]); + } + if (method === 'POST' && path === '/v1/services/app-1/deployments') { + if (options.failCreate === true) { + return Response.json( + { error: { code: 'bad-request', message: 'the platform refused the request' } }, + { status: 400 }, + ); + } + const id = `dep-${deployments.size + 1}`; + const deployment = { + id, + type: 'deployment', + url: `https://api.prisma.test/v1/deployments/${id}`, + serviceId: 'app-1', + foundryVersionId: `fv-${id}`, + status: 'new', + previewDomain: null, + createdAt: '2026-11-20T00:00:00.000Z', + }; + deployments.set(id, deployment); + return data({ ...deployment, uploadUrl: null }); + } + const deployment = deployments.get(path.match(/^\/v1\/deployments\/([^/?]+)/)?.[1] ?? ''); + if (deployment !== undefined && method === 'GET') return data(deployment); + if (deployment !== undefined && method === 'DELETE') { + deployments.delete(String(deployment['id'])); + return new Response(null, { status: 204 }); + } + return Response.json( + { error: { code: 'unhandled', message: `${method} ${path}` } }, + { status: 400 }, + ); + }), + ); + const providers = Layer.effect(Prisma.Providers, Provider.collection([Prisma.Deployment])).pipe( + Layer.provideMerge(Prisma.DeploymentProvider()), + Layer.provideMerge(api), + ); + const creates = () => + requests.filter( + (request) => request.method === 'POST' && request.path === '/v1/services/app-1/deployments', + ); + return { requests, creates, stack: scratchStack({ providers, dev: false }, 'deployment-vars') }; +} + +const program = (variables?: Record | null>) => + Effect.gen(function* () { + yield* Prisma.Deployment('deployment', { + app: 'app-1', + skipCodeUpload: true, + start: false, + ...(variables === undefined ? {} : { variables }), + }); + }); + +const variables = (port: string) => ({ + COMPOSER_SHOP_AUTH_PORT: Redacted.make(port), + COMPOSER_SHOP_AUTH_STREAMS_API_KEY: null, +}); + +test('the create request carries the variables with their values unwrapped and their nulls kept', async () => { + const { creates, stack } = fakePlatform(); + + await runScratch(stack.deploy(program(variables('3000')))); + + expect(creates().map((request) => request.body)).toEqual([ + { + skipCodeUpload: true, + variables: { COMPOSER_SHOP_AUTH_PORT: '3000', COMPOSER_SHOP_AUTH_STREAMS_API_KEY: null }, + }, + ]); +}); + +test('a deployment without variables sends no variables field', async () => { + const { creates, stack } = fakePlatform(); + + await runScratch(stack.deploy(program())); + + expect(creates().map((request) => request.body)).toEqual([{ skipCodeUpload: true }]); +}); + +test('an unchanged redeploy creates no deployment and sends the variables nowhere', async () => { + const { requests, creates, stack } = fakePlatform(); + await runScratch(stack.deploy(program(variables('3000')))); + const before = requests.length; + + await runScratch(stack.deploy(program(variables('3000')))); + + expect(creates()).toHaveLength(1); + expect( + requests.slice(before).filter((request) => JSON.stringify(request.body ?? {}).includes('3000')), + ).toEqual([]); +}); + +test('a changed value creates a new deployment that carries it', async () => { + const { creates, stack } = fakePlatform(); + await runScratch(stack.deploy(program(variables('3000')))); + + await runScratch(stack.deploy(program(variables('8080')))); + + expect(creates().map((request) => request.body)).toEqual([ + { + skipCodeUpload: true, + variables: { COMPOSER_SHOP_AUTH_PORT: '3000', COMPOSER_SHOP_AUTH_STREAMS_API_KEY: null }, + }, + { + skipCodeUpload: true, + variables: { COMPOSER_SHOP_AUTH_PORT: '8080', COMPOSER_SHOP_AUTH_STREAMS_API_KEY: null }, + }, + ]); +}); + +test('declaring variables on a deployment created without them creates a new deployment', async () => { + const { creates, stack } = fakePlatform(); + await runScratch(stack.deploy(program())); + + await runScratch(stack.deploy(program(variables('3000')))); + + expect(creates().map((request) => request.body)).toEqual([ + { skipCodeUpload: true }, + { + skipCodeUpload: true, + variables: { COMPOSER_SHOP_AUTH_PORT: '3000', COMPOSER_SHOP_AUTH_STREAMS_API_KEY: null }, + }, + ]); +}); + +test('a refused create fails without the values in its error', async () => { + const { stack } = fakePlatform({ failCreate: true }); + const secret = 'postgres://user:hunter2@db.example/app'; + + const exit = await runScratch( + Effect.exit(stack.deploy(program({ COMPOSER_SHOP_AUTH_DB_URL: Redacted.make(secret) }))), + ); + + expect(Exit.isFailure(exit)).toBe(true); + if (Exit.isFailure(exit)) { + const text = `${Cause.pretty(exit.cause)} ${JSON.stringify(Cause.squash(exit.cause))}`; + expect(text).toContain('the platform refused the request'); + expect(text).not.toContain('hunter2'); + } +}); diff --git a/packages/1-prisma-cloud/0-lowering/lowering/src/compute/deployment-edge.ts b/packages/1-prisma-cloud/0-lowering/lowering/src/compute/deployment-edge.ts index 9f8b08011..99e3fa2d2 100644 --- a/packages/1-prisma-cloud/0-lowering/lowering/src/compute/deployment-edge.ts +++ b/packages/1-prisma-cloud/0-lowering/lowering/src/compute/deployment-edge.ts @@ -1,24 +1,20 @@ /** - * A deployment's `app` prop, ordered after its environment rows and after the - * producer outputs the caller passes. The edges ride `app` because upstream - * treats an unresolved `app` as unchanged, while an unresolved artifact prop - * would skip the artifact comparison. + * A deployment's `app` prop, ordered after the producer outputs the caller + * passes. The edges ride `app` because upstream treats an unresolved `app` as + * unchanged, while an unresolved artifact prop would skip the artifact + * comparison. */ -import type { EnvironmentVariable } from '@alchemy.run/prisma'; import * as Output from 'alchemy/Output'; export const appAfter = ( app: Output.Output, - environment: readonly EnvironmentVariable[], producerOutputs: readonly Output.Output[], -): Output.Output => { - const waits = [...environment.map((variable) => Output.of(variable)), ...producerOutputs]; - return waits.length === 0 +): Output.Output => + producerOutputs.length === 0 ? app : // The app id is inside the combined expression as well as returned from // it: Alchemy's dependency walker looks only at what an expression is // built FROM, never inside the function, so an app referenced only by // the closure would leave the deployment with no edge to its own app. - Output.flatMap(Output.all(app, ...waits), () => app); -}; + Output.flatMap(Output.all(app, ...producerOutputs), () => app); diff --git a/packages/1-prisma-cloud/0-lowering/lowering/src/providers.ts b/packages/1-prisma-cloud/0-lowering/lowering/src/providers.ts index 5d20524d4..8b363d10d 100644 --- a/packages/1-prisma-cloud/0-lowering/lowering/src/providers.ts +++ b/packages/1-prisma-cloud/0-lowering/lowering/src/providers.ts @@ -46,6 +46,42 @@ const managementApiHttpLayer = (origin: string) => }), ); +type EnvironmentVariableService = Provider.ProviderService; + +// Correct only while hosted deploys declare no rows, so every delete is of a row an older Composer wrote: +// a row whose recorded identity no longer matches would otherwise fail this deploy and every later one. +const droppingMismatchedRows = ( + service: EnvironmentVariableService, +): EnvironmentVariableService => ({ + ...service, + delete: (input) => + service.delete(input).pipe( + Effect.catchIf( + (error) => error._tag === 'EnvironmentVariableConflict', + () => + Effect.logWarning( + `Composer could not delete the variable ${input.output.key} that an older Composer wrote, ` + + "because the platform's record of it no longer matches the deploy state. Composer has " + + 'stopped tracking it. Delete it in Console if it is still listed.', + ), + ), + ), + ...(service.modes === undefined + ? {} + : { + modes: { + live: Effect.map(service.modes.live, droppingMismatchedRows), + local: Effect.map(service.modes.local, droppingMismatchedRows), + }, + }), +}); + +export const providerForDeletingOldVariableRows = () => + Provider.effect( + Prisma.EnvironmentVariable, + Effect.map(Prisma.EnvironmentVariable.Provider, droppingMismatchedRows), + ).pipe(Layer.provide(Prisma.EnvironmentVariableProvider())); + /** * Upstream alchemy's live providers for the postgres family (Project, * Database, Connection), the compute family (App, Deployment, @@ -65,7 +101,7 @@ const upstreamPrismaProviders = (baseUrl: string, clientSupplied: boolean) => Prisma.ConnectionProvider(), Prisma.AppProvider(), Prisma.DeploymentProvider(), - Prisma.EnvironmentVariableProvider(), + providerForDeletingOldVariableRows(), Prisma.BucketProvider(), Prisma.BucketAccessKeyProvider(), Prisma.CustomDomainProvider(), diff --git a/packages/1-prisma-cloud/1-extensions/target/src/__tests__/compute-redeploy-apply.test.ts b/packages/1-prisma-cloud/1-extensions/target/src/__tests__/compute-redeploy-apply.test.ts index 369863e75..388b84576 100644 --- a/packages/1-prisma-cloud/1-extensions/target/src/__tests__/compute-redeploy-apply.test.ts +++ b/packages/1-prisma-cloud/1-extensions/target/src/__tests__/compute-redeploy-apply.test.ts @@ -1,9 +1,11 @@ -// A producer and a consumer that reads its url, deployed twice under the real Alchemy apply engine and the real `Prisma.App`, `Prisma.Deployment` and `Prisma.EnvironmentVariable` providers, against a fake Management API. +// A producer and a consumer that reads its url, deployed under the real Alchemy apply engine and the real `Prisma.App`, `Prisma.Deployment` and `Prisma.EnvironmentVariable` providers, against a fake Management API. import { expect, test } from 'bun:test'; import * as path from 'node:path'; import * as Prisma from '@alchemy.run/prisma'; +import type { Contract } from '@internal/core'; import { dependency, string } from '@internal/core'; import type { LowerContext } from '@internal/core/deploy'; +import { providerForDeletingOldVariableRows } from '@internal/lowering'; import { data, fakeManagementApi, @@ -11,13 +13,25 @@ import { runScratch, scratchStack, } from '@internal/lowering/scratch-stack'; +import { RPC_PEER_KEY } from '@internal/service-rpc'; +import * as Output from 'alchemy/Output'; import * as Provider from 'alchemy/Provider'; import * as Deferred from 'effect/Deferred'; import * as Duration from 'effect/Duration'; import * as Effect from 'effect/Effect'; +import * as Exit from 'effect/Exit'; import * as Layer from 'effect/Layer'; +import * as Logger from 'effect/Logger'; +import * as Redacted from 'effect/Redacted'; import { compute } from '../compute.ts'; -import { computeDescriptor } from '../descriptors/compute.ts'; +import { buildProviderParams } from '../control/extension.ts'; +import { computeDescriptor, endpointDomainOf } from '../descriptors/compute.ts'; +import { GeneratedParamProvider } from '../generated-param-resource.ts'; +import { SELF_ORIGIN } from '../origin-key.ts'; +import { RESERVED_PROVIDER_PARAMS } from '../provider-params.ts'; +import { resourceId } from '../resource-ids.ts'; +import { SentVariableNamesProvider } from '../sent-variable-names-resource.ts'; +import { STREAMS_API_KEY } from '../streams-keys.ts'; const PROJECT_ID = 'proj_1'; const BRANCH_ID = 'br_default'; @@ -27,12 +41,13 @@ interface FakePlatform { readonly services: Map>; readonly deployments: Map>; // A deleted deployment stays listed. - readonly created: unknown[]; + readonly created: { readonly serviceId: unknown; readonly body: Record }[]; readonly variables: Map>; - readonly values: Map; + readonly requests: { readonly method: string; readonly path: string }[]; readonly events: string[]; // While set, the producer's deployment create waits until the consumer's arrives, so a consumer that does not wait for its producer is created first. authCreateWaitsForWeb: Deferred.Deferred | undefined; + failVariableDeletes: boolean; } function record(body: unknown): Record { @@ -101,7 +116,7 @@ function respond(platform: FakePlatform, method: string, url: URL, body: unknown ); } if (method === 'POST' && action === '/deployments') { - platform.created.push(service['id']); + platform.created.push({ serviceId: service['id'], body: sent }); platform.events.push(`create:${service['logicalId']}`); const id = `dep_${platform.created.length}`; const deployment = { @@ -163,16 +178,22 @@ function respond(platform: FakePlatform, method: string, url: URL, body: unknown updatedAt: CREATED_AT, }; platform.variables.set(id, variable); - platform.values.set(String(sent['key']), sent['value']); return data(variable); } - const variable = platform.variables.get( - path.match(/^\/v1\/environment-variables\/([^/]+)$/)?.[1] ?? '', - ); + const variableId = path.match(/^\/v1\/environment-variables\/([^/]+)$/)?.[1] ?? ''; + const variable = platform.variables.get(variableId); + if (variable === undefined && variableId !== '') { + return Response.json({ error: { code: 'not-found', message: 'not found' } }, { status: 404 }); + } if (variable !== undefined && method === 'GET') return data(variable); - if (variable !== undefined && method === 'PATCH') { - platform.values.set(String(variable['key']), sent['value']); - return data(variable); + if (variable !== undefined && method === 'PATCH') return data(variable); + if (variable !== undefined && method === 'DELETE') { + if (platform.failVariableDeletes) { + return Response.json({ error: { code: 'bad-request', message: 'refused' } }, { status: 400 }); + } + platform.events.push(`delete-variable:${variable['key']}`); + platform.variables.delete(variableId); + return new Response(null, { status: 204 }); } return Response.json( @@ -187,13 +208,15 @@ function fakePlatform() { deployments: new Map(), created: [], variables: new Map(), - values: new Map(), + requests: [], events: [], authCreateWaitsForWeb: undefined, + failVariableDeletes: false, }; const api = fakeManagementApi(({ method, path, body }) => Effect.gen(function* () { const url = new URL(path, 'https://api.prisma.test'); + platform.requests.push({ method, path: url.pathname }); const creating = method === 'POST' ? url.pathname.match(/^\/v1\/services\/([^/]+)\/deployments$/) : null; const address = platform.services.get(creating?.[1] ?? '')?.['logicalId']; @@ -215,18 +238,27 @@ function fakePlatform() { Layer.mergeAll( Prisma.AppProvider(), Prisma.DeploymentProvider(), - Prisma.EnvironmentVariableProvider(), + providerForDeletingOldVariableRows(), + SentVariableNamesProvider(), + GeneratedParamProvider(), ), ), Layer.provideMerge(api), ); - const createdFor = (address: string) => { - const service = [...platform.services.values()].find((s) => s['logicalId'] === address); - return platform.created.filter((serviceId) => serviceId === service?.['id']); - }; + const serviceIdOf = (address: string) => + [...platform.services.values()].find((s) => s['logicalId'] === address)?.['id']; + const createsFor = (address: string) => + platform.created.filter(({ serviceId }) => serviceId === serviceIdOf(address)); + const variableWrites = () => + platform.requests.filter( + ({ method, path }) => + (method === 'POST' || method === 'PATCH') && path.startsWith('/v1/environment-variables'), + ); return { platform, - createdFor, + createsFor, + variablesSentTo: (address: string) => createsFor(address).map(({ body }) => body['variables']), + variableWrites, stack: scratchStack({ providers, dev: false }, 'compute-redeploy'), }; } @@ -237,24 +269,76 @@ const build = { module: 'file:///test/service.ts', entry: 'server.js', }; -const auth = compute({ name: 'auth', deps: {}, build }); -const web = compute({ - name: 'web', - deps: { - auth: dependency({ - type: 'rpc', - connection: { params: { url: string() }, hydrate: (v) => v }, - }), - }, - build, -}); +const exposed: Contract<'rpc', Record> = { + kind: 'rpc', + __cmp: {}, + satisfies: () => true, +}; +const urlDependency = () => + dependency({ + type: 'rpc', + connection: { params: { url: string() }, hydrate: (v) => v }, + }); +// `region` is never given a value here. +const authDependency = () => + dependency({ + type: 'rpc', + connection: { + params: { url: string(), region: string({ optional: true }) }, + hydrate: (v) => v, + }, + }); + +interface Shape { + /** The consumer also depends on a billing service outside this deploy. */ + readonly billing?: boolean; + /** The producer serves streams to at least one consumer. */ + readonly streamsConsumer?: boolean; + /** How many extra dependencies the consumer reads a url from. */ + readonly extraDependencies?: number; +} -const descriptor = computeDescriptor(() => ({ workspaceId: 'ws_1', providerParams: new Map() })); -const graph = { +const auth = compute({ name: 'auth', deps: {}, build, expose: { verify: exposed } }); +const webOf = (shape: Shape) => + compute({ + name: 'web', + deps: { + auth: authDependency(), + ...(shape.billing === true ? { billing: urlDependency() } : {}), + ...Object.fromEntries( + Array.from({ length: shape.extraDependencies ?? 0 }, (_, i) => [ + `extra${i}`, + urlDependency(), + ]), + ), + }, + build, + }); + +const descriptorOf = (shape: Shape) => + computeDescriptor(() => ({ + workspaceId: 'ws_1', + providerParams: buildProviderParams( + RESERVED_PROVIDER_PARAMS, + new Map([ + [RPC_PEER_KEY, { value: () => [] }], + [ + STREAMS_API_KEY, + { value: () => (shape.streamsConsumer === true ? 'minted-streams-key' : undefined) }, + ], + [SELF_ORIGIN, { valueForService: endpointDomainOf }], + ]), + ), + })); +const graphOf = (web: unknown) => ({ root: { id: 'shop' }, + nodes: [ + { id: 'shop.auth', node: auth }, + { id: 'shop.web', node: web }, + ], inputBindings: [], edges: [{ from: 'shop.auth', to: 'shop.web', input: 'auth', kind: 'dependency' }], -}; +}); const application = { projectId: PROJECT_ID, branchId: undefined, @@ -265,11 +349,22 @@ const application = { const artifact = { path: import.meta.path, sha256: 'sha-artifact' }; const changedArtifact = { path: path.join(import.meta.dir, '..', 'compute.ts'), sha256: 'sha-2' }; -function program(authArtifact = artifact, webArtifact = artifact) { +function program(shape: Shape = {}, authArtifact = artifact, webArtifact = artifact) { return Effect.gen(function* () { + const descriptor = descriptorOf(shape); + const web = webOf(shape); const lowered = new Map>>(); + const graph = graphOf(web); const ctxOf = (address: string, node: unknown) => - ({ id: address, address, node, graph, application, lowered }) as unknown as LowerContext; + ({ + id: address, + address, + node, + graph, + application, + lowered, + provisioned: new Map(), + }) as unknown as LowerContext; const authCtx = ctxOf('shop.auth', auth); const webCtx = ctxOf('shop.web', web); const authProvisioned = yield* descriptor.provision(authCtx); @@ -287,33 +382,118 @@ function program(authArtifact = artifact, webArtifact = artifact) { lowered.set('shop.auth', deployed.outputs); const webSerialized = yield* descriptor.serialize(webCtx, webProvisioned, { service: { port: 3000 }, - inputs: { auth: { url: deployed.outputs['url'] } }, + inputs: { + auth: { url: deployed.outputs['url'] }, + ...(shape.billing === true ? { billing: { url: 'https://billing.example' } } : {}), + ...Object.fromEntries( + Array.from({ length: shape.extraDependencies ?? 0 }, (_, i) => [ + `extra${i}`, + { url: `https://extra${i}.example` }, + ]), + ), + }, }); yield* descriptor.deploy(webCtx, webProvisioned, webArtifact, webSerialized); }) as Effect.Effect; } -test("an unchanged deploy keeps the deployment of a consumer of the producer's url", async () => { - const { platform, createdFor, stack } = fakePlatform(); +const authVariables = (streamsKey: string | null = null) => ({ + COMPOSER_SHOP_AUTH_PORT: '3000', + COMPOSER_SHOP_AUTH_RPC_ACCEPTED_KEYS: '[]', + COMPOSER_SHOP_AUTH_STREAMS_API_KEY: streamsKey, + COMPOSER_SHOP_AUTH_ORIGIN: '"https://svc_1.cdg.prisma.build"', +}); +const webVariables = { + COMPOSER_SHOP_WEB_AUTH_URL: 'https://svc_1.cdg.prisma.build', + COMPOSER_SHOP_WEB_AUTH_REGION: null, + COMPOSER_SHOP_WEB_PORT: '3000', + COMPOSER_SHOP_WEB_RPC_ACCEPTED_KEYS: null, + COMPOSER_SHOP_WEB_STREAMS_API_KEY: null, + COMPOSER_SHOP_WEB_ORIGIN: '"https://svc_2.cdg.prisma.build"', +}; + +test('a deployment is created with every key its service reads at boot, a missing value as null', async () => { + const { variablesSentTo, stack } = fakePlatform(); await runScratch(stack.deploy(program())); - expect(createdFor('shop.auth')).toHaveLength(1); - expect(createdFor('shop.web')).toHaveLength(1); - expect(platform.values.get('COMPOSER_SHOP_WEB_AUTH_URL')).toBe('https://svc_1.cdg.prisma.build'); + + expect(variablesSentTo('shop.auth')).toEqual([authVariables()]); + expect(variablesSentTo('shop.web')).toEqual([webVariables]); +}); + +test("an unchanged deploy keeps the deployment of a consumer of the producer's url", async () => { + const { createsFor, platform, stack } = fakePlatform(); await runScratch(stack.deploy(program())); - expect(createdFor('shop.auth')).toHaveLength(1); - expect(createdFor('shop.web')).toHaveLength(1); + const replaced = platform.events.length; + await runScratch(stack.deploy(program())); + + expect(createsFor('shop.auth')).toHaveLength(1); + expect(createsFor('shop.web')).toHaveLength(1); + expect(platform.events.slice(replaced).filter((event) => event.startsWith('create:'))).toEqual( + [], + ); +}); + +test('no platform deploy writes a variable row', async () => { + const { variableWrites, stack } = fakePlatform(); + + await runScratch(stack.deploy(program({ billing: true, streamsConsumer: true }))); + await runScratch(stack.deploy(program({}, changedArtifact, changedArtifact))); + + expect(variableWrites()).toEqual([]); }); test("a new artifact for the producer replaces its deployment and keeps the consumer's", async () => { - const { createdFor, stack } = fakePlatform(); + const { createsFor, stack } = fakePlatform(); + + await runScratch(stack.deploy(program())); + await runScratch(stack.deploy(program({}, changedArtifact))); + + expect(createsFor('shop.auth')).toHaveLength(2); + expect(createsFor('shop.web')).toHaveLength(1); +}); +test('a changed value replaces only the service that reads it, and its new deployment carries it', async () => { + const { createsFor, variablesSentTo, stack } = fakePlatform(); + + await runScratch(stack.deploy(program({ streamsConsumer: true }))); + await runScratch(stack.deploy(program({ streamsConsumer: true, billing: true }))); + + expect(createsFor('shop.auth')).toHaveLength(1); + expect(variablesSentTo('shop.web')).toEqual([ + webVariables, + { ...webVariables, COMPOSER_SHOP_WEB_BILLING_URL: 'https://billing.example' }, + ]); +}); + +test("a removed dependency's keys are sent as null on that deploy and on every later one, and an unchanged deploy after it replaces nothing", async () => { + const { createsFor, variablesSentTo, stack } = fakePlatform(); + + await runScratch(stack.deploy(program({ billing: true }))); + await runScratch(stack.deploy(program())); await runScratch(stack.deploy(program())); - await runScratch(stack.deploy(program(changedArtifact))); + expect(createsFor('shop.web')).toHaveLength(2); + await runScratch(stack.deploy(program({}, artifact, changedArtifact))); - expect(createdFor('shop.auth')).toHaveLength(2); - expect(createdFor('shop.web')).toHaveLength(1); + const noLongerSent = { ...webVariables, COMPOSER_SHOP_WEB_BILLING_URL: null }; + expect(variablesSentTo('shop.web')).toEqual([ + { ...webVariables, COMPOSER_SHOP_WEB_BILLING_URL: 'https://billing.example' }, + noLongerSent, + noLongerSent, + ]); +}); + +test('a streams service that loses its last consumer is deployed with STREAMS_API_KEY null', async () => { + const { variablesSentTo, stack } = fakePlatform(); + + await runScratch(stack.deploy(program({ streamsConsumer: true }))); + await runScratch(stack.deploy(program())); + + expect(variablesSentTo('shop.auth')).toEqual([ + authVariables('"minted-streams-key"'), + authVariables(), + ]); }); test("on a first deploy, the producer is promoted before the consumer's deployment is created", async () => { @@ -328,15 +508,170 @@ test("on a first deploy, the producer is promoted before the consumer's deployme }); test("when both artifacts change, the producer is promoted before the consumer's new deployment is created", async () => { - const { platform, createdFor, stack } = fakePlatform(); + const { platform, createsFor, stack } = fakePlatform(); await runScratch(stack.deploy(program())); platform.events.length = 0; platform.authCreateWaitsForWeb = Deferred.makeUnsafe(); - await runScratch(stack.deploy(program(changedArtifact, changedArtifact))); + await runScratch(stack.deploy(program({}, changedArtifact, changedArtifact))); - expect(createdFor('shop.web')).toHaveLength(2); + expect(createsFor('shop.web')).toHaveLength(2); expect( platform.events.filter((event) => event === 'promote:shop.auth' || event === 'create:shop.web'), ).toEqual(['promote:shop.auth', 'create:shop.web']); }); + +test('a service with more than 50 variables is refused before any request', async () => { + const { platform, stack } = fakePlatform(); + + const exit = await runScratch(Effect.exit(stack.deploy(program({ extraDependencies: 48 })))); + + expect(Exit.isFailure(exit)).toBe(true); + expect(String(Exit.isFailure(exit) ? exit.cause : '')).toContain( + 'The service "shop.web" needs 51 variables, but Prisma Cloud stores at most 50 on one service', + ); + expect(platform.requests).toEqual([]); +}); + +// What the release before this one declared for each service: one variable row per key and a deployment whose triggers repeat the row values. +function previousReleaseProgram(options: { readonly triggersRepeatValues: boolean }) { + return Effect.gen(function* () { + const descriptor = descriptorOf({}); + const lowered = new Map>>(); + const graph = graphOf(webOf({})); + for (const [address, node, values] of [ + ['shop.auth', auth, authVariables()], + ['shop.web', webOf({}), webVariables], + ] as const) { + const ctx = { + id: address, + address, + node, + graph, + application, + lowered, + provisioned: new Map(), + } as unknown as LowerContext; + const provisioned = yield* descriptor.provision(ctx); + const rows: Prisma.EnvironmentVariable[] = []; + const triggers: Record> = {}; + for (const [key, value] of Object.entries(values)) { + if (value === null) continue; + rows.push( + yield* Prisma.EnvironmentVariable(resourceId(address, 'env', key), { + project: PROJECT_ID, + key, + value: Redacted.make(value), + class: 'production', + }), + ); + triggers[key] = Redacted.make(value); + } + yield* Prisma.Deployment(resourceId(address, 'deployment'), { + app: Output.flatMap( + Output.all(provisioned.serviceId, ...rows.map((row) => Output.of(row))), + () => provisioned.serviceId, + ), + artifactPath: artifact.path, + artifactContentType: 'application/gzip', + triggers: options.triggersRepeatValues ? triggers : {}, + portMapping: { http: 3000 }, + start: true, + promote: true, + }); + } + }) as Effect.Effect; +} + +const rowKeys = () => + [...Object.entries(authVariables()), ...Object.entries(webVariables)] + .filter(([, value]) => value !== null) + .map(([key]) => key) + .sort(); + +test.each([{ triggersRepeatValues: true }, { triggersRepeatValues: false }])( + 'the upgrade from rows replaces each deployment once, with every value, then deletes the rows (triggers repeat values: $triggersRepeatValues)', + async ({ triggersRepeatValues }) => { + const { platform, createsFor, variablesSentTo, variableWrites, stack } = fakePlatform(); + await runScratch(stack.deploy(previousReleaseProgram({ triggersRepeatValues }))); + expect([...platform.variables.values()].map((v) => v['key']).sort()).toEqual(rowKeys()); + const writesBefore = variableWrites().length; + platform.events.length = 0; + + await runScratch(stack.deploy(program())); + + expect(createsFor('shop.auth')).toHaveLength(2); + expect(createsFor('shop.web')).toHaveLength(2); + expect(variablesSentTo('shop.auth').at(-1)).toEqual(authVariables()); + expect(variablesSentTo('shop.web').at(-1)).toEqual(webVariables); + expect(variableWrites()).toHaveLength(writesBefore); + expect(platform.variables.size).toBe(0); + for (const key of rowKeys()) { + const owner = key.startsWith('COMPOSER_SHOP_AUTH_') ? 'shop.auth' : 'shop.web'; + expect(platform.events.indexOf(`delete-variable:${key}`)).toBeGreaterThan( + platform.events.indexOf(`create:${owner}`), + ); + } + + await runScratch(stack.deploy(program())); + expect(createsFor('shop.auth')).toHaveLength(2); + expect(createsFor('shop.web')).toHaveLength(2); + }, +); + +test('an upgrade interrupted after the replacements finishes on the next deploy without replacing again', async () => { + const { platform, createsFor, stack } = fakePlatform(); + await runScratch(stack.deploy(previousReleaseProgram({ triggersRepeatValues: true }))); + platform.failVariableDeletes = true; + + const interrupted = await runScratch(Effect.exit(stack.deploy(program()))); + expect(Exit.isFailure(interrupted)).toBe(true); + expect(createsFor('shop.auth')).toHaveLength(2); + expect(platform.variables.size).toBe(rowKeys().length); + + platform.failVariableDeletes = false; + await runScratch(stack.deploy(program())); + + expect(createsFor('shop.auth')).toHaveLength(2); + expect(createsFor('shop.web')).toHaveLength(2); + expect(platform.variables.size).toBe(0); +}); + +test('a row already deleted on the platform does not fail the upgrade', async () => { + const { platform, stack } = fakePlatform(); + await runScratch(stack.deploy(previousReleaseProgram({ triggersRepeatValues: true }))); + const [goneId] = [...platform.variables.entries()].find( + ([, v]) => v['key'] === 'COMPOSER_SHOP_WEB_PORT', + ) ?? ['']; + platform.variables.delete(goneId); + + await runScratch(stack.deploy(program())); + + expect(platform.variables.size).toBe(0); +}); + +test('a row whose platform record no longer matches deploy state is dropped with a warning naming its key', async () => { + const { platform, stack } = fakePlatform(); + await runScratch(stack.deploy(previousReleaseProgram({ triggersRepeatValues: true }))); + const mismatched = [...platform.variables.values()].find( + (v) => v['key'] === 'COMPOSER_SHOP_WEB_PORT', + ); + if (mismatched === undefined) throw new Error('fixture: no COMPOSER_SHOP_WEB_PORT row'); + mismatched['branchId'] = 'br_other'; + const warnings: string[] = []; + const capture = Logger.make(({ logLevel, message }) => { + if (logLevel === 'Warn') warnings.push(JSON.stringify(message)); + }); + + await runScratch(stack.deploy(program()).pipe(Effect.provide(Logger.layer([capture])))); + const requestsBefore = platform.requests.length; + await runScratch(stack.deploy(program())); + + expect(warnings.filter((warning) => warning.includes('COMPOSER_SHOP_WEB_PORT'))).toHaveLength(1); + expect([...platform.variables.values()].map((v) => v['key'])).toEqual(['COMPOSER_SHOP_WEB_PORT']); + expect( + platform.requests + .slice(requestsBefore) + .filter(({ path }) => path.startsWith('/v1/environment-variables')), + ).toEqual([]); +}); diff --git a/packages/1-prisma-cloud/1-extensions/target/src/__tests__/control-lowering.test.ts b/packages/1-prisma-cloud/1-extensions/target/src/__tests__/control-lowering.test.ts index c4ccb57b1..fe47a8e1f 100644 --- a/packages/1-prisma-cloud/1-extensions/target/src/__tests__/control-lowering.test.ts +++ b/packages/1-prisma-cloud/1-extensions/target/src/__tests__/control-lowering.test.ts @@ -16,6 +16,7 @@ import type { DeploymentResult, LowerContext, LoweredResult, Outputs } from '@in // mode regardless of the (filesystem-dependent) test-file order. import * as RealDevEmulators from '@internal/dev-emulators'; import { field, secretString } from '@internal/foundation/arktype'; +import { CliStructuredError } from '@internal/foundation/errors'; import * as RealLocalTarget from '@internal/local-target'; import * as RealPrismaAlchemy from '@internal/lowering'; import * as Alchemy from 'alchemy'; @@ -43,6 +44,7 @@ import * as RealGeneratedParam from '../generated-param-resource.ts'; import * as RealOrmMigration from '../orm-migration-resource.ts'; import * as RealPgWarm from '../pg-warm-resource.ts'; import * as RealS3Credentials from '../s3-credentials-resource.ts'; +import * as RealSentVariableNames from '../sent-variable-names-resource.ts'; import { scopedFakes } from './scoped-fakes.ts'; // Stub the provider layer AND alchemy/Output so the compute target's data @@ -65,6 +67,7 @@ const recorded: { bucketKey: Array<[string, unknown]>; customDomain: Array<[string, unknown]>; generated: Array<[string, unknown]>; + sentVariableNames: Array<[string, unknown]>; pnMigrate: Array<[string, unknown]>; adoptPolicy: Array<[string, boolean | undefined]>; renamePolicy: Array<[string, readonly FormerId[] | undefined]>; @@ -83,6 +86,7 @@ const recorded: { bucketKey: [], customDomain: [], generated: [], + sentVariableNames: [], pnMigrate: [], adoptPolicy: [], renamePolicy: [], @@ -235,9 +239,9 @@ mock.module('@internal/lowering', () => ({ })); /** The trigger members with their Redacted wrappers unwrapped, so assertions can name the plain values. Under the Output mocks every member is already a resolved Redacted value. */ -const unwrapTriggers = (triggers: Readonly>): Record => +const unwrapRedacted = (values: Readonly>): Record => Object.fromEntries( - Object.entries(triggers).map(([key, value]) => [ + Object.entries(values).map(([key, value]) => [ key, Redacted.isRedacted(value) ? Redacted.value(value) : value, ]), @@ -285,6 +289,16 @@ mock.module('../generated-param-resource.ts', () => ({ GeneratedParamProvider: () => ({ stub: 'generated-param-provider' }), })); +// A first deploy: the record has seen no key before this one. +mock.module('../sent-variable-names-resource.ts', () => ({ + ...RealSentVariableNames, + SentVariableNames: (id: string, props: { names: readonly string[] }) => { + recorded.sentVariableNames.push([id, props]); + return Effect.succeed({ names: props.names }); + }, + SentVariableNamesProvider: () => ({ stub: 'sent-variable-names-provider' }), +})); + // A real Alchemy Resource (needs the Stack service); stubbed so the lowering runs purely. mock.module('../orm-migration-resource.ts', () => ({ ...RealOrmMigration, @@ -355,8 +369,7 @@ const runAsync = (eff: Effect.Effect): Promise // // The real types describe the real world: `ComputeProvisioned.serviceId` is an // `Output` (a lazy reference that only resolves when Alchemy applies -// the stack), and `ComputeSerialized.environment` holds real -// `EnvironmentVariable` resources. The mocks at the top of this file collapse +// the stack). The mocks at the top of this file collapse // that laziness on purpose — `Output.map` applies its function directly, and // each mock resource returns a plain object — so the hooks hand back resolved // values here and nothing else. @@ -373,16 +386,24 @@ const runAsync = (eff: Effect.Effect): Promise /** The mocks collapse Output to T; nothing else about the real types changes. */ type Resolved = T extends RealOutput.Output ? U : T; type Mirror = { readonly [K in keyof T]: Resolved }; -/** The mock EnvironmentVariable, standing in for the real resource. */ -type MockedEnvironment = ReadonlyArray<{ environmentVariableId: string; key: string }>; - type MockedProvisioned = Mirror; -type MockedSerialized = Omit, 'environment'> & { - readonly environment: MockedEnvironment; -}; -type MockedS3StoreSerialized = Omit, 'environment'> & { - readonly environment: MockedEnvironment; -}; +type MockedSerialized = Mirror; +type MockedS3StoreSerialized = Mirror; + +/** Every variable the deployments declared since `before` are created with, values unwrapped, a deleted key as null. */ +const sentSince = (before: number): Record => + Object.assign({}, ...Object.values(variablesSentSince(before))); + +/** The `variables` of every deployment declared since `before`, values unwrapped, keyed by deployment id. */ +const variablesSentSince = (before: number): Record> => + Object.fromEntries( + recorded.deploy + .slice(before) + .map(([id, props]) => [ + id, + unwrapRedacted((props as { variables: Record }).variables), + ]), + ); /** Sets env vars for the duration of `fn`, restoring whatever was there before. */ async function withEnv(values: Record, fn: () => T): Promise { @@ -955,7 +976,7 @@ describe("prismaCloud().nodes['compute'] — the service descriptor", () => { ]); }); - test('serialize writes one env var per Config leaf, keyed by configKey(address, decl)', async () => { + test('serialize sends one variable per Config leaf and reserved param, keyed by configKey(address, decl)', async () => { const target = prismaCloud({ workspaceId: 'ws_1' }); const node = compute({ name: 'test-service', @@ -992,66 +1013,30 @@ describe("prismaCloud().nodes['compute'] — the service descriptor", () => { serviceDescriptorOf(target, 'compute').serialize(ctx, provisioned, config), ); - expect(recorded.envVar.slice(-3)).toEqual([ - [ - 'shop.auth.env.COMPOSER_SHOP_AUTH_DB_URL', - { - project: 'shop-project#cloud-id', - key: 'COMPOSER_SHOP_AUTH_DB_URL', - value: 'postgres://real-db', - class: 'production', - }, - ], - // The concrete numeric leaf is encoded typed→string ("3000", not 3000): - // the ConfigVariable value field is string-typed, and deserialize reads - // it back to a number (round-tripped in pack.test.ts). - [ - 'shop.auth.env.COMPOSER_SHOP_AUTH_PORT', - { - project: 'shop-project#cloud-id', - key: 'COMPOSER_SHOP_AUTH_PORT', - value: '3000', - class: 'production', - }, - ], - // The framework-resolved origin row — one per compute service, - // unconditional, the provisioned service's own endpoint domain. - [ - 'shop.auth.env.COMPOSER_SHOP_AUTH_ORIGIN', - { - project: 'shop-project#cloud-id', - key: 'COMPOSER_SHOP_AUTH_ORIGIN', - value: '"https://auth-svc.example"', - class: 'production', - }, - ], - ]); - expect(result.environment).toEqual([ - { - environmentVariableId: 'shop.auth.env.COMPOSER_SHOP_AUTH_DB_URL#cloud-id', - key: 'COMPOSER_SHOP_AUTH_DB_URL', - }, - { - environmentVariableId: 'shop.auth.env.COMPOSER_SHOP_AUTH_PORT#cloud-id', - key: 'COMPOSER_SHOP_AUTH_PORT', - }, - { - environmentVariableId: 'shop.auth.env.COMPOSER_SHOP_AUTH_ORIGIN#cloud-id', - key: 'COMPOSER_SHOP_AUTH_ORIGIN', - }, - ]); - expect(unwrapTriggers(result.triggers)).toEqual({ + const expected = { COMPOSER_SHOP_AUTH_DB_URL: 'postgres://real-db', + // The concrete numeric leaf is encoded typed→string ("3000", not 3000); + // deserialize reads it back to a number (round-tripped in pack.test.ts). COMPOSER_SHOP_AUTH_PORT: '3000', + // A reserved param the service has no value for is sent as null, so a value an earlier deploy stored is deleted. + COMPOSER_SHOP_AUTH_RPC_ACCEPTED_KEYS: null, + COMPOSER_SHOP_AUTH_STREAMS_API_KEY: null, COMPOSER_SHOP_AUTH_ORIGIN: '"https://auth-svc.example"', - }); + }; + expect(unwrapRedacted(result.bootVariables)).toEqual(expected); + expect(recorded.sentVariableNames.at(-1)).toEqual([ + 'shop.auth.sent-variable-names', + { names: Object.keys(expected).sort() }, + ]); + expect(unwrapRedacted(result.requestVariables)).toEqual(expected); + expect(recorded.envVar.filter(([id]) => id.startsWith('shop.auth.'))).toEqual([]); expect(result.platformVariables).toEqual([]); // serialize also surfaces the resolved listen port for deploy() — the // Deployment must route to whatever the app binds, not a constant. expect(result.port).toBe(3000); }); - test('every env-var value reaches the platform as a Redacted value, never a bare string', async () => { + test('every variable value reaches the platform as a Redacted value, never a bare string', async () => { const target = prismaCloud({ workspaceId: 'ws_1' }); const node = compute({ name: 'test-service', @@ -1082,23 +1067,20 @@ describe("prismaCloud().nodes['compute'] — the service descriptor", () => { projectId: 'shop-project#cloud-id', endpointDomain: 'https://auth-svc.example', }; - const before = recorded.envVarProps.length; - - run( + const result = run( serviceDescriptorOf(target, 'compute').serialize(ctx, provisioned, { service: { port: 3000 }, inputs: { db: { url: 'postgres://real-db' } }, }), ); - const written = recorded.envVarProps.slice(before); - expect(written.length).toBeGreaterThan(0); - // A bare string here would put the value in Alchemy's state file in - // plain text — the wrapper is what keeps it out. - expect(written.every(([, props]) => Redacted.isRedacted(props.value))).toBe(true); + const values = Object.values(result.requestVariables).filter((value) => value !== null); + expect(values.length).toBeGreaterThan(0); + // Redacted keeps a value out of logs and error text. + expect(values.every((value) => Redacted.isRedacted(value))).toBe(true); }); - test('an optional connection param with no provisioned value writes NO env-var row; a provided one still does', async () => { + test('an optional connection param with no provisioned value is sent as null; a provided one is sent', async () => { const target = prismaCloud({ workspaceId: 'ws_1' }); // A dependency shaped like rpc()'s post-slice-1 connection: a required // url plus an optional serviceKey the deploy has not provisioned yet. @@ -1141,23 +1123,13 @@ describe("prismaCloud().nodes['compute'] — the service descriptor", () => { service: { port: 3000 }, inputs: { auth: { url: 'http://auth.internal', serviceKey: undefined } }, }; - const before = recorded.envVar.length; - - run( + const result = run( serviceDescriptorOf(target, 'compute').serialize(ctx, provisioned, config), ); - const writes = recorded.envVar.slice(before).map(([, props]) => props); - // The provided url still writes its row... - expect(writes).toContainEqual({ - project: 'shop-project#cloud-id', - key: 'COMPOSER_SHOP_CONSUMER_AUTH_URL', - value: 'http://auth.internal', - class: 'production', - }); - // ...but the unprovisioned serviceKey writes none — no "value: Required" at deploy. - const writtenKeys = writes.map((p) => (p as { key: string }).key); - expect(writtenKeys).not.toContain('COMPOSER_SHOP_CONSUMER_AUTH_SERVICEKEY'); + const sent = unwrapRedacted(result.bootVariables); + expect(sent['COMPOSER_SHOP_CONSUMER_AUTH_URL']).toBe('http://auth.internal'); + expect(sent['COMPOSER_SHOP_CONSUMER_AUTH_SERVICEKEY']).toBeNull(); }); test("a service's input is one artifact row that names its secrets and holds none of their values, and no variable", async () => { @@ -1206,23 +1178,16 @@ describe("prismaCloud().nodes['compute'] — the service descriptor", () => { endpointDomain: 'https://svc.example', }; const config = { service: { port: 3000 }, inputs: {} }; - const before = recorded.envVar.length; - const result = run( serviceDescriptorOf(target, 'compute').serialize(ctx, provisioned, config), ); - const writes = recorded.envVar.slice(before).map(([, props]) => props); - expect(writes.map((props) => (props as { key: string }).key)).not.toContain( - 'COMPOSER_SHOP_INGEST_INPUT', - ); - expect(unwrapTriggers(result.triggers)).not.toHaveProperty('COMPOSER_SHOP_INGEST_INPUT'); + const sent = unwrapRedacted(result.bootVariables); + expect(sent).not.toHaveProperty('COMPOSER_SHOP_INGEST_INPUT'); // The platform variable the document names joins the triggers by its // rotation timestamp. expect(result.platformVariables).toEqual(['STRIPE_SECRET_KEY']); - // No serialized EnvironmentVariable output carries the secret's value. - expect(JSON.stringify(writes)).not.toContain('sk_live'); - expect(JSON.stringify(unwrapTriggers(result.triggers))).not.toContain('sk_live'); + expect(JSON.stringify(sent)).not.toContain('sk_live'); // One self-describing document, which package writes into the artifact // and deploy() puts on the report entity; the secret leaf is a $platform // marker naming the platform variable, never a value. @@ -1238,7 +1203,7 @@ describe("prismaCloud().nodes['compute'] — the service descriptor", () => { ); }); - test('serialize provisions a GeneratedParam resource + an env row per generated leaf (ADR-0041)', async () => { + test('serialize provisions a GeneratedParam resource and sends a variable per generated leaf (ADR-0041)', async () => { const target = prismaCloud({ workspaceId: 'ws_1' }); const node = compute({ name: 'ingest', @@ -1276,7 +1241,6 @@ describe("prismaCloud().nodes['compute'] — the service descriptor", () => { }; const config = { service: { port: 3000 }, inputs: {} }; const beforeGen = recorded.generated.length; - const beforeEnv = recorded.envVar.length; const result = run( serviceDescriptorOf(target, 'compute').serialize(ctx, provisioned, config), @@ -1286,15 +1250,11 @@ describe("prismaCloud().nodes['compute'] — the service descriptor", () => { expect(recorded.generated.slice(beforeGen)).toEqual([ ['shop.ingest.generated.secret', { bytes: 48 }], ]); - // The env row carries the resource's value under the framework var the + // The variable carries the resource's value under the key the // document's $generated pointer names. - const writes = recorded.envVar.slice(beforeEnv).map(([, props]) => props); - expect(writes).toContainEqual({ - project: 'shop-project#cloud-id', - key: 'COMPOSER_SHOP_INGEST_SECRET_GENERATED', - value: 'generated-for-shop.ingest.generated.secret', - class: 'production', - }); + expect(unwrapRedacted(result.bootVariables)['COMPOSER_SHOP_INGEST_SECRET_GENERATED']).toBe( + 'generated-for-shop.ingest.generated.secret', + ); // The input document is a $generated pointer, never a value; the leaf also // rides the serialize → deploy handoff. expect(result.input?.value).toBe( @@ -1308,14 +1268,6 @@ describe("prismaCloud().nodes['compute'] — the service descriptor", () => { path: 'secret', }, ]); - // The generated row's trigger member carries the mint-once-stable value - // (Redacted): it holds still across redeploys and moves exactly when - // the value is re-generated. It is NOT joined by a platform `updatedAt` - // either — Composer rewrites this row every deploy, so that timestamp - // would move every deploy and the fingerprint would never settle. - expect(unwrapTriggers(result.triggers)['COMPOSER_SHOP_INGEST_SECRET_GENERATED']).toBe( - 'generated-for-shop.ingest.generated.secret', - ); expect(result.platformVariables).toEqual([]); }); @@ -1366,7 +1318,6 @@ describe("prismaCloud().nodes['compute'] — the service descriptor", () => { endpointDomain: 'https://login.example', }; const beforeGen = recorded.generated.length; - const beforeEnv = recorded.envVar.length; const result = run( serviceDescriptorOf(target, 'compute').serialize(ctx, provisioned, { @@ -1376,19 +1327,12 @@ describe("prismaCloud().nodes['compute'] — the service descriptor", () => { ); expect(recorded.generated.slice(beforeGen)).toEqual([]); - expect(recorded.envVar.slice(beforeEnv).map(([, props]) => props)).toContainEqual({ - project: 'shop-project#cloud-id', - key: 'COMPOSER_SHOP_LOGIN_BASEURL_GENERATED', - value: 'https://web-preview.example', - class: 'preview', - branchId: 'br_preview', - }); + expect(unwrapRedacted(result.bootVariables)['COMPOSER_SHOP_LOGIN_BASEURL_GENERATED']).toBe( + 'https://web-preview.example', + ); expect(result.input?.value).toBe( '{"baseUrl":{"$generated":"COMPOSER_SHOP_LOGIN_BASEURL_GENERATED","redacted":false}}', ); - expect(unwrapTriggers(result.triggers)['COMPOSER_SHOP_LOGIN_BASEURL_GENERATED']).toBe( - 'https://web-preview.example', - ); }); test('serialize fails loudly for serviceOrigin() naming no compute service', async () => { @@ -1439,7 +1383,7 @@ describe("prismaCloud().nodes['compute'] — the service descriptor", () => { ); }); - test('a literal-bound reserved param still serializes as a plain JSON-encoded value row (unchanged)', async () => { + test('a literal-bound reserved param still serializes as a plain JSON-encoded value', async () => { const target = prismaCloud({ workspaceId: 'ws_1' }); const node = compute({ name: 'web', @@ -1472,22 +1416,14 @@ describe("prismaCloud().nodes['compute'] — the service descriptor", () => { service: { port: 4100 }, inputs: {}, }; - const before = recorded.envVar.length; - - run( + const result = run( serviceDescriptorOf(target, 'compute').serialize(ctx, provisioned, config), ); - const writes = recorded.envVar.slice(before).map(([, props]) => props); - expect(writes).toContainEqual({ - project: 'shop-project#cloud-id', - key: 'COMPOSER_SHOP_WEB_PORT', - value: '4100', - class: 'production', - }); + expect(unwrapRedacted(result.bootVariables)['COMPOSER_SHOP_WEB_PORT']).toBe('4100'); }); - test('named environment: serialize writes env vars with class "preview" and branchId', async () => { + test('a preview environment sends the same variables and writes no row', async () => { const target = prismaCloud({ workspaceId: 'ws_1' }); const node = compute({ name: 'test-service', @@ -1518,32 +1454,147 @@ describe("prismaCloud().nodes['compute'] — the service descriptor", () => { const config = { service: { port: 3000 }, inputs: {} }; const before = recorded.envVar.length; - run( + const result = run( serviceDescriptorOf(target, 'compute').serialize(ctx, provisioned, config), ); - expect(recorded.envVar.slice(before)).toEqual([ - [ - 'shop.auth3.env.COMPOSER_SHOP_AUTH3_PORT', - { - project: 'shop-project#cloud-id', - key: 'COMPOSER_SHOP_AUTH3_PORT', - value: '3000', - class: 'preview', - branchId: 'branch_1', - }, - ], - [ - 'shop.auth3.env.COMPOSER_SHOP_AUTH3_ORIGIN', - { - project: 'shop-project#cloud-id', - key: 'COMPOSER_SHOP_AUTH3_ORIGIN', - value: '"https://svc.example"', - class: 'preview', - branchId: 'branch_1', - }, - ], - ]); + expect(recorded.envVar.slice(before)).toEqual([]); + expect(unwrapRedacted(result.bootVariables)).toEqual({ + COMPOSER_SHOP_AUTH3_PORT: '3000', + COMPOSER_SHOP_AUTH3_RPC_ACCEPTED_KEYS: null, + COMPOSER_SHOP_AUTH3_STREAMS_API_KEY: null, + COMPOSER_SHOP_AUTH3_ORIGIN: '"https://svc.example"', + }); + }); + + test('serialize refuses a service with more than 50 variables, naming the service, the count and the limit, for a deploy and under prisma dev', () => { + const target = prismaCloud({ workspaceId: 'ws_1' }); + const deps = Object.fromEntries( + Array.from({ length: 49 }, (_, i) => [ + `dep${i}`, + dependency({ type: 'rpc', connection: { params: { url: string() }, hydrate: (v) => v } }), + ]), + ); + const node = compute({ + name: 'wide', + deps, + build: { + extension: '@prisma/composer/node', + type: 'node', + module: 'file:///test/service.ts', + entry: 'server.js', + }, + }); + const ctx = { + address: 'shop.wide', + node, + graph: { root: { id: 'shop' }, inputBindings: [], edges: [] }, + application: { + projectId: 'shop-project#cloud-id', + branchId: undefined, + defaultBranchId: undefined, + branchless: false, + }, + opts: {}, + } as unknown as LowerContext; + const provisioned = { projectId: 'shop-project#cloud-id', endpointDomain: 'https://w.example' }; + const config = { + service: { port: 3000 }, + inputs: Object.fromEntries( + Object.keys(deps).map((name) => [name, { url: `https://${name}` }]), + ), + }; + const before = recorded.sentVariableNames.length; + + let thrown: unknown; + try { + run(serviceDescriptorOf(target, 'compute').serialize(ctx, provisioned, config)); + } catch (error) { + thrown = error; + } + + if (!CliStructuredError.is(thrown)) throw new Error('expected a structured error'); + const envelope = thrown.toEnvelope(); + expect(envelope.code).toBe('DEPLOY.SERVICE_VARIABLE_LIMIT'); + expect(envelope.summary).toBe( + 'The service "shop.wide" needs 51 variables, but Prisma Cloud stores at most 50 on one service.', + ); + expect(envelope.fix).toContain('fewer dependencies or generated values'); + expect(envelope.why).toContain("the branch's application topology has already been replaced"); + expect(recorded.sentVariableNames.length).toBe(before); + + let local: unknown; + try { + run( + serviceDescriptorOf(target, 'compute').serialize( + { + ...ctx, + application: { + projectId: 'shop-project#cloud-id', + branchId: undefined, + defaultBranchId: undefined, + branchless: true, + }, + } as LowerContext, + provisioned, + config, + ), + ); + } catch (error) { + local = error; + } + if (!CliStructuredError.is(local)) + throw new Error('expected a structured error under prisma dev'); + expect(local.code).toBe('DEPLOY.SERVICE_VARIABLE_LIMIT'); + expect(local.toEnvelope().why).toContain( + '`prisma dev` refuses it as a deploy to Prisma Cloud would', + ); + expect(local.toEnvelope().why).not.toContain('topology'); + }); + + test('a service with exactly 50 variables serializes', () => { + const target = prismaCloud({ workspaceId: 'ws_1' }); + const deps = Object.fromEntries( + Array.from({ length: 48 }, (_, i) => [ + `dep${i}`, + dependency({ type: 'rpc', connection: { params: { url: string() }, hydrate: (v) => v } }), + ]), + ); + const node = compute({ + name: 'wide', + deps, + build: { + extension: '@prisma/composer/node', + type: 'node', + module: 'file:///test/service.ts', + entry: 'server.js', + }, + }); + const ctx = { + address: 'shop.wide', + node, + graph: { root: { id: 'shop' }, inputBindings: [], edges: [] }, + application: { + projectId: 'shop-project#cloud-id', + branchId: undefined, + defaultBranchId: undefined, + branchless: false, + }, + opts: {}, + } as unknown as LowerContext; + const provisioned = { projectId: 'shop-project#cloud-id', endpointDomain: 'https://w.example' }; + const config = { + service: { port: 3000 }, + inputs: Object.fromEntries( + Object.keys(deps).map((name) => [name, { url: `https://${name}` }]), + ), + }; + + const result = run( + serviceDescriptorOf(target, 'compute').serialize(ctx, provisioned, config), + ); + + expect(Object.values(result.bootVariables).filter((value) => value !== null)).toHaveLength(50); }); test('serialize surfaces a non-default port so deploy routes to it', async () => { @@ -1687,7 +1738,7 @@ describe("prismaCloud().nodes['compute'] — the service descriptor", () => { ]); }); - test("deploy declares serialize's triggers (plus pointer timestamps) and rides the app ordering edge — PRO-211", () => { + test("deploy passes serialize's variables and declares a trigger per platform variable", () => { const target = prismaCloud({ workspaceId: 'ws_1' }); const ctx = { id: 'shop.auth', @@ -1702,14 +1753,13 @@ describe("prismaCloud().nodes['compute'] — the service descriptor", () => { endpointDomain: 'https://auth-svc.example', }; const artifact = { path: '/tmp/auth.tar.gz', sha256: 'sha-auth' }; + const requestVariables = { + COMPOSER_AUTH_DB_URL: Redacted.make('postgres://real-db'), + COMPOSER_AUTH_OLD_URL: null, + }; const serialized = { - environment: [ - { - environmentVariableId: 'COMPOSER_AUTH_DB_URL-var#cloud-id', - key: 'COMPOSER_AUTH_DB_URL', - }, - ], - triggers: { COMPOSER_AUTH_DB_URL: Redacted.make('postgres://real-db') }, + bootVariables: { COMPOSER_AUTH_DB_URL: requestVariables.COMPOSER_AUTH_DB_URL }, + requestVariables, // The input document points at an operator-owned platform variable; its // preflight `updatedAt` must join the triggers under `:updatedAt`. platformVariables: ['STRIPE_SECRET_KEY'], @@ -1721,12 +1771,7 @@ describe("prismaCloud().nodes['compute'] — the service descriptor", () => { serviceDescriptorOf(target, 'compute').deploy(ctx, provisioned, artifact, serialized), ); - // The mocked `Output.all`/`Output.map` collapse to "apply the function to - // the collected values", so the recorded `app` is the resolved id — what - // the real Output resolves to as well. What the assertion pins is that - // `app` is built FROM the env rows' ids, which is the dependency Alchemy - // schedules the writes on, and that the triggers reach the Deployment - // with the pointer timestamp folded in ('?' — no preflight ran here). + // The pointer timestamp is '?' because no preflight ran here. expect(recorded.deploy).toEqual([ [ 'shop.auth.deployment', @@ -1735,10 +1780,8 @@ describe("prismaCloud().nodes['compute'] — the service descriptor", () => { artifactPath: '/tmp/auth.tar.gz', artifactContentType: 'application/gzip', portMapping: { http: 8080 }, - triggers: { - COMPOSER_AUTH_DB_URL: serialized.triggers['COMPOSER_AUTH_DB_URL'], - 'STRIPE_SECRET_KEY:updatedAt': '?', - }, + triggers: { 'STRIPE_SECRET_KEY:updatedAt': '?' }, + variables: requestVariables, start: true, promote: true, }, @@ -1776,8 +1819,8 @@ describe("prismaCloud().nodes['compute'] — the service descriptor", () => { }; const artifact = { path: '/tmp/auth.tar.gz', sha256: 'sha-auth' }; const serialized = { - environment: [], - triggers: {}, + bootVariables: {}, + requestVariables: {}, platformVariables: [], port: 3000, input: { @@ -1820,8 +1863,8 @@ describe("prismaCloud().nodes['compute'] — the service descriptor", () => { }; const artifact = { path: '/tmp/mailer.tar.gz', sha256: 'sha-mailer' }; const serialized = { - environment: [], - triggers: {}, + bootVariables: {}, + requestVariables: {}, platformVariables: [], port: 3000, input: { @@ -1864,8 +1907,8 @@ describe("prismaCloud().nodes['compute'] — the service descriptor", () => { }; const artifact = { path: '/tmp/auth.tar.gz', sha256: 'sha-auth' }; const serialized = { - environment: [], - triggers: {}, + bootVariables: {}, + requestVariables: {}, platformVariables: [], port: 3000, input: { @@ -1945,7 +1988,7 @@ describe("prismaCloud().nodes['s3-store'] — the service descriptor with extend expect(result.secretAccessKey).toBe('sekret'); // compute's own serialize product survives the extension. expect(result.port).toBe(3000); - expect(Array.isArray(result.environment)).toBe(true); + expect(unwrapRedacted(result.bootVariables)['COMPOSER_SHOP_STORE_PORT']).toBe('3000'); }); test('serialize fails closed when credentials or bucket are unwired (F5)', async () => { @@ -2016,8 +2059,8 @@ describe("prismaCloud().nodes['s3-store'] — the service descriptor with extend }; const artifact = { path: '/tmp/store.tar.gz', sha256: 'sha-store' }; const serialized = { - environment: [{ id: 'STORE_PORT-var#cloud-id', key: 'STORE_PORT' }], - triggers: {}, + bootVariables: {}, + requestVariables: {}, platformVariables: [], port: 3000, bucket: 'streams', @@ -2133,7 +2176,7 @@ describe('s3StoreService() authoring factory', () => { }); describe('sharing: one module-provisioned postgres, two compute consumers — through core lowering()', () => { - test("ONE Database + Connection; both services' env writes carry its url under their own keys", async () => { + test("ONE Database + Connection; both services' variables carry its url under their own keys", async () => { const target = prismaCloud({ workspaceId: 'ws_1' }); const build = { extension: '@prisma/composer/node', @@ -2160,7 +2203,7 @@ describe('sharing: one module-provisioned postgres, two compute consumers — th const before = { db: recorded.db.length, conn: recorded.conn.length, - envVar: recorded.envVar.length, + deploy: recorded.deploy.length, }; run( @@ -2195,19 +2238,9 @@ describe('sharing: one module-provisioned postgres, two compute consumers — th ], ]); - const writes = recorded.envVar.slice(before.envVar).map(([, props]) => props); - expect(writes).toContainEqual({ - project: 'shop-project#cloud-id', - key: 'COMPOSER_SHOP_AUTH_MAIN_URL', - value: 'postgres://shop.data.connection', - class: 'production', - }); - expect(writes).toContainEqual({ - project: 'shop-project#cloud-id', - key: 'COMPOSER_SHOP_BILLING_STORE_URL', - value: 'postgres://shop.data.connection', - class: 'production', - }); + const sent = sentSince(before.deploy); + expect(sent['COMPOSER_SHOP_AUTH_MAIN_URL']).toBe('postgres://shop.data.connection'); + expect(sent['COMPOSER_SHOP_BILLING_STORE_URL']).toBe('postgres://shop.data.connection'); }); }); @@ -2298,7 +2331,7 @@ describe('ADR-0030: per-binding RPC service keys — mint (control.ts) + wire (d }, }); - test("consumer's edge writes its own serviceKey var; the provider's writes the accepted set with that one key", async () => { + test("consumer's edge sends its own serviceKey variable; the provider's sends the accepted set with that one key", async () => { const target = prismaCloud({ workspaceId: 'ws_1' }); const root = module('shop', {}, ({ provision }) => { const auth = provision( @@ -2311,7 +2344,7 @@ describe('ADR-0030: per-binding RPC service keys — mint (control.ts) + wire (d }); return {}; }); - const before = { envVar: recorded.envVar.length, serviceKey: recorded.serviceKey.length }; + const before = { deploy: recorded.deploy.length, serviceKey: recorded.serviceKey.length }; run( lowering(root, configFor(target), { @@ -2329,19 +2362,11 @@ describe('ADR-0030: per-binding RPC service keys — mint (control.ts) + wire (d 'shop.web.servicekey.auth', ]); - const writes = recorded.envVar.slice(before.envVar).map(([, props]) => props); - expect(writes).toContainEqual({ - project: 'shop-project#cloud-id', - key: 'COMPOSER_SHOP_WEB_AUTH_SERVICEKEY', - value: 'key-for-shop.web.servicekey.auth', - class: 'production', - }); - expect(writes).toContainEqual({ - project: 'shop-project#cloud-id', - key: 'COMPOSER_SHOP_AUTH_RPC_ACCEPTED_KEYS', - value: '["key-for-shop.web.servicekey.auth"]', - class: 'production', - }); + const sent = sentSince(before.deploy); + expect(sent['COMPOSER_SHOP_WEB_AUTH_SERVICEKEY']).toBe('key-for-shop.web.servicekey.auth'); + expect(sent['COMPOSER_SHOP_AUTH_RPC_ACCEPTED_KEYS']).toBe( + '["key-for-shop.web.servicekey.auth"]', + ); }); test('two consumers of one provider mint two distinct edge keys; the accepted set carries both', async () => { @@ -2361,7 +2386,7 @@ describe('ADR-0030: per-binding RPC service keys — mint (control.ts) + wire (d }); return {}; }); - const before = recorded.envVar.length; + const before = recorded.deploy.length; run( lowering(root, configFor(target), { @@ -2375,23 +2400,19 @@ describe('ADR-0030: per-binding RPC service keys — mint (control.ts) + wire (d }), ); - const writes = recorded.envVar - .slice(before) - .map(([, props]) => props as { key: string; value: string }); - const web1Key = writes.find((w) => w.key === 'COMPOSER_SHOP_WEB1_AUTH_SERVICEKEY')?.value; - const web2Key = writes.find((w) => w.key === 'COMPOSER_SHOP_WEB2_AUTH_SERVICEKEY')?.value; + const sent = sentSince(before); + const web1Key = sent['COMPOSER_SHOP_WEB1_AUTH_SERVICEKEY']; + const web2Key = sent['COMPOSER_SHOP_WEB2_AUTH_SERVICEKEY']; expect(web1Key).toBeDefined(); expect(web2Key).toBeDefined(); expect(web1Key).not.toBe(web2Key); - const acceptedRaw = writes.find( - (w) => w.key === 'COMPOSER_SHOP_AUTH2_RPC_ACCEPTED_KEYS', - )?.value; - if (acceptedRaw === undefined) throw new Error('expected an accepted-keys row'); + const acceptedRaw = sent['COMPOSER_SHOP_AUTH2_RPC_ACCEPTED_KEYS']; + if (typeof acceptedRaw !== 'string') throw new Error('expected an accepted-keys value'); expect(JSON.parse(acceptedRaw).sort()).toEqual([web1Key, web2Key].sort()); }); - test('a provider that exposes RPC with zero wired consumers still writes an accepted-set var — value "[]" (deny-all, closes the fail-open hole)', async () => { + test('a provider that exposes RPC with zero wired consumers still sends an accepted set — value "[]" (deny-all, closes the fail-open hole)', async () => { const target = prismaCloud({ workspaceId: 'ws_1' }); const root = module('shop', {}, ({ provision }) => { provision(compute({ name: 'auth3', deps: {}, build, expose: { verify: fakeRpcContract } }), { @@ -2399,7 +2420,7 @@ describe('ADR-0030: per-binding RPC service keys — mint (control.ts) + wire (d }); return {}; }); - const before = { envVar: recorded.envVar.length, serviceKey: recorded.serviceKey.length }; + const before = { deploy: recorded.deploy.length, serviceKey: recorded.serviceKey.length }; run( lowering(root, configFor(target), { @@ -2412,16 +2433,11 @@ describe('ADR-0030: per-binding RPC service keys — mint (control.ts) + wire (d // No consumer, so no ServiceKey is minted. expect(recorded.serviceKey.slice(before.serviceKey)).toEqual([]); - const writes = recorded.envVar.slice(before.envVar).map(([, props]) => props); - expect(writes).toContainEqual({ - project: 'shop-project#cloud-id', - key: 'COMPOSER_SHOP_AUTH3_RPC_ACCEPTED_KEYS', - value: '[]', - class: 'production', - }); + const sent = sentSince(before.deploy); + expect(sent['COMPOSER_SHOP_AUTH3_RPC_ACCEPTED_KEYS']).toBe('[]'); }); - test('a service with no `expose` never serves, so it writes no accepted-keys var', async () => { + test('a service with no `expose` never serves, so its accepted keys are sent as null', async () => { const target = prismaCloud({ workspaceId: 'ws_1' }); const root = module('shop', {}, ({ provision }) => { const auth = provision( @@ -2435,7 +2451,7 @@ describe('ADR-0030: per-binding RPC service keys — mint (control.ts) + wire (d }); return {}; }); - const before = recorded.envVar.length; + const before = recorded.deploy.length; run( lowering(root, configFor(target), { @@ -2448,14 +2464,11 @@ describe('ADR-0030: per-binding RPC service keys — mint (control.ts) + wire (d }), ); - const writtenKeys = recorded.envVar - .slice(before) - .map(([, props]) => (props as { key: string }).key); - expect(writtenKeys).not.toContain('COMPOSER_SHOP_STOREFRONT_RPC_ACCEPTED_KEYS'); - // The origin row is service-derived, not edge-derived, so the expose - // check above does not apply to it: the non-exposing storefront still - // gets its own origin row. - expect(writtenKeys).toContain('COMPOSER_SHOP_STOREFRONT_ORIGIN'); + const sent = sentSince(before); + expect(sent['COMPOSER_SHOP_STOREFRONT_RPC_ACCEPTED_KEYS']).toBeNull(); + // The origin is service-derived, not edge-derived, so the expose check + // above does not apply to it: the non-exposing storefront still gets it. + expect(sent['COMPOSER_SHOP_STOREFRONT_ORIGIN']).toBe('"https://shop.storefront.example"'); }); }); @@ -2499,7 +2512,7 @@ describe("streams' provisioned bearer key — one value per PROVIDER, stored on }); return {}; }); - const before = { envVar: recorded.envVar.length, serviceKey: recorded.serviceKey.length }; + const before = { deploy: recorded.deploy.length, serviceKey: recorded.serviceKey.length }; run( lowering(root, configFor(target), { @@ -2519,30 +2532,15 @@ describe("streams' provisioned bearer key — one value per PROVIDER, stored on 'shop.events.streamkey', ]); - const writes = recorded.envVar.slice(before.envVar).map(([, props]) => props); - const writtenValue = (envName: string): unknown => - ( - writes.find((w) => (w as { key: string }).key === envName) as - | { value?: unknown } - | undefined - )?.value; - expect(writtenValue('COMPOSER_SHOP_READER_EVENTS_APIKEY')).toBe( - 'key-for-shop.events.streamkey', - ); - expect(writtenValue('COMPOSER_SHOP_WRITER_EVENTS_APIKEY')).toBe( - 'key-for-shop.events.streamkey', - ); + const sent = sentSince(before.deploy); + expect(sent['COMPOSER_SHOP_READER_EVENTS_APIKEY']).toBe('key-for-shop.events.streamkey'); + expect(sent['COMPOSER_SHOP_WRITER_EVENTS_APIKEY']).toBe('key-for-shop.events.streamkey'); // The provider's own reserved provider param: the same key, under the // name the streams entrypoint reads (address-scoped; compute's run // validates and re-stashes it), JSON-encoded like any service-own // literal param. - expect(writes).toContainEqual({ - project: 'shop-project#cloud-id', - key: 'COMPOSER_SHOP_EVENTS_STREAMS_API_KEY', - value: '"key-for-shop.events.streamkey"', - class: 'production', - }); + expect(sent['COMPOSER_SHOP_EVENTS_STREAMS_API_KEY']).toBe('"key-for-shop.events.streamkey"'); }); test('the reserved provider param refuses two disagreeing keys for one provider (a per-edge flip would be loud)', () => { @@ -2601,7 +2599,7 @@ describe("streams' provisioned bearer key — one value per PROVIDER, stored on ).toThrow(/provisioned 2 distinct keys/); }); - test('a streams provider with no consumers mints nothing and stores no key', async () => { + test('a streams provider with no consumers mints nothing and sends its key as null', async () => { const target = prismaCloud({ workspaceId: 'ws_1' }); const root = module('shop', {}, ({ provision }) => { provision( @@ -2610,7 +2608,7 @@ describe("streams' provisioned bearer key — one value per PROVIDER, stored on ); return {}; }); - const before = { envVar: recorded.envVar.length, serviceKey: recorded.serviceKey.length }; + const before = { deploy: recorded.deploy.length, serviceKey: recorded.serviceKey.length }; run( lowering(root, configFor(target), { @@ -2621,10 +2619,7 @@ describe("streams' provisioned bearer key — one value per PROVIDER, stored on ); expect(recorded.serviceKey.slice(before.serviceKey)).toEqual([]); - const keys = recorded.envVar - .slice(before.envVar) - .map(([, props]) => (props as { key: string }).key); - expect(keys).not.toContain('COMPOSER_SHOP_LONELY_STREAMS_API_KEY'); + expect(sentSince(before.deploy)['COMPOSER_SHOP_LONELY_STREAMS_API_KEY']).toBeNull(); }); }); @@ -2641,7 +2636,7 @@ describe("descriptors/compute.ts's provider-param loop is generic over the regis satisfies: () => true, }; - test('three independently-registered provider params — including a brand this test invents — each write their own row through the same unmodified serialize()', async () => { + test('three independently-registered provider params — including a brand this test invents — each send their own variable through the same unmodified serialize()', async () => { // Neither of these two symbols is RPC_PEER_KEY or STREAMS_API_KEY — // `computeDescriptor` is handed this registry as plain data and never // imports a brand's module, so it cannot tell a real brand from a made- @@ -2659,7 +2654,7 @@ describe("descriptors/compute.ts's provider-param loop is generic over the regis brandTwo, { name: 'PARAM_TWO', schema: type('string'), brand: brandTwo, value: () => 'value-two' }, ], - // A third registrant may also decline to write a row at all. + // A third registrant may also decline to send a value at all. [ brandThree, { @@ -2694,31 +2689,18 @@ describe("descriptors/compute.ts's provider-param loop is generic over the regis endpointDomain: 'https://multi-svc.example', }; const config = { service: { port: 3000 }, inputs: {} }; - const before = recorded.envVar.length; // The three-brand options can't ride the shared registry, so erase the // precise descriptor to the registry's own type — the same assignment // control.ts makes when it registers the real one. const descriptor: NodeDescriptor = computeDescriptor(() => o); if (descriptor.kind !== 'service') throw new Error('expected a service descriptor'); - run(descriptor.serialize(ctx, provisioned, config)); + const result = run(descriptor.serialize(ctx, provisioned, config)); - const writes = recorded.envVar.slice(before).map(([, props]) => props); - expect(writes).toContainEqual({ - project: 'shop-project#cloud-id', - key: 'COMPOSER_SHOP_MULTI_PARAM_ONE', - value: '"value-one"', - class: 'production', - }); - expect(writes).toContainEqual({ - project: 'shop-project#cloud-id', - key: 'COMPOSER_SHOP_MULTI_PARAM_TWO', - value: '"value-two"', - class: 'production', - }); - expect(writes.map((w) => (w as { key: string }).key)).not.toContain( - 'COMPOSER_SHOP_MULTI_PARAM_THREE', - ); + const sent = unwrapRedacted(result.bootVariables); + expect(sent['COMPOSER_SHOP_MULTI_PARAM_ONE']).toBe('"value-one"'); + expect(sent['COMPOSER_SHOP_MULTI_PARAM_TWO']).toBe('"value-two"'); + expect(sent).not.toHaveProperty('COMPOSER_SHOP_MULTI_PARAM_THREE'); }); }); @@ -3129,7 +3111,7 @@ describe('platform identity: each row carries its topology node logicalId — th 'Bucket shop.files', ]), ); - expect(ownRows.some(([resource]) => resource.startsWith('EnvironmentVariable '))).toBe(true); + expect(ownRows.some(([resource]) => resource.startsWith('EnvironmentVariable '))).toBe(false); expect(ownRows.filter(([, adopt]) => adopt !== true)).toEqual([]); expect(policies.has('Connection shop.auth.database.connection')).toBe(true); expect(policies.get('Connection shop.auth.database.connection')).toBeUndefined(); @@ -3177,7 +3159,7 @@ describe('resource IDs are built from the full address, and each declares the ID endpointDomain: 'https://shop.auth.api.example', }, { path: '/tmp/api.tar.gz', sha256: 'sha-api' }, - { environment: [], triggers: {}, platformVariables: [], port: 3000 }, + { bootVariables: {}, requestVariables: {}, platformVariables: [], port: 3000 }, ), ); @@ -3189,7 +3171,7 @@ describe('resource IDs are built from the full address, and each declares the ID expect(renamedFromOf('Deployment shop.auth.api.deployment')).toEqual(['auth.api-deploy']); }); - test('compute: config rows, the input row, a generated value and its row, and a provider-param row', async () => { + test('compute: a generated value keeps its former ID, and the variables are keyed by the full address', async () => { const target = prismaCloud({ workspaceId: 'ws_1' }); const node = compute({ name: 'api', @@ -3230,38 +3212,20 @@ describe('resource IDs are built from the full address, and each declares the ID 'COMPOSER_AUTH_API_INPUT:secret-generated', ]); - const rows = idsSince(recorded.envVar, before.envVar).map((id) => [ - id, - renamedFromOf(`EnvironmentVariable ${id}`), - ]); - expect(rows).toEqual([ - // Config rows: an input's dependency param, then the service's own param. - ['shop.auth.api.env.COMPOSER_SHOP_AUTH_API_DB_URL', ['COMPOSER_AUTH_API_DB_URL-var']], - ['shop.auth.api.env.COMPOSER_SHOP_AUTH_API_PORT', ['COMPOSER_AUTH_API_PORT-var']], - [ - 'shop.auth.api.env.COMPOSER_SHOP_AUTH_API_SECRET_GENERATED', - ['COMPOSER_AUTH_API_SECRET_GENERATED-var'], - ], - // The origin is a provider param every compute service writes. - ['shop.auth.api.env.COMPOSER_SHOP_AUTH_API_ORIGIN', ['COMPOSER_AUTH_API_ORIGIN-var']], - ]); - - // The input row travels in the artifact. A service with no artifact gets it as a variable. - const beforeReserve = recorded.envVar.length; - const { reserve } = serviceDescriptorOf(target, 'compute'); - if (reserve === undefined) throw new Error('compute declares reserve'); - run(reserve(ctx, provisioned, serialized)); - expect( - idsSince(recorded.envVar, beforeReserve).map((id) => [ - id, - renamedFromOf(`EnvironmentVariable ${id}`), - ]), - ).toEqual([ - ['shop.auth.api.env.COMPOSER_SHOP_AUTH_API_INPUT', ['COMPOSER_AUTH_API_INPUT-var']], + expect(idsSince(recorded.envVar, before.envVar)).toEqual([]); + expect(Object.keys(serialized.bootVariables)).toEqual([ + // An input's dependency param, then the service's own param. + 'COMPOSER_SHOP_AUTH_API_DB_URL', + 'COMPOSER_SHOP_AUTH_API_PORT', + 'COMPOSER_SHOP_AUTH_API_SECRET_GENERATED', + 'COMPOSER_SHOP_AUTH_API_RPC_ACCEPTED_KEYS', + 'COMPOSER_SHOP_AUTH_API_STREAMS_API_KEY', + 'COMPOSER_SHOP_AUTH_API_ORIGIN', ]); + expect(recorded.sentVariableNames.at(-1)?.[0]).toBe('shop.auth.api.sent-variable-names'); }); - test('compute: an app name with `-` builds the new key with `_`, and the legacy key from the address without the app name', async () => { + test('compute: an app name with `-` builds the key with `_`, and the App keeps the ID from the address without the app name', async () => { const target = prismaCloud({ workspaceId: 'ws_1' }); const node = compute({ name: 'web', deps: {}, build }); const ctx = { @@ -3272,10 +3236,10 @@ describe('resource IDs are built from the full address, and each declares the ID application, opts: {}, } as unknown as LowerContext; - const before = { svc: recorded.svc.length, envVar: recorded.envVar.length }; + const before = { svc: recorded.svc.length }; run(serviceDescriptorOf(target, 'compute').provision(ctx)); - run( + const serialized = run( serviceDescriptorOf(target, 'compute').serialize( ctx, { projectId: 'shop-project#cloud-id', endpointDomain: 'https://web.example' }, @@ -3286,9 +3250,7 @@ describe('resource IDs are built from the full address, and each declares the ID expect(idsSince(recorded.svc, before.svc)).toEqual(['my-shop.web']); expect(renamedFromOf('App my-shop.web')).toEqual(['web-svc']); expect(recorded.svc[before.svc]?.[1]).toHaveProperty('displayName', 'my-shop.web'); - const port = 'my-shop.web.env.COMPOSER_MY_SHOP_WEB_PORT'; - expect(idsSince(recorded.envVar, before.envVar)).toContain(port); - expect(renamedFromOf(`EnvironmentVariable ${port}`)).toEqual(['COMPOSER_WEB_PORT-var']); + expect(serialized.bootVariables).toHaveProperty('COMPOSER_MY_SHOP_WEB_PORT'); }); test('compute: an RPC service key is named under the calling service, and a streams key under the provider', async () => { @@ -3332,7 +3294,7 @@ describe('resource IDs are built from the full address, and each declares the ID }); return {}; }); - const before = { serviceKey: recorded.serviceKey.length, envVar: recorded.envVar.length }; + const before = { serviceKey: recorded.serviceKey.length, deploy: recorded.deploy.length }; const bundle = { dir: 'dist/bundle', entry: 'server.js' }; run( @@ -3349,18 +3311,12 @@ describe('resource IDs are built from the full address, and each declares the ID ]); expect(renamedFromOf('ServiceKey shop.web.servicekey.auth')).toEqual(['servicekey-web.auth']); expect(renamedFromOf('ServiceKey shop.events.streamkey')).toEqual(['streamskey-events']); - // The provider-param rows the keys feed. - const accepted = 'shop.auth.env.COMPOSER_SHOP_AUTH_RPC_ACCEPTED_KEYS'; - const streams = 'shop.events.env.COMPOSER_SHOP_EVENTS_STREAMS_API_KEY'; - expect(idsSince(recorded.envVar, before.envVar)).toEqual( - expect.arrayContaining([accepted, streams]), + // The provider params the keys feed. + const sent = sentSince(before.deploy); + expect(sent['COMPOSER_SHOP_AUTH_RPC_ACCEPTED_KEYS']).toBe( + '["key-for-shop.web.servicekey.auth"]', ); - expect(renamedFromOf(`EnvironmentVariable ${accepted}`)).toEqual([ - 'COMPOSER_AUTH_RPC_ACCEPTED_KEYS-var', - ]); - expect(renamedFromOf(`EnvironmentVariable ${streams}`)).toEqual([ - 'COMPOSER_EVENTS_STREAMS_API_KEY-var', - ]); + expect(sent['COMPOSER_SHOP_EVENTS_STREAMS_API_KEY']).toBe('"key-for-shop.events.streamkey"'); }); test('raw postgres: the Database, Connection and warm-up; the Connection is named by the address', () => { @@ -3619,21 +3575,20 @@ describe('local dev: the emulators hook keys each node by its main resource ID', }); afterAll(() => { - // Every resource declared anywhere in this file named exactly one former ID. - expect(recorded.renamePolicy.filter(([, former]) => former?.length !== 1)).toEqual([]); + // Only a dev server's local rows are new since the release before ADR-0057; every other resource + // declared anywhere in this file named exactly one former ID and is adopted as the app's own row. + const isRow = ([resource]: [string, unknown]) => resource.startsWith('EnvironmentVariable '); + expect(recorded.renamePolicy.filter((entry) => !isRow(entry) && entry[1]?.length !== 1)).toEqual( + [], + ); const declared = recorded.adoptPolicy.filter(([resource]) => !resource.startsWith('Connection ')); - const variables = declared - .map(([resource]) => resource) - .filter((resource) => resource.startsWith('EnvironmentVariable ')); - // Every declaration site in compute.ts ran somewhere in this file: params, the input document - // (in reserve), generated leaves and provider params. - for (const suffix of ['_INPUT', '_GENERATED', '_RPC_ACCEPTED_KEYS', '_PORT']) { - expect(variables.some((resource) => resource.endsWith(suffix))).toBe(true); - } + expect(declared.filter((entry) => !isRow(entry) && entry[1] !== true)).toEqual([]); + const rows = declared.filter(isRow); + expect(rows.length).toBeGreaterThan(0); + expect(rows.filter(([, adopt]) => adopt !== undefined)).toEqual([]); expect( - variables.filter((resource) => !/^EnvironmentVariable \S+\.env\.COMPOSER_/.test(resource)), + rows.filter(([resource]) => !/^EnvironmentVariable \S+\.env\.COMPOSER_/.test(resource)), ).toEqual([]); - expect(declared.filter(([, adopt]) => adopt !== true)).toEqual([]); }); describe("prismaCloud().nodes['public-url'] — the public URL descriptor", () => { @@ -3976,88 +3931,80 @@ describe("a compute service's input document travels in its artifact", () => { ), ); - test('no variable and no trigger member is keyed by it; the port, connection, generated and provider rows stay variables', async () => { + test('it is not a variable; the port, connection, generated and provider values are, and no row is written', async () => { const before = recorded.envVar.length; const serialized = serialize('Shop'); - const keys = recorded.envVar.slice(before).map(([, props]) => (props as { key: string }).key); - expect(keys).toEqual([ + expect(recorded.envVar.slice(before)).toEqual([]); + expect(Object.keys(serialized.bootVariables)).toEqual([ 'COMPOSER_SHOP_WEB_DB_URL', 'COMPOSER_SHOP_WEB_PORT', 'COMPOSER_SHOP_WEB_TOKEN_GENERATED', + 'COMPOSER_SHOP_WEB_RPC_ACCEPTED_KEYS', + 'COMPOSER_SHOP_WEB_STREAMS_API_KEY', 'COMPOSER_SHOP_WEB_ORIGIN', ]); - expect(Object.keys(serialized.triggers)).toEqual(keys); - expect(unwrapTriggers(serialized.triggers)['COMPOSER_SHOP_WEB_PORT']).toBe('3000'); + expect(unwrapRedacted(serialized.bootVariables)['COMPOSER_SHOP_WEB_PORT']).toBe('3000'); expect(serialized.input?.value).toBe( '{"siteName":"Shop","stripeKey":{"$platform":{"name":"STRIPE_SECRET_KEY","secret":true}},"token":{"$generated":"COMPOSER_SHOP_WEB_TOKEN_GENERATED","redacted":true}}', ); }); - test('for a service with no artifact, reserve writes the input document as the variable it was before', async () => { + /** The local, branchless application `prisma dev` lowers into: the only one `reserve` runs for. */ + const localContextFor = (siteName: string) => + ({ + ...contextFor(siteName), + application: { ...application, branchless: true }, + }) as unknown as LowerContext; + + test('for a dev server, reserve writes a local row per value and the input document, and none for a key sent as null', async () => { const { reserve } = serviceDescriptorOf(prismaCloud({ workspaceId: 'ws_1' }), 'compute'); if (reserve === undefined) throw new Error('compute declares reserve'); const serialized = serialize('Shop'); const before = recorded.envVar.length; - run(reserve(contextFor('Shop'), provisioned, serialized)); + run(reserve(localContextFor('Shop'), provisioned, serialized)); - expect(recorded.envVar.slice(before)).toEqual([ - [ - 'shop.web.env.COMPOSER_SHOP_WEB_INPUT', - { - project: 'shop-project#cloud-id', - key: 'COMPOSER_SHOP_WEB_INPUT', - value: - '{"siteName":"Shop","stripeKey":{"$platform":{"name":"STRIPE_SECRET_KEY","secret":true}},"token":{"$generated":"COMPOSER_SHOP_WEB_TOKEN_GENERATED","redacted":true}}', - class: 'production', - }, - ], + const rows = recorded.envVar.slice(before).map(([, props]) => props); + expect(rows.map((row) => (row as { key: string }).key)).toEqual([ + 'COMPOSER_SHOP_WEB_DB_URL', + 'COMPOSER_SHOP_WEB_PORT', + 'COMPOSER_SHOP_WEB_TOKEN_GENERATED', + 'COMPOSER_SHOP_WEB_ORIGIN', + 'COMPOSER_SHOP_WEB_INPUT', ]); + expect(rows.at(-1)).toEqual({ + project: 'shop-project#cloud-id', + key: 'COMPOSER_SHOP_WEB_INPUT', + value: + '{"siteName":"Shop","stripeKey":{"$platform":{"name":"STRIPE_SECRET_KEY","secret":true}},"token":{"$generated":"COMPOSER_SHOP_WEB_TOKEN_GENERATED","redacted":true}}', + class: 'production', + }); }); test("reserve publishes the App's endpoint domain as the service's url", async () => { const { reserve } = serviceDescriptorOf(prismaCloud({ workspaceId: 'ws_1' }), 'compute'); if (reserve === undefined) throw new Error('compute declares reserve'); - const result = run(reserve(contextFor('Shop'), provisioned, serialize('Shop'))); + const result = run( + reserve(localContextFor('Shop'), provisioned, serialize('Shop')), + ); expect(result.outputs['url']).toBe('https://shop.web.example'); expect(result.entities[0]).toHaveProperty('url', 'https://shop.web.example'); }); - test('reserve writes the input document as a preview variable on the branch of an environment that has one, as serialize does for its variables', async () => { + test('reserve outside the local application fails as a bug and writes no row', async () => { const { reserve } = serviceDescriptorOf(prismaCloud({ workspaceId: 'ws_1' }), 'compute'); if (reserve === undefined) throw new Error('compute declares reserve'); - const ctx = { - ...contextFor('Shop'), - application: { ...application, branchId: 'br_staging' }, - } as unknown as LowerContext; + const serialized = serialize('Shop'); const before = recorded.envVar.length; - const serialized = run( - serviceDescriptorOf(prismaCloud({ workspaceId: 'ws_1' }), 'compute').serialize( - ctx, - provisioned, - config, - ), - ); - const serializedClassesAndBranches = recorded.envVar - .slice(before) - .map(([, props]) => props as { class: string; branchId?: string }); - const beforeReserve = recorded.envVar.length; - - run(reserve(ctx, provisioned, serialized)); - const [reserved] = recorded.envVar.slice(beforeReserve); - expect(reserved?.[1]).toMatchObject({ - key: 'COMPOSER_SHOP_WEB_INPUT', - class: 'preview', - branchId: 'br_staging', - }); - for (const classAndBranch of serializedClassesAndBranches) { - expect(classAndBranch).toMatchObject({ class: 'preview', branchId: 'br_staging' }); - } + expect(() => run(reserve(contextFor('Shop'), provisioned, serialized))).toThrow( + 'this is a bug in Composer', + ); + expect(recorded.envVar.slice(before)).toEqual([]); }); test('a platform variable named by an input marker stays a trigger member', async () => { diff --git a/packages/1-prisma-cloud/1-extensions/target/src/__tests__/env-key-clash.test.ts b/packages/1-prisma-cloud/1-extensions/target/src/__tests__/env-key-clash.test.ts deleted file mode 100644 index 461b0a859..000000000 --- a/packages/1-prisma-cloud/1-extensions/target/src/__tests__/env-key-clash.test.ts +++ /dev/null @@ -1,115 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { dependency, Load, type ModuleNode, module, string } from '@internal/core'; -import { findEnvKeyClashes } from '../env-key-clash.ts'; -import { compute } from '../exports/index.ts'; - -const build = { - extension: '@prisma/composer/node', - type: 'node', - module: 'file:///test/service.ts', - entry: 'server.js', -}; - -const service = (name: string) => compute({ name, deps: {}, build }); - -type EmptyModule = ModuleNode, Record, undefined>; - -/** Modules with these ids, each inside the one before, the last holding a service `x`. */ -const xInside = (id: string, ...inner: string[]): EmptyModule => - module(id, ({ provision }) => { - const [next, ...rest] = inner; - if (next === undefined) provision(service('x'), { id: 'x' }); - else provision(xInside(next, ...rest), { id: next }); - }); - -/** The app `app` with a service `x` directly below the root, and another inside the modules `id`, then `inner`. */ -const appWithNestedX = (app: string, id: string, ...inner: string[]) => - Load( - module(app, ({ provision }) => { - provision(service('x'), { id: 'x' }); - provision(xInside(id, ...inner), { id }); - }), - ); - -const clashKeys = (graph: ReturnType) => - findEnvKeyClashes(graph).map(({ key, newOwner, oldOwner }) => ({ key, newOwner, oldOwner })); - -describe('findEnvKeyClashes', () => { - test("a module named like the app: one node's new key is the other node's old key", () => { - expect(clashKeys(appWithNestedX('shop', 'shop'))).toContainEqual({ - key: 'COMPOSER_SHOP_X_ORIGIN', - newOwner: 'shop.x', - oldOwner: 'shop.shop.x', - }); - }); - - test('a module named like the app in another letter case', () => { - expect(clashKeys(appWithNestedX('shop', 'Shop'))).toContainEqual({ - key: 'COMPOSER_SHOP_X_ORIGIN', - newOwner: 'shop.x', - oldOwner: 'shop.Shop.x', - }); - }); - - test('an app name with `-` whose parts modules spell', () => { - expect(clashKeys(appWithNestedX('my-shop', 'my', 'shop'))).toContainEqual({ - key: 'COMPOSER_MY_SHOP_X_ORIGIN', - newOwner: 'my-shop.x', - oldOwner: 'my-shop.my.shop.x', - }); - }); - - test('an app name with `_` whose parts modules spell', () => { - expect(clashKeys(appWithNestedX('my_shop', 'my', 'shop'))).toContainEqual({ - key: 'COMPOSER_MY_SHOP_X_ORIGIN', - newOwner: 'my_shop.x', - oldOwner: 'my_shop.my.shop.x', - }); - }); - - test('a service directly under the root named like the app, with a dependency input named like a sibling', () => { - const dep = dependency({ - type: 'test', - connection: { params: { origin: string() }, hydrate: (v) => v }, - }); - const graph = Load( - module('shop', ({ provision }) => { - const x = provision(service('x'), { id: 'x' }); - provision(compute({ name: 'shop', deps: { x: dep }, build }), { - id: 'shop', - deps: { x }, - }); - }), - ); - - expect(clashKeys(graph)).toContainEqual({ - key: 'COMPOSER_SHOP_X_ORIGIN', - newOwner: 'shop.x', - oldOwner: 'shop.shop', - }); - }); - - test("names the key the old owner's row moves to", () => { - const clash = findEnvKeyClashes(appWithNestedX('shop', 'shop')).find( - (c) => c.key === 'COMPOSER_SHOP_X_ORIGIN', - ); - - expect(clash?.oldOwnerNewKey).toBe('COMPOSER_SHOP_SHOP_X_ORIGIN'); - }); - - test('an app without the clash has none', () => { - const graph = Load( - module('shop', ({ provision }) => { - provision(service('x'), { id: 'x' }); - provision( - module('catalog', ({ provision: p }) => { - p(service('x'), { id: 'x' }); - }), - { id: 'catalog' }, - ); - }), - ); - - expect(findEnvKeyClashes(graph)).toEqual([]); - }); -}); diff --git a/packages/1-prisma-cloud/1-extensions/target/src/__tests__/local-compute-converge.test.ts b/packages/1-prisma-cloud/1-extensions/target/src/__tests__/local-compute-converge.test.ts new file mode 100644 index 000000000..621f9ff1b --- /dev/null +++ b/packages/1-prisma-cloud/1-extensions/target/src/__tests__/local-compute-converge.test.ts @@ -0,0 +1,284 @@ +/** + * `prisma dev`'s converge of compute services, under the real Alchemy engine, + * the real local providers and a real Compute emulator in a temporary + * emulators directory: a service that runs its artifact takes its keys from + * its deployment's `variables`, and a dev server from the rows `reserve` + * writes to `env.json`. + */ +import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { dependency, string } from '@internal/core'; +import type { LowerContext } from '@internal/core/deploy'; +import { EMULATORS_DIR_ENV, ensureDaemon, stopDaemon } from '@internal/dev-emulators'; +import { deleteAppInstances, devServerRows, localTargetProviders } from '@internal/local-target'; +import { runScratch, scratchStack } from '@internal/lowering/scratch-stack'; +import * as Effect from 'effect/Effect'; +import * as Layer from 'effect/Layer'; +import { compute } from '../compute.ts'; +import { computeDescriptor } from '../descriptors/compute.ts'; +import { GeneratedParamProvider } from '../generated-param-resource.ts'; +import { localTargetDescriptor } from '../local-target/descriptor.ts'; +import { SentVariableNamesProvider } from '../sent-variable-names-resource.ts'; + +const APP = 'devapp'; +const savedEmulatorsDir = process.env[EMULATORS_DIR_ENV]; + +/** Answers with its own address, its process id and every `COMPOSER_` key it was given. */ +const echoBootstrap = (address: string) => { + const portKey = `COMPOSER_${address.toUpperCase().replaceAll('.', '_')}_PORT`; + return ( + `Bun.serve({ port: JSON.parse(process.env['${portKey}']), fetch: () => Response.json({ ` + + `address: '${address}', pid: process.pid, keys: Object.fromEntries(Object.entries(process.env)` + + `.filter(([key]) => key.startsWith('COMPOSER_'))) }) });\n` + ); +}; + +const build = { + extension: '@prisma/composer/node', + type: 'node', + module: 'file:///test/service.ts', + entry: 'server.js', +}; +const nodeOf = () => + compute({ + name: 'service', + deps: { + upstream: dependency({ + type: 'rpc', + connection: { params: { url: string({ optional: true }) }, hydrate: (v) => v }, + }), + }, + build, + }); + +interface Service { + readonly address: string; + /** The service runs a dev server, so `reserve` stands in for `deploy`. */ + readonly devServer?: boolean; + readonly upstream?: string; +} + +describe.skipIf(process.platform === 'win32')( + 'converging compute services under prisma dev', + () => { + let root: string; + let devDir: string; + let artifacts: Map; + let stack: ReturnType; + + beforeEach(async () => { + root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'local-converge-'))); + process.env[EMULATORS_DIR_ENV] = path.join(root, 'emulators'); + const entry = fileURLToPath(import.meta.resolve('@internal/dev-emulators/compute-main')); + await ensureDaemon('compute', entry, { registryRoot: path.join(root, 'emulators') }); + devDir = path.join(root, 'app', '.prisma-composer', 'dev', 'dev'); + fs.mkdirSync(devDir, { recursive: true }); + artifacts = new Map(); + for (const address of ['devapp.a', 'devapp.b']) { + const dir = path.join(root, 'artifacts', address); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync( + path.join(dir, 'compute.manifest.json'), + JSON.stringify({ manifestVersion: '1', entrypoint: 'bootstrap.js', address }), + ); + fs.writeFileSync(path.join(dir, 'compute.bootstrap.json'), '{}'); + fs.writeFileSync(path.join(dir, 'bootstrap.js'), echoBootstrap(address)); + const tarball = path.join(root, 'artifacts', `${address}.tar.gz`); + expect(spawnSync('tar', ['-czf', tarball, '-C', dir, ...fs.readdirSync(dir)]).status).toBe( + 0, + ); + artifacts.set(address, { path: tarball, sha256: address }); + } + const descriptor = localTargetDescriptor(); + const container = await descriptor.container.ensure({ appName: APP, environment: 'dev' }); + const providers = Layer.mergeAll( + localTargetProviders({ container, devDir, plainVariableText: {}, namedSecrets: {} }), + SentVariableNamesProvider(), + GeneratedParamProvider(), + ); + stack = scratchStack({ providers, dev: false }, 'local-converge'); + }, 60_000); + + afterEach(async () => { + await deleteAppInstances({ devDir, app: APP, environment: 'dev' }).catch(() => undefined); + await stopDaemon('compute', { registryRoot: path.join(root, 'emulators') }).catch( + () => undefined, + ); + fs.rmSync(root, { recursive: true, force: true }); + if (savedEmulatorsDir === undefined) delete process.env[EMULATORS_DIR_ENV]; + else process.env[EMULATORS_DIR_ENV] = savedEmulatorsDir; + }); + + const converge = (services: readonly Service[]) => + runScratch( + stack.deploy( + Effect.gen(function* () { + const descriptor = computeDescriptor(() => ({ + workspaceId: 'local', + providerParams: new Map(), + })); + for (const service of services) { + const node = nodeOf(); + const ctx = { + id: service.address, + address: service.address, + node, + graph: { + root: { id: APP }, + nodes: [{ id: service.address, node }], + inputBindings: [], + edges: [], + }, + application: { + projectId: 'local', + branchId: undefined, + defaultBranchId: undefined, + branchless: true, + }, + lowered: new Map(), + provisioned: new Map(), + } as unknown as LowerContext; + const provisioned = yield* descriptor.provision(ctx); + const serialized = yield* descriptor.serialize(ctx, provisioned, { + service: { port: 3000 }, + inputs: { upstream: { url: service.upstream } }, + }); + const artifact = artifacts.get(service.address); + if (artifact === undefined) throw new Error(`no artifact for ${service.address}`); + if (service.devServer === true) { + yield* descriptor.reserve?.(ctx, provisioned, serialized) ?? Effect.void; + } else { + yield* descriptor.deploy(ctx, provisioned, artifact, serialized); + } + } + }) as Effect.Effect, + ), + ); + + interface Echo { + readonly pid: number; + readonly keys: Record; + } + + const portOf = (address: string): number => { + const records = JSON.parse( + fs.readFileSync(path.join(devDir, 'emulator-instances.json'), 'utf8'), + ); + const port = records?.apps?.[APP]?.nodes?.[address]?.port; + if (typeof port !== 'number') throw new Error(`no instance recorded for ${address}`); + return port; + }; + + const echo = async (address: string): Promise => { + const deadline = Date.now() + 15_000; + while (true) { + try { + const response = await fetch(`http://127.0.0.1:${String(portOf(address))}`); + const body = (await response.json()) as Echo & { address: string }; + if (body.address === address) return body; + } catch {} + if (Date.now() > deadline) throw new Error(`${address} never answered`); + await new Promise((resolve) => setTimeout(resolve, 100)); + } + }; + + const envJson = (): Record => { + const file = path.join(devDir, 'env.json'); + return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : {}; + }; + + test("a service that runs its artifact boots with its deployment's keys, a null left out, and nothing in env.json", async () => { + await converge([ + { address: 'devapp.a', upstream: 'http://up.local' }, + { address: 'devapp.b' }, + ]); + + const a = await echo('devapp.a'); + const b = await echo('devapp.b'); + expect(a.keys['COMPOSER_DEVAPP_A_UPSTREAM_URL']).toBe('http://up.local'); + expect(a.keys['COMPOSER_DEVAPP_A_PORT']).toBe(String(portOf('devapp.a'))); + expect('COMPOSER_DEVAPP_B_UPSTREAM_URL' in b.keys).toBe(false); + expect('COMPOSER_DEVAPP_A_STREAMS_API_KEY' in a.keys).toBe(false); + expect(Object.keys(a.keys).every((key) => key.startsWith('COMPOSER_DEVAPP_A_'))).toBe(true); + expect(envJson()).toEqual({}); + }, 60_000); + + test('a changed value, an added key and a key turned to null each restart only the service that reads it; an unchanged converge restarts nothing', async () => { + await converge([ + { address: 'devapp.a', upstream: 'http://one.local' }, + { address: 'devapp.b' }, + ]); + const first = { a: await echo('devapp.a'), b: await echo('devapp.b') }; + + await converge([ + { address: 'devapp.a', upstream: 'http://one.local' }, + { address: 'devapp.b' }, + ]); + const unchanged = { a: await echo('devapp.a'), b: await echo('devapp.b') }; + expect(unchanged.a.pid).toBe(first.a.pid); + expect(unchanged.b.pid).toBe(first.b.pid); + + await converge([ + { address: 'devapp.a', upstream: 'http://two.local' }, + { address: 'devapp.b' }, + ]); + const changed = { a: await echo('devapp.a'), b: await echo('devapp.b') }; + expect(changed.a.pid).not.toBe(first.a.pid); + expect(changed.a.keys['COMPOSER_DEVAPP_A_UPSTREAM_URL']).toBe('http://two.local'); + expect(changed.b.pid).toBe(first.b.pid); + + await converge([ + { address: 'devapp.a', upstream: 'http://two.local' }, + { address: 'devapp.b', upstream: 'http://added.local' }, + ]); + const added = { a: await echo('devapp.a'), b: await echo('devapp.b') }; + expect(added.a.pid).toBe(changed.a.pid); + expect(added.b.pid).not.toBe(changed.b.pid); + expect(added.b.keys['COMPOSER_DEVAPP_B_UPSTREAM_URL']).toBe('http://added.local'); + + await converge([ + { address: 'devapp.a' }, + { address: 'devapp.b', upstream: 'http://added.local' }, + ]); + const nulled = { a: await echo('devapp.a'), b: await echo('devapp.b') }; + expect(nulled.a.pid).not.toBe(added.a.pid); + expect('COMPOSER_DEVAPP_A_UPSTREAM_URL' in nulled.a.keys).toBe(false); + expect(nulled.b.pid).toBe(added.b.pid); + }, 120_000); + + test('a dev server gets its rows in env.json, and none for a key sent as null', async () => { + await converge([{ address: 'devapp.a', devServer: true }]); + + const rows = envJson(); + expect(Object.values(rows).every((value) => typeof value === 'string')).toBe(true); + expect(Object.keys(rows).sort()).toEqual(['COMPOSER_DEVAPP_A_PORT']); + expect(await devServerRows(devDir, 'devapp.a')).toEqual(rows); + }, 60_000); + + test('a service that switches from its artifact to a dev server reads only the rows reserve wrote', async () => { + await converge([{ address: 'devapp.a', upstream: 'http://artifact.local' }]); + expect(envJson()).toEqual({}); + + await converge([{ address: 'devapp.a', devServer: true }]); + + const rows = await devServerRows(devDir, 'devapp.a'); + expect(Object.keys(rows).sort()).toEqual(['COMPOSER_DEVAPP_A_PORT']); + expect(envJson()).toEqual(rows); + }, 60_000); + + test("a service that switches from a dev server to its artifact boots without the dev server's rows, which leave env.json", async () => { + await converge([{ address: 'devapp.a', devServer: true, upstream: 'http://dev.local' }]); + expect(envJson()).toHaveProperty('COMPOSER_DEVAPP_A_UPSTREAM_URL', 'http://dev.local'); + + await converge([{ address: 'devapp.a' }]); + + const a = await echo('devapp.a'); + expect('COMPOSER_DEVAPP_A_UPSTREAM_URL' in a.keys).toBe(false); + expect(envJson()).toEqual({}); + }, 60_000); + }, +); diff --git a/packages/1-prisma-cloud/1-extensions/target/src/__tests__/orm-postgres-ordering.test.ts b/packages/1-prisma-cloud/1-extensions/target/src/__tests__/orm-postgres-ordering.test.ts index a5706a22f..bbe85c191 100644 --- a/packages/1-prisma-cloud/1-extensions/target/src/__tests__/orm-postgres-ordering.test.ts +++ b/packages/1-prisma-cloud/1-extensions/target/src/__tests__/orm-postgres-ordering.test.ts @@ -1,24 +1,29 @@ /** - * What a consumer of a `postgres()` database waits for, against the REAL - * Output machinery and the real resource constructors (no cloud, nothing - * applies). Every consumer reads the database through the lowering's `url` - * output — its environment row writes it and its deployment's triggers carry - * it — so whatever `url` references is what Alchemy schedules them after. + * What a consumer of a `postgres()` database waits for, against the REAL Output machinery and the real resource + * constructors (no cloud, nothing applies): the url reaches the consumer's deployment through its `variables`. */ import { describe, expect, test } from 'bun:test'; import * as path from 'node:path'; -import * as Prisma from '@alchemy.run/prisma'; import type { LowerContext, LoweredResult } from '@internal/core/deploy'; import * as Output from 'alchemy/Output'; import { Stack } from 'alchemy/Stack'; import * as Effect from 'effect/Effect'; -import * as Redacted from 'effect/Redacted'; +import { compute } from '../compute.ts'; +import { computeDescriptor } from '../descriptors/compute.ts'; import { postgresDescriptor } from '../descriptors/orm-postgres.ts'; +import { rawPostgres } from '../exports/index.ts'; import { dataContract, postgres } from '../exports/orm.ts'; import widgetContractJson from './fixtures/widget-contract/emitted/contract.json' with { type: 'json', }; +const build = { + extension: '@prisma/composer/node', + type: 'node', + module: 'file:///test/service.ts', + entry: 'server.js', +}; + /** A stack the resource constructors register into; nothing ever applies it. */ const stack = { name: 'shop', stage: 'prod', resources: {}, bindings: {}, actions: {} }; @@ -69,19 +74,43 @@ describe("the postgres lowering's url — what every consumer is scheduled after expect(resolved).toBe('postgres://pndata'); }); - test("a consumer's environment row built from the url waits for the migration", () => { - const url = outputs['url'] as Output.Output; - // Built the way the compute descriptor builds a dependency-input row. - const row = Effect.runSync( + test("a consumer's deployment, created with the url in its variables, waits for the migration", async () => { + const consumer = compute({ name: 'widgets', deps: { db: rawPostgres() }, build }); + const consumerCtx = { + ...ctx, + id: 'shop.widgets', + address: 'shop.widgets', + node: consumer, + graph: { root: { id: 'shop' }, edges: [], nodes: [], inputBindings: [] }, + lowered: new Map(), + provisioned: new Map(), + } as unknown as LowerContext; + const descriptor = computeDescriptor(() => ({ + workspaceId: 'ws_1', + providerParams: new Map(), + })); + + await Effect.runPromise( registered( - Prisma.EnvironmentVariable('shop.widgets.env.COMPOSER_SHOP_WIDGETS_DB_URL', { - project: 'proj-1', - class: 'production', - key: 'COMPOSER_SHOP_WIDGETS_DB_URL', - value: Output.map(url, Redacted.make), - }), + Effect.gen(function* () { + const provisioned = yield* descriptor.provision(consumerCtx); + const serialized = yield* descriptor.serialize(consumerCtx, provisioned, { + service: { port: 3000 }, + inputs: { db: { url: outputs['url'] } }, + }); + yield* descriptor.deploy( + consumerCtx, + provisioned, + { path: '/tmp/widgets.tar.gz', sha256: 'sha-widgets' }, + serialized, + ); + }) as Effect.Effect, ), ); - expect(Object.keys(Output.upstreamAny(row.Props))).toContain('shop.pndata.migration'); + + const deployment = (stack.resources as Record)[ + 'shop.widgets.deployment' + ]; + expect(Object.keys(Output.upstreamAny(deployment?.Props))).toContain('shop.pndata.migration'); }); }); diff --git a/packages/1-prisma-cloud/1-extensions/target/src/__tests__/preflight.test.ts b/packages/1-prisma-cloud/1-extensions/target/src/__tests__/preflight.test.ts index a57923b68..20969f66f 100644 --- a/packages/1-prisma-cloud/1-extensions/target/src/__tests__/preflight.test.ts +++ b/packages/1-prisma-cloud/1-extensions/target/src/__tests__/preflight.test.ts @@ -867,149 +867,6 @@ describe('the deploy check reads which variables exist and sets none', () => { }); }); -describe('runPreflight — a COMPOSER_ key that changes owner in the move to full addresses (ADR-0057)', () => { - const clashGraph = () => - Load( - module('shop', ({ provision }) => { - provision(compute({ name: 'x', deps: {}, build }), { id: 'x' }); - provision( - module('shop', ({ provision: p }) => { - p(compute({ name: 'x', deps: {}, build }), { id: 'x' }); - }), - { id: 'shop' }, - ); - }), - ); - const row = (key: string): Row => ({ - projectId: 'proj', - class: 'preview', - key, - branchId: 'br_1', - }); - let state: FakeState; - - beforeEach(() => { - state = { gets: [], posts: [], rows: [] }; - }); - - const preflight = () => - preflightWith( - { graph: clashGraph(), container: fakeContainer('proj', 'br_1'), environment: 'pr-1' }, - { client: fakeClient(state) }, - ); - - test('fails before any resource changes while the old owner still holds the key', async () => { - state.rows = [row('COMPOSER_SHOP_X_ORIGIN')]; - - const error = await preflight().catch((e: unknown) => e); - - expect(error).toBeInstanceOf(Error); - expect(String(error)).toContain( - 'COMPOSER_SHOP_X_ORIGIN belongs to "shop.shop.x" from the previous Composer release. ' + - 'This release writes it for "shop.x"', - ); - expect(String(error)).toContain( - "prisma project env delete 'COMPOSER_SHOP_X_ORIGIN' --project 'proj' --branch 'pr-1'", - ); - expect(state.posts).toEqual([]); - }); - - test('quotes the environment so the printed command is safe to paste', async () => { - state.rows = [row('COMPOSER_SHOP_X_ORIGIN')]; - - const error = await preflightWith( - { - graph: clashGraph(), - container: fakeContainer('proj', 'br_1'), - environment: `it's "$HOME" x`, - }, - { client: fakeClient(state) }, - ).catch((e: unknown) => e); - - expect(String(error)).toContain(`--branch 'it'\\''s "$HOME" x'`); - }); - - test('passes once that variable is deleted', async () => { - await preflight(); - }); - - test("passes after the move, when the old owner's row has its new key", async () => { - state.rows = [row('COMPOSER_SHOP_X_ORIGIN'), row('COMPOSER_SHOP_SHOP_X_ORIGIN')]; - - await preflight(); - }); - - test('ignores a row with that key in another scope', async () => { - state.rows = [{ ...row('COMPOSER_SHOP_X_ORIGIN'), branchId: null }]; - - await preflight(); - }); -}); - -describe('runPreflight — a chain of COMPOSER_ keys that change owner', () => { - /** `shop.x`, `shop.shop.x` and `shop.shop.shop.x`: each node's new key is the next one's old key. */ - const chainGraph = () => - Load( - module('shop', ({ provision }) => { - provision(compute({ name: 'x', deps: {}, build }), { id: 'x' }); - provision( - module('shop', ({ provision: p }) => { - p(compute({ name: 'x', deps: {}, build }), { id: 'x' }); - p( - module('shop', ({ provision: q }) => { - q(compute({ name: 'x', deps: {}, build }), { id: 'x' }); - }), - { id: 'shop' }, - ); - }), - { id: 'shop' }, - ); - }), - ); - const row = (key: string): Row => ({ - projectId: 'proj', - class: 'production', - key, - branchId: null, - }); - const preflight = (state: FakeState) => - preflightWith( - { - graph: chainGraph(), - container: fakeContainer('proj', undefined), - environment: 'production', - }, - { client: fakeClient(state) }, - ); - - test('reports every link in one run', async () => { - const state: FakeState = { - gets: [], - posts: [], - rows: [row('COMPOSER_SHOP_X_ORIGIN'), row('COMPOSER_SHOP_SHOP_X_ORIGIN')], - }; - - const message = String(await preflight(state).catch((e: unknown) => e)); - - expect(message).toContain('COMPOSER_SHOP_X_ORIGIN belongs to "shop.shop.x"'); - expect(message).toContain('COMPOSER_SHOP_SHOP_X_ORIGIN belongs to "shop.shop.shop.x"'); - }); - - test('passes once every node has moved', async () => { - const state: FakeState = { - gets: [], - posts: [], - rows: [ - row('COMPOSER_SHOP_X_ORIGIN'), - row('COMPOSER_SHOP_SHOP_X_ORIGIN'), - row('COMPOSER_SHOP_SHOP_SHOP_X_ORIGIN'), - ], - }; - - await preflight(state); - }); -}); - describe('preflight names', () => { test('a secret source that is not a platform variable fails preflight, naming the place and the service', async () => { const graph = Load( diff --git a/packages/1-prisma-cloud/1-extensions/target/src/__tests__/resource-ids.test.ts b/packages/1-prisma-cloud/1-extensions/target/src/__tests__/resource-ids.test.ts index c7e2c7484..78b247459 100644 --- a/packages/1-prisma-cloud/1-extensions/target/src/__tests__/resource-ids.test.ts +++ b/packages/1-prisma-cloud/1-extensions/target/src/__tests__/resource-ids.test.ts @@ -2,14 +2,10 @@ import { describe, expect, test } from 'bun:test'; import { RenamePolicy } from 'alchemy/Rename'; import * as Effect from 'effect/Effect'; import * as Option from 'effect/Option'; -import { configKey } from '../config-key.ts'; import { addressBelowApp, fromLegacyId, - legacyConfigKey, - legacyEnvVarId, legacyGeneratedParamId, - legacyGeneratedParamVarName, legacyInputKey, legacyNodeResourceId, legacyServiceKeyId, @@ -73,36 +69,10 @@ describe('legacy resource IDs', () => { ); }); - test('legacyEnvVarId is the key and `-var`', () => { - expect(legacyEnvVarId('COMPOSER_WEB_PORT')).toBe('COMPOSER_WEB_PORT-var'); - }); - - test('legacyConfigKey builds the key from the address below the app, for both owners', () => { - expect(legacyConfigKey('shop', 'shop.web', { owner: 'service', name: 'port' })).toBe( - 'COMPOSER_WEB_PORT', - ); - expect( - legacyConfigKey('my-shop', 'my-shop.auth.api', { owner: { input: 'db' }, name: 'url' }), - ).toBe('COMPOSER_AUTH_API_DB_URL'); - }); - - test("a module named like the app makes a node's new key equal another node's old key", () => { - const port = { owner: 'service', name: 'port' } as const; - // The upgrade deploy of such an app fails with a conflict on this key and deletes nothing (ADR-0057). - expect(configKey('shop.x', port)).toBe(legacyConfigKey('shop', 'shop.shop.x', port)); - expect(configKey('shop.x', port)).toBe('COMPOSER_SHOP_X_PORT'); - }); - test('legacyInputKey is the input row key below the app', () => { expect(legacyInputKey('shop', 'shop.auth.api')).toBe('COMPOSER_AUTH_API_INPUT'); }); - test('legacyGeneratedParamVarName is the generated leaf variable below the app', () => { - expect(legacyGeneratedParamVarName('shop', 'shop.web', 'stripe.key')).toBe( - 'COMPOSER_WEB_STRIPE_KEY_GENERATED', - ); - }); - test('legacyGeneratedParamId is the legacy input key, the path and `-generated`', () => { expect(legacyGeneratedParamId('shop', 'shop.web', 'secret')).toBe( 'COMPOSER_WEB_INPUT:secret-generated', diff --git a/packages/1-prisma-cloud/1-extensions/target/src/control/extension.ts b/packages/1-prisma-cloud/1-extensions/target/src/control/extension.ts index 36699d6d4..a1da68bf9 100644 --- a/packages/1-prisma-cloud/1-extensions/target/src/control/extension.ts +++ b/packages/1-prisma-cloud/1-extensions/target/src/control/extension.ts @@ -48,6 +48,7 @@ import { RESERVED_PROVIDER_PARAMS } from '../provider-params.ts'; import { prismaCloudReporter } from '../reporting/reporter.ts'; import { resourceId } from '../resource-ids.ts'; import { S3CredentialsProvider } from '../s3-credentials-resource.ts'; +import { SentVariableNamesProvider } from '../sent-variable-names-resource.ts'; import type { ProviderParamEntry } from '../serializer.ts'; import { STREAMS_API_KEY } from '../streams-keys.ts'; import { serializeDeployPreflightPayload } from './preflight-payload.ts'; @@ -330,6 +331,7 @@ export const prismaCloud = (opts: PrismaCloudOptions = {}): ExtensionDescriptor OrmMigrationProvider(), S3CredentialsProvider(), GeneratedParamProvider(), + SentVariableNamesProvider(), Prisma.ServiceKeyProvider(), ), ), diff --git a/packages/1-prisma-cloud/1-extensions/target/src/descriptors/compute.ts b/packages/1-prisma-cloud/1-extensions/target/src/descriptors/compute.ts index 81fee7110..2feb96b34 100644 --- a/packages/1-prisma-cloud/1-extensions/target/src/descriptors/compute.ts +++ b/packages/1-prisma-cloud/1-extensions/target/src/descriptors/compute.ts @@ -2,6 +2,7 @@ import * as Prisma from '@alchemy.run/prisma'; import type { ServiceLowering } from '@internal/core/deploy'; +import { CliStructuredError } from '@internal/foundation/errors'; import { describeDocument, type PlatformMarkerUse } from '@internal/input-document'; import { ARTIFACT_CONTENT_TYPE, appAfter, packageComputeArtifact } from '@internal/lowering'; import * as Output from 'alchemy/Output'; @@ -12,15 +13,13 @@ import { preflightView } from '../control/preflight-payload.ts'; import { GeneratedParam } from '../generated-param-resource.ts'; import { fromLegacyId, - legacyConfigKey, - legacyEnvVarId, legacyGeneratedParamId, - legacyGeneratedParamVarName, - legacyInputKey, legacyNodeResourceId, } from '../legacy-resource-ids.ts'; +import { RESERVED_PROVIDER_PARAMS } from '../provider-params.ts'; import { provisionedEdges } from '../provisioned-edges.ts'; import { resourceId } from '../resource-ids.ts'; +import { SentVariableNames } from '../sent-variable-names-resource.ts'; import { encode, type InputDocumentRow, paramEntries, serializeInput } from '../serializer.ts'; import { asOwnRow, @@ -28,6 +27,7 @@ import { logicalIdProp, projectIdOf, type ResolvedCloudOptions, + SERVICE_VARIABLE_LIMIT, type ServiceProvisionedAttributes, validatePlatformName, variableClassAndBranch, @@ -54,34 +54,21 @@ export interface ComputeProvisioned { readonly endpointDomain: Output.Output; } -/** compute's serialize → deploy handoff: the env-var rows deploy must depend on, the deployment's replacement triggers, the resolved port it routes to, and the serialized input document (when the service declares one) for the deploy report. */ +/** A service variable's value: `Redacted` keeps it out of logs, though Alchemy writes it to deploy state in plain text. It may still be an unresolved deploy-time reference. */ +type ServiceVariableValue = Redacted.Redacted | Output.Output>; + +/** compute's serialize → deploy handoff. */ export interface ComputeSerialized { - readonly environment: readonly Prisma.EnvironmentVariable[]; - /** - * What the deploy hook declares as `Prisma.Deployment.triggers` — one member - * per row of `environment`, carrying the SAME value the row writes (Redacted, - * possibly still an unresolved Output). The platform materializes env rows - * into a deployment only at create (PRO-211), so a changed value must replace - * the deployment; upstream compares a salted hash of these to plan that - * replacement. Alchemy also writes the members to its state as given, - * `Redacted` values in plain text included. Because upstream resolves the actual - * values, a value re-issued under a stable resource identity (a connection - * rotated in place, a re-minted service key) moves the fingerprint too. - */ - readonly triggers: Readonly>; + /** Every `COMPOSER_` key the service reads at boot, as its value or `null`. */ + readonly bootVariables: Readonly>; + /** What the create-deployment request carries: `bootVariables`, plus `null` for every name Composer no longer sends. */ + readonly requestVariables: Output.Output | null>>; /** Platform variables the service reads and Composer does not write; each joins the triggers as `:updatedAt`. */ readonly platformVariables: readonly string[]; readonly port: number; readonly input?: InputDocumentRow; } -/** - * Every env-var value goes to the platform wrapped in `Redacted`: the - * Management API never reads a value back, so alchemy persists the desired one - * in state to repair drift, and `Redacted` is what keeps it out of the - * serialized state row. A value that is still an unresolved deploy-time - * reference is wrapped inside the map, at the same point it becomes a string. - */ const envValue = ( value: string | Output.Output, ): Redacted.Redacted | Output.Output> => @@ -131,11 +118,44 @@ function isComputeProvisioned(value: unknown): value is ComputeProvisioned { return typeof value === 'object' && value !== null && 'endpointDomain' in value; } -/** One environment row and its trigger member: the resource AND the value it writes, so a row cannot exist without joining the deployment's replacement triggers. */ -interface EnvRow { - readonly record: Prisma.EnvironmentVariable; - readonly key: string; - readonly value: Redacted.Redacted | Output.Output>; +function withNamesNoLongerSentDeleted( + variables: Readonly>, + everSent: Output.Output, +): Output.Output | null>> { + const resolved: Record | null> = {}; + const pending: Output.Output]>[] = []; + for (const [key, value] of Object.entries(variables)) { + if (Output.isOutput(value)) pending.push(Output.map(value, (v) => [key, v] as const)); + else resolved[key] = value; + } + return Output.map(Output.all(everSent, Output.all(...pending)), ([names, entries]) => ({ + ...Object.fromEntries(names.map((name) => [name, null])), + ...resolved, + ...Object.fromEntries(entries), + })); +} + +function checkServiceVariableCount( + address: string, + variables: Readonly>, + local: boolean, +): void { + const count = Object.values(variables).filter((value) => value !== null).length; + if (count <= SERVICE_VARIABLE_LIMIT) return; + throw new CliStructuredError( + 'DEPLOY.SERVICE_VARIABLE_LIMIT', + `The service "${address}" needs ${count} variables, but Prisma Cloud stores at most ${SERVICE_VARIABLE_LIMIT} on one service.`, + { + why: + `Composer sends one variable for each of the service's params, dependency connection values and generated values, ` + + `and the app declares ${count} for "${address}". ` + + (local + ? '`prisma dev` refuses it as a deploy to Prisma Cloud would, before it starts or changes anything locally.' + : "No resource has been created, changed or deleted; the branch's application topology has already been replaced and the build recorded."), + fix: `Give "${address}" fewer dependencies or generated values, for example by splitting it into two services.`, + meta: { address, count, limit: SERVICE_VARIABLE_LIMIT }, + }, + ); } const sortedMarkerNames = (markers: readonly PlatformMarkerUse[]): string[] => @@ -186,30 +206,18 @@ export function computeDescriptor( Effect.gen(function* () { const { address, node, graph } = ctx; const app = graph.root.id; - const classAndBranch = variableClassAndBranch(ctx.application); - const projectId = provisioned.projectId; if (node.kind !== 'service') { throw new Error(`prisma-cloud: cannot serialize non-service node "${address}".`); } const svc = node; - const rows: EnvRow[] = []; + // A key left out keeps the value an earlier deploy stored on the service, so every key boot reads is sent, as `null` when it has no value. + const bootVariables: Record = {}; for (const d of paramEntries(svc)) { const value = d.owner === 'service' ? config.service[d.name] : config.inputs[d.owner.input]?.[d.name]; - // An unprovisioned optional connection param has no value yet — write - // no row (boot's coerce() reads a missing var as absent → undefined). - // Mirrors stash(), keeping writer and reader consistent. - if (value === undefined) continue; - const key = configKey(address, d); - const wrapped = envValue(encode(d.owner, value)); - const record = yield* Prisma.EnvironmentVariable(resourceId(address, 'env', key), { - project: projectId, - key, - value: wrapped, - ...classAndBranch, - }).pipe(asOwnRow, fromLegacyId(legacyEnvVarId(legacyConfigKey(app, address, d)))); - rows.push({ record, key, value: wrapped }); + bootVariables[configKey(address, d)] = + value === undefined ? null : envValue(encode(d.owner, value)); } const inputRow = serializeInput( @@ -218,63 +226,22 @@ export function computeDescriptor( graph.inputBindings.find((b) => b.serviceAddress === address)?.binding, { absentVariables: preflightView(ctx.preflight).absentVariables }, ); - if (inputRow !== undefined) { - // Each generated leaf: generate its value ONCE (the resource keeps it - // stable across redeploys via its persisted output) and provision it - // under the framework var the document's `$generated` pointer names. - // The resource id is stable per service+leaf so reconcile finds the - // existing value instead of regenerating. - for (const leaf of inputRow.generated) { - // References the target's App, not its Deployment, so its consumers form no cycle. - const value = - leaf.origin !== undefined - ? originOf(ctx.services, leaf.origin, address) - : (yield* GeneratedParam(resourceId(address, 'generated', leaf.path), { - bytes: leaf.bytes, - }).pipe(fromLegacyId(legacyGeneratedParamId(app, address, leaf.path)))).value; - // The generated value is mint-once-stable (the resource returns - // its persisted output), so this trigger member holds still across - // redeploys and moves exactly when the value is re-generated. - const generatedValue = envValue(value); - rows.push({ - record: yield* Prisma.EnvironmentVariable(resourceId(address, 'env', leaf.varName), { - project: projectId, - key: leaf.varName, - value: generatedValue, - ...classAndBranch, - }).pipe( - asOwnRow, - fromLegacyId(legacyEnvVarId(legacyGeneratedParamVarName(app, address, leaf.path))), - ), - key: leaf.varName, - value: generatedValue, - }); - } + for (const leaf of inputRow?.generated ?? []) { + // References the target's App, not its Deployment, so its consumers form no cycle. + const value = + leaf.origin !== undefined + ? originOf(ctx.services, leaf.origin, address) + : (yield* GeneratedParam(resourceId(address, 'generated', leaf.path), { + bytes: leaf.bytes, + }).pipe(fromLegacyId(legacyGeneratedParamId(app, address, leaf.path)))).value; + bootVariables[leaf.varName] = envValue(value); } - // ADR-0031: this node's own faceted inputs already got their edge's - // key above, through the generic param loop — core's buildConfig - // fills a provisioned param like any other, so there is no - // consumer-side special case left to write here. - - // Provider side (ADR-0031). Compute never names a brand — it looks - // one up. Two kinds of registered entries: - // - // · Edge-derived (`value(refs)`) — driven by the PROVIDER, not by - // its edges: asked even with no inbound edge for that brand, - // because "no edges" and "no var" are not the same thing — an - // absent var reads as "never provisioned" (local dev, tests), so - // a deployed provider with zero wired consumers must still be - // able to emit a deny-everything value. Whether an empty set - // means deny-all or emit-nothing is that param's own call, so it - // may return undefined to write no row at all. The expose check - // is main's and stays for these: a service that exposes nothing - // can never be any binding's provider. - // - // · Service-derived (`valueForService(provisioned, address)`) — - // derived from this service's OWN provisioned attributes (e.g. - // its origin), so EVERY compute service is asked, exposing or - // not; the expose check does not apply. + // Reserved provider params (ADR-0031): an edge-derived one is asked only of a service that exposes something, + // a service-derived one (such as the origin) of every service; one with no value is sent as `null`. + for (const entry of RESERVED_PROVIDER_PARAMS) { + bootVariables[configKey(address, { owner: 'service', name: entry.name })] = null; + } const exposes = svc.expose !== undefined && Object.keys(svc.expose).length > 0; const refsByBrand = new Map(); if (exposes) { @@ -295,47 +262,30 @@ export function computeDescriptor( ? entry.value(refsByBrand.get(brand) ?? []) : undefined; if (raw === undefined) continue; - const key = configKey(address, { owner: 'service', name: entry.name }); - // The value may still be an unresolved deploy-time Output (a - // minted key or the provisioned endpoint domain isn't known until - // Alchemy applies it) or already a plain value (e.g. a zero-refs - // deny-all literal) — either way it is JSON-encoded through the - // same `encode` a declared param's own literal takes, never a - // brand-invented format. + // JSON-encoded through the same `encode` a declared param's own literal takes, never a brand-invented format. const value = Output.isOutput(raw) ? Output.map(raw, (v) => encode('service', v)) : encode('service', raw); - // May be a minted key (rpc, streams). Redacted keeps it out of logs; - // Alchemy state still stores it in plain text, on the row and the - // trigger member. - const providerValue = envValue(value); - rows.push({ - record: yield* Prisma.EnvironmentVariable(resourceId(address, 'env', key), { - project: projectId, - key, - value: providerValue, - ...classAndBranch, - }).pipe( - asOwnRow, - fromLegacyId( - legacyEnvVarId( - legacyConfigKey(app, address, { owner: 'service', name: entry.name }), - ), - ), - ), - key, - value: providerValue, - }); + bootVariables[configKey(address, { owner: 'service', name: entry.name })] = + envValue(value); } + checkServiceVariableCount( + address, + bootVariables, + cloudApplicationOf(ctx.application).branchless, + ); + const everSent = yield* SentVariableNames(resourceId(address, 'sent-variable-names'), { + names: Object.keys(bootVariables).sort(), + }); + // Carries the resolved port to deploy(); falls back to 3000 if unset. // This is the only place the raw, untyped config is read, so it is the // only place the fallback belongs — from here on `port` is a number. const port = typeof config.service['port'] === 'number' ? config.service['port'] : 3000; return { - environment: rows.map((r) => r.record), - // Keys are unique per row (one env var each), so no member collides. - triggers: Object.fromEntries(rows.map((r) => [r.key, r.value])), + bootVariables, + requestVariables: withNamesNoLongerSentDeleted(bootVariables, everSent.names), platformVariables: inputRow !== undefined ? sortedMarkerNames(inputRow.markers) : [], port, ...(inputRow !== undefined ? { input: inputRow } : {}), @@ -360,40 +310,32 @@ export function computeDescriptor( deploy: ({ id, address, graph, lowered, preflight }, provisioned, artifact, serialized) => Effect.gen(function* () { - // Only to order this deployment after its producers are live; their values reach it through the rows and triggers. + // Only to order this deployment after its producers are live; their values reach it through `variables`. const producerOutputs = graph.edges .filter((edge) => edge.kind === 'dependency' && edge.to === id) .flatMap((edge) => Object.values(lowered.get(edge.from) ?? {})) .filter(Output.isOutput); const { platformVariableVersion } = preflightView(preflight); - // Env keys never contain ':', so a `:updatedAt` member cannot - // collide with a row's own trigger member. The key name is historical: - // under `prisma dev` the member holds an HMAC of the value, and - // renaming it would redeploy every hosted deployment once. - const triggers = { - ...serialized.triggers, - ...Object.fromEntries( - serialized.platformVariables.map((name) => [ - `${name}:updatedAt`, - platformVariableVersion(name) ?? '?', - ]), - ), - }; + const triggers = Object.fromEntries( + serialized.platformVariables.map((name) => [ + `${name}:updatedAt`, + platformVariableVersion(name) ?? '?', + ]), + ); const app = graph.root.id; const deployment = yield* Prisma.Deployment(resourceId(address, 'deployment'), { // `app` carries the ordering edges as well as the app id — see // `appAfter` for why it is the only prop that can. - app: appAfter(provisioned.serviceId, serialized.environment, producerOutputs), + app: appAfter(provisioned.serviceId, producerOutputs), artifactPath: artifact.path, // The artifact IS a gzipped tar (see @internal/lowering's packager); // upstream sends this as the upload's Content-Type and folds it into // the fingerprint that decides whether a new deployment is needed. artifactContentType: ARTIFACT_CONTENT_TYPE, - // Upstream plans a replacement exactly when a member moved (or cannot - // be proven unmoved), because the platform materializes env rows into - // a deployment only at create (PRO-211). Alchemy writes the members - // to its state as given. + // A changed platform variable replaces the deployment: the platform + // copies variables into a deployment only when it is created. triggers, + variables: serialized.requestVariables, // Route to the port the app actually binds (the service's `port` // param, resolved by serialize) — not a hardcoded constant. portMapping: { http: serialized.port }, @@ -425,19 +367,31 @@ export function computeDescriptor( }), // ADR-0056: a service that runs its build adapter's dev server under - // `prisma dev` has no artifact. What `deploy` returns, with the - // `Deployment` removed. With no artifact to carry it, the input document - // is a variable. - reserve: ({ address, application, graph }, provisioned, serialized) => + // `prisma dev` has no artifact and no deployment to carry its variables, + // so its values and its input document are local rows, read by the dev + // server. + reserve: ({ address, application }, provisioned, serialized) => Effect.gen(function* () { - const { input } = serialized; - if (input !== undefined) { - yield* Prisma.EnvironmentVariable(resourceId(address, 'env', input.key), { + if (!cloudApplicationOf(application).branchless) { + throw new Error( + `prisma-cloud: the dev server of "${address}" was reserved outside \`prisma dev\`. ` + + 'Variable rows are written only to the local application; this is a bug in Composer.', + ); + } + const rows: Record = {}; + for (const [key, value] of Object.entries(serialized.bootVariables)) { + if (value !== null) rows[key] = value; + } + if (serialized.input !== undefined) { + rows[serialized.input.key] = envValue(serialized.input.value); + } + for (const [key, value] of Object.entries(rows)) { + yield* Prisma.EnvironmentVariable(resourceId(address, 'env', key), { project: provisioned.projectId, - key: input.key, - value: envValue(input.value), + key, + value, ...variableClassAndBranch(application), - }).pipe(asOwnRow, fromLegacyId(legacyEnvVarId(legacyInputKey(graph.root.id, address)))); + }); } const url = endpointDomainOf(provisioned, address); return { diff --git a/packages/1-prisma-cloud/1-extensions/target/src/descriptors/shared.ts b/packages/1-prisma-cloud/1-extensions/target/src/descriptors/shared.ts index bd168c8f6..f62b87cb4 100644 --- a/packages/1-prisma-cloud/1-extensions/target/src/descriptors/shared.ts +++ b/packages/1-prisma-cloud/1-extensions/target/src/descriptors/shared.ts @@ -94,6 +94,9 @@ const PLATFORM_NAME_LIMITS = { Bucket: { min: 1, max: 100 }, } as const; +/** The most variables the platform stores on one service; a `null` deletes a key and is not counted. */ +export const SERVICE_VARIABLE_LIMIT = 50; + /** * Checks that the platform can hold the node's address as the name of its `kind` row (ADR-0057). * Fails naming the address and the limit; a name is never shortened or padded. @@ -172,13 +175,7 @@ export function logicalIdProp( return cloudApplicationOf(application).branchless ? {} : { logicalId: address }; } -/** - * Declares one of the app's own App, Database, Bucket or `COMPOSER_` variable rows. On the app's - * Project and branch, the row holding a node's logicalId (or a variable's key) is that node's row, - * so a deploy resuming an interrupted create uses it instead of refusing it (ADR-0057). Only for - * resources declared with their identity: `logicalIdProp` on App, Database and Bucket, a - * `COMPOSER_` key on variables. Without one, upstream falls back to matching by display name. - */ +/** Adopts the row holding the node's `logicalId` on the app's Project and branch, so a resumed create uses it (ADR-0057). Only for App, Database and Bucket declared with `logicalIdProp`. */ export const asOwnRow = adopt(true); /** diff --git a/packages/1-prisma-cloud/1-extensions/target/src/env-key-clash.ts b/packages/1-prisma-cloud/1-extensions/target/src/env-key-clash.ts deleted file mode 100644 index e16a55354..000000000 --- a/packages/1-prisma-cloud/1-extensions/target/src/env-key-clash.ts +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Finds the `COMPOSER_` keys that the move to full addresses (ADR-0057) gives two rows: the new - * key of one row is the key the previous release wrote for another. Within one format keys are - * distinct; across the two they can meet, because every key is upper-cased and `-` becomes `_`. - * Delete this file with `legacy-resource-ids.ts`. - */ -import type { Graph, ServiceNode } from '@internal/core'; -import { INPUT_KEY_NAME } from '@internal/input-document'; -import { configKey } from './config-key.ts'; -import { addressBelowApp } from './legacy-resource-ids.ts'; -import { RESERVED_PROVIDER_PARAMS } from './provider-params.ts'; -import { generatedParamVarName, paramEntries, serializeInput } from './serializer.ts'; - -export interface EnvKeyClash { - /** The variable both rows are written under. */ - readonly key: string; - /** The node whose new row has this key. */ - readonly newOwner: string; - /** The node whose row had this key under the previous release. */ - readonly oldOwner: string; - /** The key the old owner's row moves to in the same deploy. */ - readonly oldOwnerNewKey: string; -} - -interface Row { - readonly address: string; - readonly newKey: string; - readonly oldKey: string; -} - -/** Every `COMPOSER_` row a service can have, each under both its new and its old key. */ -function rowsOf(node: ServiceNode, address: string, app: string, binding: unknown): Row[] { - const below = addressBelowApp(address, app); - const names: { owner: 'service' | { input: string }; name: string }[] = [ - ...paramEntries(node), - { owner: 'service', name: INPUT_KEY_NAME }, - ...RESERVED_PROVIDER_PARAMS.map(({ name }) => ({ owner: 'service' as const, name })), - ]; - const rows = names.map((d) => ({ - address, - newKey: configKey(address, d), - oldKey: configKey(below, d), - })); - const generated = serializeInput(node, address, binding)?.generated ?? []; - for (const { path } of generated) { - rows.push({ - address, - newKey: generatedParamVarName(address, path), - oldKey: generatedParamVarName(below, path), - }); - } - return rows; -} - -/** Every key that is one row's new key and a different row's old key. */ -export function findEnvKeyClashes(graph: Graph): readonly EnvKeyClash[] { - const app = graph.root.id; - const rows: Row[] = []; - for (const { id, node } of graph.nodes) { - if (node.kind !== 'service') continue; - const binding = graph.inputBindings.find((b) => b.serviceAddress === id)?.binding; - rows.push(...rowsOf(node, id, app, binding)); - } - const byOldKey = new Map(rows.map((row) => [row.oldKey, row])); - const clashes: EnvKeyClash[] = []; - for (const row of rows) { - const old = byOldKey.get(row.newKey); - if (old === undefined) continue; - clashes.push({ - key: row.newKey, - newOwner: row.address, - oldOwner: old.address, - oldOwnerNewKey: old.newKey, - }); - } - return clashes; -} diff --git a/packages/1-prisma-cloud/1-extensions/target/src/legacy-resource-ids.ts b/packages/1-prisma-cloud/1-extensions/target/src/legacy-resource-ids.ts index e1b43efd4..5673e4006 100644 --- a/packages/1-prisma-cloud/1-extensions/target/src/legacy-resource-ids.ts +++ b/packages/1-prisma-cloud/1-extensions/target/src/legacy-resource-ids.ts @@ -5,8 +5,7 @@ * Delete this file once no such environment remains. */ import { renamedFrom } from 'alchemy/Rename'; -import { configKey } from './config-key.ts'; -import { generatedParamVarName, inputKey } from './serializer.ts'; +import { inputKey } from './serializer.ts'; /** The address without its first segment, the app name: `shop.auth.api` in the app `shop` is `auth.api`. */ export function addressBelowApp(address: string, app: string): string { @@ -22,30 +21,11 @@ export function legacyNodeResourceId(app: string, address: string, suffix: strin return `${addressBelowApp(address, app)}-${suffix}`; } -/** An environment variable row: its old key, then `-var`. */ -export function legacyEnvVarId(legacyKey: string): string { - return `${legacyKey}-var`; -} - -/** The key a config row had when its address left out the app name. */ -export function legacyConfigKey( - app: string, - address: string, - d: Parameters[1], -): string { - return configKey(addressBelowApp(address, app), d); -} - /** The input document row's old key. */ export function legacyInputKey(app: string, address: string): string { return inputKey(addressBelowApp(address, app)); } -/** A generated input leaf's old variable name. */ -export function legacyGeneratedParamVarName(app: string, address: string, path: string): string { - return generatedParamVarName(addressBelowApp(address, app), path); -} - /** A generated input leaf's value: `:-generated`. */ export function legacyGeneratedParamId(app: string, address: string, path: string): string { return `${legacyInputKey(app, address)}:${path}-generated`; diff --git a/packages/1-prisma-cloud/1-extensions/target/src/local-target/attach.ts b/packages/1-prisma-cloud/1-extensions/target/src/local-target/attach.ts index 60e9b1c7b..5ab6e6b57 100644 --- a/packages/1-prisma-cloud/1-extensions/target/src/local-target/attach.ts +++ b/packages/1-prisma-cloud/1-extensions/target/src/local-target/attach.ts @@ -9,6 +9,7 @@ import type { LocalTargetAttachInput, LocalTargetAttachment } from '@internal/co import { computeClient } from '@internal/dev-emulators'; import { type AppScope, + devServerRows, directoryOf, ensureServiceInstance, materializeEnv, @@ -159,8 +160,8 @@ export async function devAttach(input: LocalTargetAttachInput): Promise { const { instance } = await ensureServiceInstance(scope, address); - const materialized = await materializeEnv( - input.devDir, + const materialized = materializeEnv( + await devServerRows(input.devDir, address), address, instance.port, configuration, diff --git a/packages/1-prisma-cloud/1-extensions/target/src/local-target/descriptor.ts b/packages/1-prisma-cloud/1-extensions/target/src/local-target/descriptor.ts index 0b9900e44..3ad46dd5c 100644 --- a/packages/1-prisma-cloud/1-extensions/target/src/local-target/descriptor.ts +++ b/packages/1-prisma-cloud/1-extensions/target/src/local-target/descriptor.ts @@ -19,6 +19,7 @@ import { GeneratedParamProvider } from '../generated-param-resource.ts'; import { LocalOrmMigrationProvider } from '../orm-migration-resource.ts'; import { PgWarmProvider } from '../pg-warm-resource.ts'; import { S3CredentialsProvider } from '../s3-credentials-resource.ts'; +import { SentVariableNamesProvider } from '../sent-variable-names-resource.ts'; import { devAttach } from './attach.ts'; import { devContainerDescriptor } from './container.ts'; import { runDevEmulators } from './emulators.ts'; @@ -49,6 +50,7 @@ export function localTargetDescriptor(): LocalTargetDescriptor { LocalOrmMigrationProvider(), S3CredentialsProvider(), GeneratedParamProvider(), + SentVariableNamesProvider(), Prisma.ServiceKeyProvider(), ), ), diff --git a/packages/1-prisma-cloud/1-extensions/target/src/preflight.ts b/packages/1-prisma-cloud/1-extensions/target/src/preflight.ts index 50cce3c70..445925866 100644 --- a/packages/1-prisma-cloud/1-extensions/target/src/preflight.ts +++ b/packages/1-prisma-cloud/1-extensions/target/src/preflight.ts @@ -18,7 +18,6 @@ import * as Effect from 'effect/Effect'; import * as Layer from 'effect/Layer'; import { prismaCloudContainerOf } from './container.ts'; import type { DeployPreflightPayload } from './control/preflight-payload.ts'; -import { type EnvKeyClash, findEnvKeyClashes } from './env-key-clash.ts'; import { mapWithConcurrency } from './map-with-concurrency.ts'; import { addReader, missingVariableNames, missingVariablesText } from './missing-variables-text.ts'; import { resolveOrmConfig } from './orm-config.ts'; @@ -115,72 +114,6 @@ async function readPlatformVariable( return { updatedAt, managedBySystem }; } -/** Whether `key` has a row in the scope Composer writes its own rows to: production, or the environment's branch. */ -async function composerRowExists( - client: ManagementApiClient, - projectId: string, - branchId: string | undefined, - key: string, -): Promise { - const cls = classFor(branchId); - let exists = false; - await drivePagesAsync( - `environment variables named "${key}"`, - async (cursor) => { - const res = await listEnvVars( - client, - cursor === undefined - ? { projectId, class: cls, key } - : { projectId, class: cls, key, cursor }, - ); - if (res.error !== undefined) throw listFailedError(key, res.error); - return res.data ?? { data: [], pagination: { nextCursor: null, hasMore: false } }; - }, - (data) => { - exists ||= data.some((row) => row.branchId === (branchId ?? null)); - return exists; - }, - ); - return exists; -} - -/** - * A clash blocks the deploy while the old owner's row still holds the key and has not moved to - * its new key yet. Before the move, the deploy would fail on that key partway through; after it, - * the key belongs to the new owner, and a new environment has neither row. The old owner's new key can - * itself be a third node's old key (`shop.x`, `shop.shop.x`, `shop.shop.shop.x`); a row there - * counts as moved only when that clash is not pending, so a whole chain is reported at once. - * Along a chain every key is longer than the one before, so the walk ends. - */ -async function pendingEnvKeyClashes( - client: ManagementApiClient, - projectId: string, - branchId: string | undefined, - clashes: readonly EnvKeyClash[], -): Promise { - const byKey = new Map(clashes.map((clash) => [clash.key, clash])); - const exists = new Map>(); - const rowExists = (key: string) => { - const known = exists.get(key); - if (known !== undefined) return known; - const found = composerRowExists(client, projectId, branchId, key); - exists.set(key, found); - return found; - }; - const isPending = async (clash: EnvKeyClash): Promise => - (await rowExists(clash.key)) && !(await hasMoved(clash.oldOwnerNewKey)); - const hasMoved = async (key: string): Promise => { - if (!(await rowExists(key))) return false; - const next = byKey.get(key); - return next === undefined || !(await isPending(next)); - }; - const pending: EnvKeyClash[] = []; - for (const clash of clashes) { - if (await isPending(clash)) pending.push(clash); - } - return pending; -} - /** The preflight input typed against this extension's own client — the concrete form of the framework's erased `PreflightInput`. */ export type PrismaCloudPreflightInput = PreflightInput; @@ -231,36 +164,6 @@ const managedBySystemError = (names: readonly string[]): Error => const invalidInputError = (serviceAddress: string, message: string): Error => new Error(`invalid input for service "${serviceAddress}": ${message}`); -function envKeyClashError( - clashes: readonly EnvKeyClash[], - projectId: string, - branchId: string | undefined, - environment: string, -): Error { - const scopeFlag = - branchId === undefined ? '--role production' : `--branch ${shellQuote(environment)}`; - const lines = clashes.map( - (c) => - ` - ${c.key} belongs to "${c.oldOwner}" from the previous Composer release. ` + - `This release writes it for "${c.newOwner}", and moves "${c.oldOwner}"'s value to ${c.oldOwnerNewKey}.`, - ); - const commands = clashes.map( - (c) => - ` prisma project env delete ${shellQuote(c.key)} --project ${shellQuote(projectId)} ${scopeFlag}`, - ); - return new Error( - "Deploy failed before any resource was created, changed or deleted; the branch's application " + - 'topology has already been replaced and the build recorded. Moving to addresses that start with the app name ' + - "gives these environment variables a new owner, but each still holds its old owner's value:\n" + - `${lines.join('\n')}\n\n` + - 'Delete each one, then deploy again. The deploy writes every value under its new key, so ' + - 'nothing is lost; the running deployments keep their own copy until then.\n' + - `${commands.join('\n')}\n` + - 'Or delete it in the Prisma Console: open the project, go to Environment variables, and ' + - `delete it under ${branchId === undefined ? 'Production' : `the branch "${environment}"`}.`, - ); -} - async function managementClient(): Promise { if ((process.env['PRISMA_SERVICE_TOKEN'] ?? '').length === 0) throw tokenRequiredError(); return Effect.runPromise( @@ -297,15 +200,12 @@ export async function runPreflight( const names = [ ...new Set([...services.flatMap((service) => service.names), ...unread.map((use) => use.name)]), ]; - const clashes = findEnvKeyClashes(input.graph); - if (names.length === 0 && clashes.length === 0) { + if (names.length === 0) { input.report?.({ checked: 0, unset: [] }); return { updatedAt: new Map() }; } const client = composerClientOf(input.credentials) ?? deps?.client ?? (await managementClient()); - const pending = await pendingEnvKeyClashes(client, projectId, branchId, clashes); - if (pending.length > 0) throw envKeyClashError(pending, projectId, branchId, input.environment); const rows = await mapWithConcurrency(names, LIST_CONCURRENCY, (name) => readPlatformVariable(client, projectId, branchId, name), diff --git a/packages/1-prisma-cloud/1-extensions/target/src/sent-variable-names-resource.ts b/packages/1-prisma-cloud/1-extensions/target/src/sent-variable-names-resource.ts new file mode 100644 index 000000000..6876305c2 --- /dev/null +++ b/packages/1-prisma-cloud/1-extensions/target/src/sent-variable-names-resource.ts @@ -0,0 +1,38 @@ +/** + * The `SentVariableNames` Alchemy resource: every variable name a service's deployments have been sent, kept in + * deploy state so a name Composer no longer sends can be sent as `null`, which deletes it from the service. + */ +import { Resource } from 'alchemy'; +import * as Provider from 'alchemy/Provider'; +import * as Effect from 'effect/Effect'; + +export interface SentVariableNamesProps { + /** This deploy's variable names, sorted. */ + readonly names: readonly string[]; +} + +export interface SentVariableNamesAttributes { + /** Every variable name this resource has been given, sorted. */ + readonly names: readonly string[]; +} + +export type SentVariableNames = Resource< + 'PrismaCloud.SentVariableNames', + SentVariableNamesProps, + SentVariableNamesAttributes +>; + +export const SentVariableNames = Resource('PrismaCloud.SentVariableNames'); + +function union(recorded: readonly string[] | undefined, sent: readonly string[]) { + return { names: [...new Set([...(recorded ?? []), ...sent])].sort() }; +} + +const sentVariableNamesProviderService: Provider.ProviderService = { + list: () => Effect.succeed([]), + reconcile: ({ news, output }) => Effect.sync(() => union(output?.names, news.names)), + delete: () => Effect.void, +}; + +export const SentVariableNamesProvider = () => + Provider.effect(SentVariableNames, Effect.succeed(sentVariableNamesProviderService)); diff --git a/packages/1-prisma-cloud/1-extensions/target/src/serializer.ts b/packages/1-prisma-cloud/1-extensions/target/src/serializer.ts index c5f9b109a..b1ec6f871 100644 --- a/packages/1-prisma-cloud/1-extensions/target/src/serializer.ts +++ b/packages/1-prisma-cloud/1-extensions/target/src/serializer.ts @@ -232,7 +232,7 @@ export const generatedParamVarName = (address: string, path: string): string => const ABSENT: unique symbol = Symbol('composer-input-absent'); -/** One generated input leaf the walk records: the descriptor provisions a `GeneratedParam` resource + an env row per entry, and the substitution emits its `$generated` pointer at `path`. */ +/** One generated input leaf: the descriptor sends its value under `varName`, and the document holds a `$generated` pointer at `path`. */ export interface GeneratedLeaf { readonly varName: string; readonly bytes: number; @@ -379,14 +379,14 @@ export function resolveInputBinding( }; } -/** One serialized input document, ready to write as a row: into the artifact, or as a variable for a service with no artifact. */ +/** One serialized input document: written into the artifact, or as a local row for a dev server. */ export interface InputDocumentRow { readonly key: string; /** The JSON document: defaults applied, each secret leaf a `$platform` marker, each generated leaf a `$generated` marker, never a secret's value. */ readonly value: string; /** Binding paths whose platform variable `prisma dev` found unset. */ readonly absent: readonly string[]; - /** Generated leaves the descriptor must provision (a `GeneratedParam` resource + env row each). */ + /** Generated leaves the descriptor must send a value for. */ readonly generated: readonly GeneratedLeaf[]; /** Every `$platform` marker the document holds, in document order. Composer does not write the variables they name. */ readonly markers: readonly PlatformMarkerUse[]; diff --git a/patches/@alchemy.run__prisma@2.0.0-beta.87.patch b/patches/@alchemy.run__prisma@2.0.0-beta.87.patch new file mode 100644 index 000000000..58892dc08 --- /dev/null +++ b/patches/@alchemy.run__prisma@2.0.0-beta.87.patch @@ -0,0 +1,301 @@ +diff --git a/lib/Deployment.d.ts b/lib/Deployment.d.ts +index 4bbdd61c..d8883e48 100644 +--- a/lib/Deployment.d.ts ++++ b/lib/Deployment.d.ts +@@ -119,6 +119,25 @@ export interface DeploymentProps { + * ``` + */ + triggers?: Record; ++ /** ++ * Variables the platform stores on the App, sent with the request that ++ * creates the deployment. A string sets a key, `null` deletes it, and a key ++ * left out keeps its stored value. The platform accepts them only when a ++ * deployment is created, so any change to the resolved map, a value that is ++ * not resolved while planning, or declaring `variables` on a deployment that ++ * was created without them replaces the deployment. They are never sent on ++ * an update. ++ * ++ * The values are stored on the App and outlive this deployment: deleting or ++ * replacing the Deployment leaves them, and so does removing `variables` ++ * from its props; only `null` or deleting the App removes one. Every ++ * Deployment of one App writes to the same store. ++ * ++ * Values may be wrapped in `Redacted.make(secret)`; they are unwrapped only ++ * for the request and the fingerprint. Leaving `variables` unset sends no ++ * field. ++ */ ++ variables?: Record | null>; + } + export interface Deployment extends Resource<"Prisma.Deployment", DeploymentProps, { + /** +@@ -152,6 +171,11 @@ export interface Deployment extends Resource<"Prisma.Deployment", DeploymentProp + * state; absent when `triggers` is unset. + */ + triggersHash?: Redacted.Redacted; ++ /** ++ * Salted fingerprint of the resolved `variables` this deployment was ++ * created with; absent when `variables` is unset. ++ */ ++ variablesHash?: Redacted.Redacted; + /** + * Stable App endpoint domain after promotion. + */ +diff --git a/lib/Deployment.js b/lib/Deployment.js +index 07e57267..ddc92b19 100644 +--- a/lib/Deployment.js ++++ b/lib/Deployment.js +@@ -112,6 +112,7 @@ const attrsFrom = (deployment, appId, extra) => ({ + previewDomain: deployment.previewDomain, + artifactHash: extra?.artifactHash, + triggersHash: extra?.triggersHash, ++ variablesHash: extra?.variablesHash, + appEndpointDomain: extra?.appEndpointDomain, + createdAt: deployment.createdAt, + }); +@@ -196,7 +197,31 @@ const triggersHashOf = (triggers) => sha256Object({ + salt: TRIGGERS_HASH_SALT, + triggers: unwrapRedacted(triggers) ?? null, + }); +-const persistedTriggersHash = (value) => Redacted.isRedacted(value) ? Redacted.value(value) : value; ++const persistedHash = (value) => Redacted.isRedacted(value) ? Redacted.value(value) : value; ++const VARIABLES_HASH_SALT = "alchemy/Prisma.Deployment/variables/v1"; ++const variablesHashOf = (variables) => sha256Object({ ++ salt: VARIABLES_HASH_SALT, ++ variables: unwrapRedacted(variables) ?? null, ++}); ++const requestVariables = (variables) => Object.fromEntries(Object.entries(variables).map(([key, value]) => [ ++ key, ++ Redacted.isRedacted(value) ? Redacted.value(value) : value, ++])); ++/** ++ * Whether the declared `variables` require a new deployment. Unlike ++ * `triggers`, a declaration with no recorded fingerprint replaces: an update ++ * creates no deployment, so the values would never reach the platform. ++ */ ++const variablesChanged = Effect.fn(function* (variables, persisted) { ++ if (variables === undefined) ++ return false; ++ const recorded = persistedHash(persisted); ++ if (recorded === undefined) ++ return true; ++ if (!isResolved({ variables })) ++ return true; ++ return (yield* variablesHashOf(variables)) !== recorded; ++}); + /** + * Whether the declared `triggers` inputs differ from the fingerprint the + * running deployment was created for. +@@ -211,7 +236,7 @@ const persistedTriggersHash = (value) => Redacted.isRedacted(value) ? Redacted.v + * default update instead of replacing the deployment. + */ + const triggersChanged = Effect.fn(function* (triggers, persisted) { +- const recorded = persistedTriggersHash(persisted); ++ const recorded = persistedHash(persisted); + if (triggers === undefined || recorded === undefined) + return false; + if (!isResolved({ triggers })) +@@ -268,6 +293,9 @@ const ProviderLive = () => Provider.effect(Deployment, Effect.gen(function* () { + if (yield* triggersChanged(news.triggers, output?.triggersHash)) { + return { action: "replace" }; + } ++ if (yield* variablesChanged(news.variables, output?.variablesHash)) { ++ return { action: "replace" }; ++ } + const replacementContent = { + portMapping: news.portMapping, + skipCodeUpload: news.skipCodeUpload, +@@ -368,6 +396,9 @@ const ProviderLive = () => Provider.effect(Deployment, Effect.gen(function* () { + const triggersHash = news.triggers === undefined + ? undefined + : Redacted.make(yield* triggersHashOf(news.triggers)); ++ const variablesHash = news.variables === undefined ++ ? undefined ++ : Redacted.make(yield* variablesHashOf(news.variables)); + const appId = yield* resolveAppId(news.app); + const deploymentId = isPrismaDevId(output?.deploymentId) + ? undefined +@@ -392,6 +423,9 @@ const ProviderLive = () => Provider.effect(Deployment, Effect.gen(function* () { + serviceId: appId, + ...(news.portMapping === undefined ? {} : { portMapping: news.portMapping }), + ...(news.skipCodeUpload === undefined ? {} : { skipCodeUpload: news.skipCodeUpload }), ++ ...(news.variables === undefined ++ ? {} ++ : { variables: requestVariables(news.variables) }), + }).pipe( + // A replayed create would make a second deployment; the retry + // policy cannot see the request, so opt out explicitly. +@@ -447,6 +481,7 @@ const ProviderLive = () => Provider.effect(Deployment, Effect.gen(function* () { + return attrsFrom(deployment, appId, { + artifactHash, + triggersHash, ++ variablesHash, + appEndpointDomain, + }); + }), +@@ -474,6 +509,7 @@ const ProviderLocal = () => devProvider(Deployment, ["deploymentId"], ({ id, new + previewDomain: undefined, + artifactHash: undefined, + triggersHash: undefined, ++ variablesHash: undefined, + appEndpointDomain: undefined, + createdAt: DEV_TIMESTAMP, + })); +diff --git a/src/Deployment.ts b/src/Deployment.ts +index 71258d31..704a5e02 100644 +--- a/src/Deployment.ts ++++ b/src/Deployment.ts +@@ -144,6 +144,25 @@ export interface DeploymentProps { + * ``` + */ + triggers?: Record; ++ /** ++ * Variables the platform stores on the App, sent with the request that ++ * creates the deployment. A string sets a key, `null` deletes it, and a key ++ * left out keeps its stored value. The platform accepts them only when a ++ * deployment is created, so any change to the resolved map, a value that is ++ * not resolved while planning, or declaring `variables` on a deployment that ++ * was created without them replaces the deployment. They are never sent on ++ * an update. ++ * ++ * The values are stored on the App and outlive this deployment: deleting or ++ * replacing the Deployment leaves them, and so does removing `variables` ++ * from its props; only `null` or deleting the App removes one. Every ++ * Deployment of one App writes to the same store. ++ * ++ * Values may be wrapped in `Redacted.make(secret)`; they are unwrapped only ++ * for the request and the fingerprint. Leaving `variables` unset sends no ++ * field. ++ */ ++ variables?: Record | null>; + } + + export interface Deployment extends Resource< +@@ -181,6 +200,11 @@ export interface Deployment extends Resource< + * state; absent when `triggers` is unset. + */ + triggersHash?: Redacted.Redacted; ++ /** ++ * Salted fingerprint of the resolved `variables` this deployment was ++ * created with; absent when `variables` is unset. ++ */ ++ variablesHash?: Redacted.Redacted; + /** + * Stable App endpoint domain after promotion. + */ +@@ -286,6 +310,7 @@ const attrsFrom = ( + extra?: { + artifactHash?: string; + triggersHash?: Redacted.Redacted; ++ variablesHash?: Redacted.Redacted; + appEndpointDomain?: string; + }, + ): Deployment["Attributes"] => ({ +@@ -296,6 +321,7 @@ const attrsFrom = ( + previewDomain: deployment.previewDomain, + artifactHash: extra?.artifactHash, + triggersHash: extra?.triggersHash, ++ variablesHash: extra?.variablesHash, + appEndpointDomain: extra?.appEndpointDomain, + createdAt: deployment.createdAt, + }); +@@ -424,9 +450,43 @@ const triggersHashOf = (triggers: unknown) => + triggers: unwrapRedacted(triggers) ?? null, + }); + +-const persistedTriggersHash = (value: Redacted.Redacted | string | undefined) => ++const persistedHash = (value: Redacted.Redacted | string | undefined) => + Redacted.isRedacted(value) ? Redacted.value(value) : value; + ++const VARIABLES_HASH_SALT = "alchemy/Prisma.Deployment/variables/v1"; ++ ++const variablesHashOf = (variables: unknown) => ++ sha256Object({ ++ salt: VARIABLES_HASH_SALT, ++ variables: unwrapRedacted(variables) ?? null, ++ }); ++ ++const requestVariables = ( ++ variables: Record | string | null>, ++): Record => ++ Object.fromEntries( ++ Object.entries(variables).map(([key, value]) => [ ++ key, ++ Redacted.isRedacted(value) ? Redacted.value(value) : value, ++ ]), ++ ); ++ ++/** ++ * Whether the declared `variables` require a new deployment. Unlike ++ * `triggers`, a declaration with no recorded fingerprint replaces: an update ++ * creates no deployment, so the values would never reach the platform. ++ */ ++const variablesChanged = Effect.fn(function* ( ++ variables: unknown, ++ persisted: Redacted.Redacted | string | undefined, ++) { ++ if (variables === undefined) return false; ++ const recorded = persistedHash(persisted); ++ if (recorded === undefined) return true; ++ if (!isResolved({ variables })) return true; ++ return (yield* variablesHashOf(variables)) !== recorded; ++}); ++ + /** + * Whether the declared `triggers` inputs differ from the fingerprint the + * running deployment was created for. +@@ -444,7 +504,7 @@ const triggersChanged = Effect.fn(function* ( + triggers: unknown, + persisted: Redacted.Redacted | string | undefined, + ) { +- const recorded = persistedTriggersHash(persisted); ++ const recorded = persistedHash(persisted); + if (triggers === undefined || recorded === undefined) return false; + if (!isResolved({ triggers })) return true; + return (yield* triggersHashOf(triggers)) !== recorded; +@@ -510,6 +570,9 @@ const ProviderLive = () => + if (yield* triggersChanged(news.triggers, output?.triggersHash)) { + return { action: "replace" } as const; + } ++ if (yield* variablesChanged(news.variables, output?.variablesHash)) { ++ return { action: "replace" } as const; ++ } + const replacementContent = { + portMapping: news.portMapping, + skipCodeUpload: news.skipCodeUpload, +@@ -622,6 +685,10 @@ const ProviderLive = () => + news.triggers === undefined + ? undefined + : Redacted.make(yield* triggersHashOf(news.triggers)); ++ const variablesHash = ++ news.variables === undefined ++ ? undefined ++ : Redacted.make(yield* variablesHashOf(news.variables)); + const appId = yield* resolveAppId(news.app); + const deploymentId = isPrismaDevId(output?.deploymentId) + ? undefined +@@ -661,6 +728,9 @@ const ProviderLive = () => + serviceId: appId, + ...(news.portMapping === undefined ? {} : { portMapping: news.portMapping }), + ...(news.skipCodeUpload === undefined ? {} : { skipCodeUpload: news.skipCodeUpload }), ++ ...(news.variables === undefined ++ ? {} ++ : { variables: requestVariables(news.variables) }), + }).pipe( + // A replayed create would make a second deployment; the retry + // policy cannot see the request, so opt out explicitly. +@@ -740,6 +810,7 @@ const ProviderLive = () => + return attrsFrom(deployment, appId, { + artifactHash, + triggersHash, ++ variablesHash, + appEndpointDomain, + }); + }), +@@ -778,6 +849,7 @@ const ProviderLocal = () => + previewDomain: undefined, + artifactHash: undefined, + triggersHash: undefined, ++ variablesHash: undefined, + appEndpointDomain: undefined, + createdAt: DEV_TIMESTAMP, + })); diff --git a/patches/@distilled.cloud__prisma@1.0.0-rc.20.patch b/patches/@distilled.cloud__prisma@1.0.0-rc.20.patch new file mode 100644 index 000000000..cac99055a --- /dev/null +++ b/patches/@distilled.cloud__prisma@1.0.0-rc.20.patch @@ -0,0 +1,44 @@ +diff --git a/lib/services/management.d.ts b/lib/services/management.d.ts +index e050e7e802da5cb600230d3a37253c3d8c4a1514..9b1155cd53c88942eacf2af5a1e2470305fd7390 100644 +--- a/lib/services/management.d.ts ++++ b/lib/services/management.d.ts +@@ -891,6 +891,9 @@ export interface CreateServiceDeploymentRequest { + serviceId: string; + portMapping?: CreateServiceDeploymentRequestPortMapping | undefined; + skipCodeUpload?: boolean | undefined; ++ variables?: { ++ [key: string]: string | null; ++ } | undefined; + } + export interface CreateServiceDeploymentResponseData { + id: string; +diff --git a/lib/services/management.js b/lib/services/management.js +index 0b6d4dbd4d8ca9875598c77d613a3fa8317dbddb..732df207b6001e73e1f010de3e20d6b35c7680ec 100644 +--- a/lib/services/management.js ++++ b/lib/services/management.js +@@ -1,4 +1,4 @@ +-import{Ba as e,Wb as t,Xb as n,a as r,c as i,dc as a,e as o,ec as s,errors$UnknownPrismaError as c,fc as ee,hc as l,ic as u,k as d,kc as f,l as p,layer_s3$S3BucketName as te,layer_s3$S3CredentialsError as ne,layer_s3$layerS3 as re,m,mc as h,nc as g,pc as _,protocol$PrismaProtocol as v,retry$Retry as y,traits$Http as b,traits$Label as x,traits$Query as S,traits$RawResponseRoot as C,traits$SensitiveValue as w,traits$StringEncoded as ie,traits$applyErrorMatchers as T,uc as E,vc as D,xa as ae,ya as O}from"../_bundle/sdk.js";const k={system:`prisma-api`,responseHeaders:[{header:`x-request-id`,name:`http.response.header.x-request-id`,transform:`list`},{header:`request-id`,name:`http.response.header.request-id`,transform:`list`}],prefix:`Prisma`,service:`Prisma`,labels:`prisma`,propagate:`w3c`};const A=/*@__PURE__*/ o(function BadRequest(e){return p(e,new.target,[`$5($4()("BadRequest",{code:$2,message:$3}).pipe($1),[{status:400}])`,[_,O,s,l,f,T]])});const j=/*@__PURE__*/ o(function Conflict(t){return p(t,new.target,[`$5($4()("Conflict",{code:$2,message:$3}).pipe($1),[{status:409}])`,[_,e,s,l,f,T]])});const M=/*@__PURE__*/ o(function DomainDnsNotConfigured(e){return p(e,new.target,[`$4($3()("DomainDnsNotConfigured",{message:$2}).pipe($1),[{status:400,message:{includes:"DNS is not configured"}},{status:400,body:{"/error/hint":{includes:"DNS is not configured"}}}])`,[_,O,l,f,T]])});const N=/*@__PURE__*/ o(function DomainOwnershipRequired(e){return p(e,new.target,[`$5($4()("DomainOwnershipRequired",{message:$2,body:$3}).pipe($1),[{status:422,body:{"/error/code":"domain-ownership-required"}}])`,[_,O,l,g,f,T]])});const P=/*@__PURE__*/ o(function Forbidden(e){return p(e,new.target,[`$5($4()("Forbidden",{code:$2,message:$3}).pipe($1),[{status:403}])`,[_,ae,s,l,f,T]])});const F=/*@__PURE__*/ o(function NotFound(e){return p(e,new.target,[`$5($4()("NotFound",{code:$2,message:$3}).pipe($1),[{status:404}])`,[_,O,s,l,f,T]])});const I=/*@__PURE__*/ o(function UnprocessableEntity(e){return p(e,new.target,[`$5($4()("UnprocessableEntity",{code:$2,message:$3}).pipe($1),[{status:422}])`,[_,O,s,l,f,T]])});const L=/*@__PURE__*/ m(e=>e===r?d(`CreateAuthGithubActionsToken`,`{input:#1,output:#3,errors:[$7,$8],protocol:$9,retry:$10,telemetry:$11,span:"%"};$6(>4)@"%Request";$6(>5)@"%ResponseData";$6(>6)@"%Response";$5({token:$2,expiresInSeconds:$4($3)}).pipe($1({method:"POST",uri:"/v1/auth/github-actions/token",code:200}));$5({id:$2,type:$2,value:$2,expiresAt:$2,workspaceId:$2});$5({data:#2})`,[_,b,l,s,E,u,D,A,c,v,y,k]):i(L,e));const R=/*@__PURE__*/ m(e=>e===r?d(`CreateBucket`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$5(>2)@"%Request";$4({projectId:$2,name:$3($2),branchId:$3($2),branchGitName:$3($2),logicalId:$3($2)}).pipe($1({method:"POST",uri:"/v1/buckets",code:200}))`,[_,b,l,E,u,D,__d38,A,P,F,j,c,v,y,k]):i(R,e));const z=/*@__PURE__*/ m(e=>e===r?d(`CreateBucketKey`,`{input:#1,output:#3,errors:[$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$6(>4)@"%Request";$6(>5)@"%ResponseData";$6(>6)@"%Response";$5({bucketId:$3.pipe($2()),name:$4($3),role:$3}).pipe($1({method:"POST",uri:"/v1/buckets/{bucketId}/keys",code:200}));$5({id:$3,type:$3,name:$3,valueHint:$3,role:$3,createdAt:$3,secretAccessKey:$3.pipe($7({})),accessKeyId:$3.pipe($7({})),endpoint:$3,bucketName:$3});$5({data:#2})`,[_,b,x,l,E,u,D,w,A,F,c,v,y,k]):i(z,e));const B=/*@__PURE__*/ m(e=>e===r?d(`CreateBuild`,`{input:#2,output:#7:0,errors:[$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$4(>3)@"%RequestRunIdentity";$4(>4)@"%Request";$3({provider:$1,repositoryId:$1,runId:$1,runAttempt:$2});$3({source:$1,commitSha:$1,branchName:$1,runIdentity:$6(#1),externalLogUrl:$6($1),projectId:$6($1),branchId:$6($1),applicationTopologyContentHash:$6($1)}).pipe($5({method:"POST",uri:"/v1/builds",code:200}))`,[_,l,s,u,D,b,E,__d0,A,F,c,v,y,k]):i(B,e));const V=/*@__PURE__*/ m(e=>e===r?d(`CreateConnection`,`{input:#1,output:#5:3,errors:[$6,$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$4(>2)@"%Request";$3({databaseId:$2,name:$2}).pipe($1({method:"POST",uri:"/v1/connections",code:200}))`,[_,b,l,u,D,__d3,A,j,F,I,c,v,y,k]):i(V,e));const H=/*@__PURE__*/ m(e=>e===r?d(`CreateConnectionRotate`,`{input:#1,output:#6:3,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({id:$3.pipe($2())}).pipe($1({method:"POST",uri:"/v1/connections/{id}/rotate",code:200}))`,[_,b,x,l,u,D,__d3,A,F,c,v,y,k]):i(H,e));const U=/*@__PURE__*/ m(e=>e===r?d(`CreateDatabase`,`{input:#2,output:#5,errors:[$14,$15,$16,$17,$18,$19],protocol:$20,retry:$21,telemetry:$22,span:"%"};$4(>6);$4(>7)@"%Request";$4(>8);$4(>9)@"%ResponseData";$4(>10)@"%Response";$3([#1:0,#2:0,#1:1]);$10({projectId:$6,region:$7($6),name:$7($6),isDefault:$7($8),source:$7(#1),branchId:$7($9($6)),branchGitName:$7($9($6)),logicalId:$7($6)}).pipe($5({method:"POST",uri:"/v1/databases",code:200}));$3([#1:0,#2:0,#1:1]);$10({id:$6,type:$6,url:$6,name:$6,status:$6,createdAt:$6,isDefault:$8,defaultConnectionId:$9($6),connections:#11:3,project:#12:0,region:$9(#13:0),source:$9(#3),branchId:$9($6),logicalId:$9($6)});$10({data:#4})`,[_,__d7,__d5,h,D,b,l,E,n,a,u,__d6,__d37,__d4,A,P,F,j,I,c,v,y,k]):i(U,e));const W=/*@__PURE__*/ m(e=>e===r?d(`CreateDatabaseConnection`,`{input:#1,output:#6:3,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({databaseId:$3.pipe($2()),name:$3}).pipe($1({method:"POST",uri:"/v1/databases/{databaseId}/connections",code:200}))`,[_,b,x,l,u,D,__d3,A,F,I,c,v,y,k]):i(W,e));const G=/*@__PURE__*/ m(e=>e===r?d(`CreateDatabaseRestore`,`{input:#1,output:#3,errors:[$12,$13,$14,$15,$16],protocol:$17,retry:$18,telemetry:$19,span:"%"};$6(>4)@"%Request";$6(>5)@"%ResponseData";$6(>6)@"%Response";$5({targetDatabaseId:$3.pipe($2()),source:#4:0}).pipe($1({method:"POST",uri:"/v1/databases/{targetDatabaseId}/restore",code:200}));$5({id:$3,type:$3,url:$3,name:$3,status:$3,createdAt:$3,isDefault:$7,defaultConnectionId:$8($3),connections:#9:0,project:#10:0,region:$8(#11:0),source:#4:0,branchId:$8($3),logicalId:$8($3)});$5({data:#2})`,[_,b,x,l,__d5,u,D,n,a,__d10,__d37,__d4,A,F,j,I,c,v,y,k]):i(G,e));const K=/*@__PURE__*/ m(e=>e===r?d(`CreateDeploymentStart`,`{input:#1,output:#3,errors:[$6,$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>4)@"%Request";$5(>5)@"%ResponseData";$5(>6)@"%Response";$4({deploymentId:$3.pipe($2())}).pipe($1({method:"POST",uri:"/v1/deployments/{deploymentId}/start",code:200}));$4({previewDomain:$3});$4({data:#2})`,[_,b,x,l,u,D,A,P,F,j,c,v,y,k]):i(K,e));const q=/*@__PURE__*/ m(e=>e===r?d(`CreateDeploymentStop`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$5(>2)@"%Request";$4({deploymentId:$3.pipe($2())}).pipe($1({method:"POST",uri:"/v1/deployments/{deploymentId}/stop",code:200}))`,[_,b,x,l,u,D,__d11,A,P,F,j,c,v,y,k]):i(q,e));const J=/*@__PURE__*/ m(e=>e===r?d(`CreateDomainOwnershipVerify`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({domainOwnershipId:$3.pipe($2())}).pipe($1({method:"POST",uri:"/v1/domain-ownerships/{domainOwnershipId}/verify",code:200}))`,[_,b,x,l,u,D,__d12,A,F,c,v,y,k]):i(J,e));const Y=/*@__PURE__*/ m(e=>e===r?d(`CreateDomainRetry`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$5(>2)@"%Request";$4({domainId:$3.pipe($2())}).pipe($1({method:"POST",uri:"/v1/domains/{domainId}/retry",code:200}))`,[_,b,x,l,u,D,__d15,A,P,F,j,c,v,y,k]):i(Y,e));const X=/*@__PURE__*/ m(e=>e===r?d(`CreateEnvironmentVariable`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$5(>2)@"%Request";$4({projectId:$2,branchId:$3($2),class:$2,key:$2,value:$2}).pipe($1({method:"POST",uri:"/v1/environment-variables",code:200}))`,[_,b,l,E,u,D,__d17,A,F,j,I,c,v,y,k]):i(X,e));const Z=/*@__PURE__*/ m(e=>e===r?d(`CreateProject`,`{input:#1,output:#5,errors:[$17,$18,$19,$20],protocol:$21,retry:$22,telemetry:$23,span:"%"};$6(>6)@"%Request";$6(>7);$6(>8)@"%ResponseDataDatabase";$6(>9)@"%ResponseData";$6(>10)@"%Response";$5({createDatabase:$3($2),name:$3($4),region:$3($4),logicalId:$3($4),workspaceId:$3($4)}).pipe($1({method:"POST",uri:"/v1/projects",code:200}));$9([#7:0,#8:0,#7:1]);$5({id:$4,type:$4,url:$4,name:$4,status:$4,createdAt:$4,isDefault:$2,defaultConnectionId:$10($4),connections:#11:3,region:#12:0,source:$10(#2),branchId:$10($4),logicalId:$10($4),apiKeys:#13:1,connectionString:$10($4).pipe($14({})),directConnection:$10(#15:0)});$5({id:$4,type:$4,url:$4,name:$4,logicalId:$10($4),createdAt:$4,defaultRegion:$10($4),workspace:#16:0,database:$10(#3)});$5({data:#4})`,[_,b,n,E,l,u,D,__d7,__d5,h,a,__d6,__d4,__d19,w,__d2,__d37,A,j,I,c,v,y,k]):i(Z,e));const Q=/*@__PURE__*/ m(e=>e===r?d(`CreateProjectBranch`,`{input:#1,output:#8:0,errors:[$9,$10,$11,$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$7(>2)@"%Request";$6({projectId:$3.pipe($2()),gitName:$3,isDefault:$5($4)}).pipe($1({method:"POST",uri:"/v1/projects/{projectId}/branches",code:200}))`,[_,b,x,l,n,E,u,D,__d20,A,F,j,I,c,v,y,k]):i(Q,e));const oe=/*@__PURE__*/ m(e=>e===r?d(`CreateProjectBranchAlchemyStateLease`,`{input:#1,output:#8:1,errors:[$9,$10,$11,$12],protocol:$13,retry:$14,telemetry:$15,span:"%"};$7(>2)@"%Request";$6({projectId:$3.pipe($2()),branchId:$3.pipe($2()),stack:$3,stage:$3,ttlSeconds:$5($4),holderDescription:$5($3)}).pipe($1({method:"POST",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/lease",code:200}))`,[_,b,x,l,s,E,u,D,__d22,A,F,j,c,v,y,k]):i(oe,e));const se=/*@__PURE__*/ m(e=>e===r?d(`CreateProjectDatabase`,`{input:#3,output:#6,errors:[$18,$19,$20,$21,$22,$23],protocol:$24,retry:$25,telemetry:$26,span:"%"};$4(>7)@"%RequestFromDatabase";$4(>8);$4(>9)@"%Request";$4(>10);$4(>11)@"%ResponseData";$4(>12)@"%Response";$3({id:$1,backupId:$2($1)});$7([#5:0,#6:0,#5:1]);$3({projectId:$1.pipe($9()),region:$2($1),name:$2($1),isDefault:$2($10),fromDatabase:$2(#1),source:$2(#2)}).pipe($8({method:"POST",uri:"/v1/projects/{projectId}/databases",code:200}));$7([#5:0,#6:0,#5:1]);$3({id:$1,type:$1,url:$1,name:$1,status:$1,createdAt:$1,isDefault:$10,defaultConnectionId:$11($1),connections:#12:3,project:#13:0,region:#14:0,source:$11(#4),branchId:$11($1),logicalId:$11($1),apiKeys:#15:1,connectionString:$11($1).pipe($16({})),directConnection:$11(#17:0)});$3({data:#5})`,[_,l,E,u,D,__d7,__d5,h,b,x,n,a,__d6,__d37,__d4,__d19,w,__d2,A,P,F,j,I,c,v,y,k]):i(se,e));const ce=/*@__PURE__*/ m(e=>e===r?d(`CreateProjectTransfer`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$5(>2)@"%Request";$4({id:$3.pipe($2()),recipientAccessToken:$3}).pipe($1({method:"POST",uri:"/v1/projects/{id}/transfer",code:200}))`,[_,b,x,l,u,D,__d11,A,F,j,I,c,v,y,k]):i(ce,e));const le=/*@__PURE__*/ m(e=>e===r?d(`CreateScmInstallationsInstallIntent`,`{input:#1,output:#3,errors:[$7,$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$5(>4)@"%Request";$5(>5)@"%ResponseData";$5(>6)@"%Response";$4({provider:$2,workspaceId:$2,repository:$3($2)}).pipe($1({method:"POST",uri:"/v1/scm-installations/install-intents",code:200}));$4({type:$2,provider:$2,workspaceId:$2,installUrl:$2,alreadyLinked:$3($6),accountLogin:$3($2),hint:$3($2)});$4({data:#2})`,[_,b,l,E,u,D,n,A,P,F,I,c,v,y,k]):i(le,e));const ue=/*@__PURE__*/ m(e=>e===r?d(`CreateService`,`{input:#1,output:#7:0,errors:[$8,$9,$10,$11,$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$6(>2)@"%Request";$5({displayName:$2,regionId:$3($2),branchId:$3($4($2)),branchGitName:$3($4($2)),projectId:$2,logicalId:$3($2)}).pipe($1({method:"POST",uri:"/v1/services",code:200}))`,[_,b,l,E,a,u,D,__d24,A,P,F,j,I,c,v,y,k]):i(ue,e));const de=/*@__PURE__*/ m(e=>e===r?d(`CreateServiceDeployment`,`{input:#2,output:#4,errors:[$10,$11,$12,$13,$14],protocol:$15,retry:$16,telemetry:$17,span:"%"};$5(>5)@"%RequestPortMapping";$5(>6)@"%Request";$5(>7)@"%ResponseData";$5(>8)@"%Response";$4({http:$3($2($1))});$4({serviceId:$8.pipe($7()),portMapping:$3(#1),skipCodeUpload:$3($9)}).pipe($6({method:"POST",uri:"/v1/services/{serviceId}/deployments",code:200}));$4({id:$8,type:$8,url:$8,foundryVersionId:$8,uploadUrl:$2($8)});$4({data:#3})`,[_,s,a,E,u,D,b,x,l,n,A,P,F,I,c,v,y,k]):i(de,e));const fe=/*@__PURE__*/ m(e=>e===r?d(`CreateServiceDomain`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10,$11,$12,$13,$14],protocol:$15,retry:$16,telemetry:$17,span:"%"};$5(>2)@"%Request";$4({serviceId:$3.pipe($2()),hostname:$3}).pipe($1({method:"POST",uri:"/v1/services/{serviceId}/domains",code:200}))`,[_,b,x,l,u,D,__d15,A,P,F,j,I,N,M,c,v,y,k]):i(fe,e));const pe=/*@__PURE__*/ m(e=>e===r?d(`CreateServicePromote`,`{input:#1,output:#7:1,errors:[$8,$9,$10,$11,$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$6(>2)@"%Request";$5({serviceId:$3.pipe($2()),deploymentId:$4($3),versionId:$4($3)}).pipe($1({method:"POST",uri:"/v1/services/{serviceId}/promote",code:200}))`,[_,b,x,l,E,u,D,__d25,A,P,F,j,I,c,v,y,k]):i(pe,e));const me=/*@__PURE__*/ m(e=>e===r?d(`CreateServiceRollback`,`{input:#1,output:#7:1,errors:[$8,$9,$10,$11,$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$6(>2)@"%Request";$5({serviceId:$3.pipe($2()),deploymentId:$4($3),versionId:$4($3)}).pipe($1({method:"POST",uri:"/v1/services/{serviceId}/rollback",code:200}))`,[_,b,x,l,E,u,D,__d25,A,P,F,j,I,c,v,y,k]):i(me,e));const he=/*@__PURE__*/ m(e=>e===r?d(`CreateServiceUrl`,`{input:#1,output:#8:0,errors:[$9,$10,$11,$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$7(>2)@"%Request";$6({serviceId:$3.pipe($2()),hostname:$3,logicalId:$4($3),createDomainOwnership:$4($5)}).pipe($1({method:"POST",uri:"/v1/services/{serviceId}/urls",code:200}))`,[_,b,x,l,E,n,u,D,__d26,A,F,j,I,c,v,y,k]):i(he,e));const ge=/*@__PURE__*/ m(e=>e===r?d(`CreateSourceRepository`,`{input:#1,output:#7:0,errors:[$8,$9,$10,$11,$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$6(>2)@"%Request";$5({projectId:$2,provider:$2,providerRepositoryId:$3,installationId:$4($2)}).pipe($1({method:"POST",uri:"/v1/source-repositories",code:200}))`,[_,b,l,s,E,u,D,__d29,A,P,F,j,I,c,v,y,k]):i(ge,e));const _e=/*@__PURE__*/ m(e=>e===r?d(`CreateUrlCheck`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({id:$3.pipe($2())}).pipe($1({method:"POST",uri:"/v1/urls/{id}/check",code:200}))`,[_,b,x,l,u,D,__d26,A,F,c,v,y,k]):i(_e,e));const ve=/*@__PURE__*/ m(e=>e===r?d(`CreateWorkspace`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({displayName:$3($2)}).pipe($1({method:"POST",uri:"/v1/workspaces",code:200}))`,[_,b,l,E,u,D,__d30,A,P,c,v,y,k]):i(ve,e));const ye=/*@__PURE__*/ m(e=>e===r?d(`CreateWorkspaceDomainOwnership`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$5(>2)@"%Request";$4({workspaceId:$3.pipe($2()),domain:$3}).pipe($1({method:"POST",uri:"/v1/workspaces/{workspaceId}/domain-ownerships",code:200}))`,[_,b,x,l,u,D,__d12,A,F,I,N,c,v,y,k]):i(ye,e));const be=/*@__PURE__*/ m(e=>e===r?d(`CreateWorkspaceServiceToken`,`{input:#1,output:#3,errors:[$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$7(>4)@"%Request";$7(>5)@"%ResponseData";$7(>6)@"%Response";$6({workspaceId:$3.pipe($2()),projectId:$5($4($3)),expiresAt:$5($4($3)),name:$3}).pipe($1({method:"POST",uri:"/v1/workspaces/{workspaceId}/service-tokens",code:200}));$6({id:$3,type:$3,name:$3,scope:$3,projectId:$4($3),valueHint:$3,createdAt:$3,expiresAt:$5($4($3)),value:$3});$6({data:#2})`,[_,b,x,l,a,E,u,D,A,F,I,c,v,y,k]):i(be,e));const xe=/*@__PURE__*/ m(e=>e===r?d(`DeleteBranch`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$5(>2)@"%Request";$4({branchId:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/branches/{branchId}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,j,I,c,v,y,k]):i(xe,e));const Se=/*@__PURE__*/ m(e=>e===r?d(`DeleteBucket`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({bucketId:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/buckets/{bucketId}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,c,v,y,k]):i(Se,e));const Ce=/*@__PURE__*/ m(e=>e===r?d(`DeleteBucketKey`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({bucketId:$3.pipe($2()),keyId:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/buckets/{bucketId}/keys/{keyId}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,c,v,y,k]):i(Ce,e));const we=/*@__PURE__*/ m(e=>e===r?d(`DeleteConnection`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({id:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/connections/{id}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,I,c,v,y,k]):i(we,e));const Te=/*@__PURE__*/ m(e=>e===r?d(`DeleteDatabase`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$5(>2)@"%Request";$4({databaseId:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/databases/{databaseId}",code:200}))`,[_,b,x,l,u,D,__d11,A,P,F,I,c,v,y,k]):i(Te,e));const Ee=/*@__PURE__*/ m(e=>e===r?d(`DeleteDeployment`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$5(>2)@"%Request";$4({deploymentId:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/deployments/{deploymentId}",code:200}))`,[_,b,x,l,u,D,__d11,A,P,F,j,c,v,y,k]):i(Ee,e));const De=/*@__PURE__*/ m(e=>e===r?d(`DeleteDomain`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({domainId:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/domains/{domainId}",code:200}))`,[_,b,x,l,u,D,__d11,A,P,F,c,v,y,k]):i(De,e));const Oe=/*@__PURE__*/ m(e=>e===r?d(`DeleteDomainOwnership`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({domainOwnershipId:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/domain-ownerships/{domainOwnershipId}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,c,v,y,k]):i(Oe,e));const ke=/*@__PURE__*/ m(e=>e===r?d(`DeleteEnvironmentVariable`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({envVarId:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/environment-variables/{envVarId}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,I,c,v,y,k]):i(ke,e));const Ae=/*@__PURE__*/ m(e=>e===r?d(`DeleteIntegration`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({id:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/integrations/{id}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,I,c,v,y,k]):i(Ae,e));const je=/*@__PURE__*/ m(e=>e===r?d(`DeleteProject`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$5(>2)@"%Request";$4({id:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/projects/{id}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,j,I,c,v,y,k]):i(je,e));const Me=/*@__PURE__*/ m(e=>e===r?d(`DeleteProjectBranchAlchemyStateLease`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({projectId:$3.pipe($2()),branchId:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/lease",code:200}))`,[_,b,x,l,u,D,__d11,A,F,c,v,y,k]):i(Me,e));const Ne=/*@__PURE__*/ m(e=>e===r?d(`DeleteProjectBranchAlchemyStateStateStack`,`{input:#1,output:#8:0,errors:[$9,$10,$11,$12],protocol:$13,retry:$14,telemetry:$15,span:"%"};$7(>2)@"%Request";$6({projectId:$3.pipe($2()),branchId:$3.pipe($2()),stack:$3.pipe($2()),stage:$5($3.pipe($4()))}).pipe($1({method:"DELETE",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/state/stacks/{stack}",code:200}))`,[_,b,x,l,S,E,u,D,__d11,A,F,j,c,v,y,k]):i(Ne,e));const Pe=/*@__PURE__*/ m(e=>e===r?d(`DeleteProjectBranchAlchemyStateStateStackStageResource`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({projectId:$3.pipe($2()),branchId:$3.pipe($2()),stack:$3.pipe($2()),stage:$3.pipe($2()),fqn:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/state/stacks/{stack}/stages/{stage}/resources/{fqn}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,j,c,v,y,k]):i(Pe,e));const Fe=/*@__PURE__*/ m(e=>e===r?d(`DeleteService`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$5(>2)@"%Request";$4({serviceId:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/services/{serviceId}",code:200}))`,[_,b,x,l,u,D,__d11,A,P,F,j,c,v,y,k]):i(Fe,e));const Ie=/*@__PURE__*/ m(e=>e===r?d(`DeleteSourceRepository`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({id:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/source-repositories/{id}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,c,v,y,k]):i(Ie,e));const Le=/*@__PURE__*/ m(e=>e===r?d(`DeleteUrl`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({id:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/urls/{id}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,c,v,y,k]):i(Le,e));const Re=/*@__PURE__*/ m(e=>e===r?d(`DeleteWorkspaceIntegration`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({workspaceId:$3.pipe($2()),clientId:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/workspaces/{workspaceId}/integrations/{clientId}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,I,c,v,y,k]):i(Re,e));const ze=/*@__PURE__*/ m(e=>e===r?d(`DeleteWorkspaceServiceToken`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({workspaceId:$3.pipe($2()),serviceTokenId:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/workspaces/{workspaceId}/service-tokens/{serviceTokenId}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,c,v,y,k]):i(ze,e));const Be=/*@__PURE__*/ m(e=>e===r?d(`GetAgentApproval`,`{input:#1,output:#2,errors:[$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>3)@"%Request";$5(>4)@"%Response";$4({approvalId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/agent-approvals/{approvalId}",code:200}));$4({id:$3,status:$3,expiresAt:$3,windowExpiresAt:$6($3),decidedAt:$6($3),hint:$7($3)})`,[_,b,x,l,u,D,a,E,F,c,v,y,k]):i(Be,e));const Ve=/*@__PURE__*/ m(e=>e===r?d(`GetBranch`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({branchId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/branches/{branchId}",code:200}))`,[_,b,x,l,u,D,__d20,A,F,c,v,y,k]):i(Ve,e));const He=/*@__PURE__*/ m(e=>e===r?d(`GetBucket`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({bucketId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/buckets/{bucketId}",code:200}))`,[_,b,x,l,u,D,__d38,A,F,c,v,y,k]):i(He,e));const Ue=/*@__PURE__*/ m(e=>e===r?d(`GetBucketKeys`,`{input:#1,output:#4,errors:[$11,$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$8(>5)@"%Request";$8(>6)@"%ResponseDataItem";$9(#2);$8(>7)@"%Response";$7({bucketId:$3.pipe($2()),cursor:$5($3.pipe($4())),limit:$5($6.pipe($4()))}).pipe($1({method:"GET",uri:"/v1/buckets/{bucketId}/keys",code:200}));$7({id:$3,type:$3,name:$3,valueHint:$3,role:$3,createdAt:$3});$7({data:#3,pagination:#10:0})`,[_,b,x,l,S,E,s,u,D,t,__d32,A,F,c,v,y,k]):i(Ue,e));const We=/*@__PURE__*/ m(e=>e===r?d(`GetBuckets`,`{input:#1,output:#3,errors:[$11,$12],protocol:$13,retry:$14,telemetry:$15,span:"%"};$7(>4)@"%Request";$9(#8:0);$7(>5)@"%Response";$6({cursor:$4($3.pipe($2())),limit:$4($5.pipe($2())),projectId:$4($3.pipe($2())),logicalId:$4($3.pipe($2())),branchId:$4($3.pipe($2())),branchGitName:$4($3.pipe($2()))}).pipe($1({method:"GET",uri:"/v1/buckets",code:200}));$6({data:#2,pagination:#10:0})`,[_,b,S,l,E,s,u,D,__d39,t,__d32,A,c,v,y,k]):i(We,e));const Ge=/*@__PURE__*/ m(e=>e===r?d(`GetBuildResponse`,`{input:#1,output:#5,errors:[$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"GetBuild"};$5(>6)@"GetBuildRequest";$5(>7)@"%DataResourcesItem";$6(#2);$5(>8)@"%Data";$5(>9)@"%";$4({buildId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/builds/{buildId}",code:200}));$4({resourceType:$3,resourceId:$3,action:$3,createdAt:$3});$4({id:$3,source:$3,state:$3,phase:$7($3),commitSha:$3,branchName:$3,gitRepoId:$7($3),projectId:$7($3),branchId:$7($3),externalLogUrl:$7($3),deployedUrl:$7($3),applicationTopologyContentHash:$7($3),errorMessage:$7($3),failingStep:$7($3),createdAt:$3,startedAt:$7($3),finishedAt:$7($3),resources:#3});$4({data:#4})`,[_,b,x,l,u,D,t,a,A,F,c,v,y,k]):i(Ge,e));const Ke=/*@__PURE__*/ m(e=>e===r?d(`GetBuilds`,`{input:#1,output:#3,errors:[$11,$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$7(>4)@"%Request";$9(#8:0);$7(>5)@"%Response";$6({cursor:$4($3.pipe($2())),limit:$4($5.pipe($2())),projectId:$4($3.pipe($2())),branchId:$4($3.pipe($2())),state:$4($3.pipe($2()))}).pipe($1({method:"GET",uri:"/v1/builds",code:200}));$6({data:#2,pagination:#10:0})`,[_,b,S,l,E,s,u,D,__d1,t,__d32,A,F,c,v,y,k]):i(Ke,e));const qe=/*@__PURE__*/ m(e=>e===r?d(`GetConnection`,`{input:#1,output:#2,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>3)@"%Request";$5(>4)@"%Response";$4({id:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/connections/{id}",code:200}));$4({data:#6:0})`,[_,b,x,l,u,D,__d9,A,F,I,c,v,y,k]):i(qe,e));const Je=/*@__PURE__*/ m(e=>e===r?d(`GetConnections`,`{input:#1,output:#8:0,errors:[$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$7(>2)@"%Request";$6({cursor:$4($3.pipe($2())),limit:$4($5.pipe($2())),databaseId:$4($3.pipe($2()))}).pipe($1({method:"GET",uri:"/v1/connections",code:200}))`,[_,b,S,l,E,s,u,D,__d33,A,c,v,y,k]):i(Je,e));const Ye=/*@__PURE__*/ m(e=>e===r?d(`GetDatabase`,`{input:#1,output:#4,errors:[$14,$15,$16,$17,$18],protocol:$19,retry:$20,telemetry:$21,span:"%"};$5(>5)@"%Request";$5(>6);$5(>7)@"%ResponseData";$5(>8)@"%Response";$4({databaseId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/databases/{databaseId}",code:200}));$8([#6:0,#7:0,#6:1]);$4({id:$3,type:$3,url:$3,name:$3,status:$3,createdAt:$3,isDefault:$9,defaultConnectionId:$10($3),connections:#11:0,project:#12:0,region:$10(#13:0),source:$10(#2),branchId:$10($3),logicalId:$10($3)});$4({data:#3})`,[_,b,x,l,u,D,__d7,__d5,h,n,a,__d10,__d37,__d4,A,P,F,I,c,v,y,k]):i(Ye,e));const Xe=/*@__PURE__*/ m(e=>e===r?d(`GetDatabaseBackups`,`{input:#1,output:#6,errors:[$12,$13,$14,$15],protocol:$16,retry:$17,telemetry:$18,span:"%"};$8(>7)@"%Request";$8(>8)@"%ResponseDataItem";$9(#2);$8(>9)@"%ResponseMeta";$8(>10)@"%ResponsePagination";$8(>11)@"%Response";$7({databaseId:$3.pipe($2()),limit:$6($5.pipe($4()))}).pipe($1({method:"GET",uri:"/v1/databases/{databaseId}/backups",code:200}));$7({id:$3,backupType:$3,createdAt:$3,size:$6($5),status:$3,type:$6($3)});$7({backupRetentionDays:$5});$7({hasMore:$10,limit:$11($5)});$7({data:#3,meta:#4,pagination:#5})`,[_,b,x,l,S,s,E,u,D,t,n,a,A,F,I,c,v,y,k]):i(Xe,e));const Ze=/*@__PURE__*/ m(e=>e===r?d(`GetDatabaseConnections`,`{input:#1,output:#9:0,errors:[$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$8(>2)@"%Request";$7({databaseId:$3.pipe($2()),cursor:$5($3.pipe($4())),limit:$5($6.pipe($4()))}).pipe($1({method:"GET",uri:"/v1/databases/{databaseId}/connections",code:200}))`,[_,b,x,l,S,E,s,u,D,__d33,I,c,v,y,k]):i(Ze,e));const Qe=/*@__PURE__*/ m(e=>e===r?d(`GetDatabases`,`{input:#1,output:#5,errors:[$18,$19,$20],protocol:$21,retry:$22,telemetry:$23,span:"%"};$7(>6)@"%Request";$7(>7);$7(>8)@"%ResponseDataItem";$16(#3);$7(>9)@"%Response";$6({cursor:$4($3.pipe($2())),limit:$4($5.pipe($2())),projectId:$4($3.pipe($2())),logicalId:$4($3.pipe($2())),branchId:$4($3.pipe($2())),branchGitName:$4($3.pipe($2()))}).pipe($1({method:"GET",uri:"/v1/databases",code:200}));$10([#8:0,#9:0,#8:1]);$6({id:$3,type:$3,url:$3,name:$3,status:$3,createdAt:$3,isDefault:$11,defaultConnectionId:$12($3),connections:#13:0,project:#14:0,region:$12(#15:0),source:$12(#2),branchId:$12($3),logicalId:$12($3)});$6({data:#4,pagination:#17:0})`,[_,b,S,l,E,s,u,D,__d7,__d5,h,n,a,__d10,__d37,__d4,t,__d32,A,P,c,v,y,k]):i(Qe,e));const $e=/*@__PURE__*/ m(e=>e===r?d(`GetDatabaseUsage`,`{input:#1,output:#5,errors:[$9,$10,$11,$12],protocol:$13,retry:$14,telemetry:$15,span:"%"};$7(>6)@"%Request";$7(>7)@"%ResponsePeriod";$7(>8)@"%ResponseMetricsOperations";$7(>9)@"%ResponseMetrics";$7(>10)@"%Response";$6({databaseId:$3.pipe($2()),startDate:$5($3.pipe($4())),endDate:$5($3.pipe($4()))}).pipe($1({method:"GET",uri:"/v1/databases/{databaseId}/usage",code:200}));$6({start:$3,end:$3});$6({used:$8,unit:$3});$6({operations:#3,storage:#3});$6({period:#2,metrics:#4,generatedAt:$3})`,[_,b,x,l,S,E,u,D,s,A,F,I,c,v,y,k]):i($e,e));const et=/*@__PURE__*/ m(e=>e===r?d(`GetDeployment`,`{input:#1,output:#5,errors:[$10,$11,$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$5(>6)@"%Request";$6($3,$3);$5(>7)@"%ResponseDataPortMapping";$5(>8)@"%ResponseData";$5(>9)@"%Response";$4({deploymentId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/deployments/{deploymentId}",code:200}));$4({http:$8($7)});$4({id:$3,type:$3,url:$3,serviceId:$3,foundryVersionId:$3,status:$3,previewDomain:$9($3),envVars:$8(#2),portMapping:$8(#3),createdAt:$3});$4({data:#4})`,[_,b,x,l,u,D,ee,s,E,a,A,P,F,c,v,y,k]):i(et,e));const tt=/*@__PURE__*/ m(e=>e===r?d(`GetDeploymentLogs`,`{input:#1,output:#11:0,errors:[$12,$13,$14,$15],protocol:$16,retry:$17,telemetry:$18,span:"%"};$10(>2)@"%Request";$9({deploymentId:$3.pipe($2()),tail:$6($5.pipe($4())),from_start:$6($8.pipe($4(),$7())),cursor:$6($3.pipe($4()))}).pipe($1({method:"GET",uri:"/v1/deployments/{deploymentId}/logs",code:200}))`,[_,b,x,l,S,s,E,ie,n,u,D,__d11,A,P,F,c,v,y,k]):i(tt,e));const nt=/*@__PURE__*/ m(e=>e===r?d(`GetDomain`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({domainId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/domains/{domainId}",code:200}))`,[_,b,x,l,u,D,__d15,A,P,F,c,v,y,k]):i(nt,e));const rt=/*@__PURE__*/ m(e=>e===r?d(`GetDomainOwnership`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({domainOwnershipId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/domain-ownerships/{domainOwnershipId}",code:200}))`,[_,b,x,l,u,D,__d12,A,F,c,v,y,k]):i(rt,e));const it=/*@__PURE__*/ m(e=>e===r?d(`GetEnvironmentVariable`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({envVarId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/environment-variables/{envVarId}",code:200}))`,[_,b,x,l,u,D,__d17,A,F,I,c,v,y,k]):i(it,e));const at=/*@__PURE__*/ m(e=>e===r?d(`GetEnvironmentVariables`,`{input:#1,output:#3,errors:[$11,$12,$13,$14],protocol:$15,retry:$16,telemetry:$17,span:"%"};$7(>4)@"%Request";$9(#8:0);$7(>5)@"%Response";$6({cursor:$4($3.pipe($2())),limit:$4($5.pipe($2())),projectId:$4($3.pipe($2())),class:$4($3.pipe($2())),key:$4($3.pipe($2())),branchId:$4($3.pipe($2()))}).pipe($1({method:"GET",uri:"/v1/environment-variables",code:200}));$6({data:#2,pagination:#10:0})`,[_,b,S,l,E,s,u,D,__d18,t,__d32,F,A,I,c,v,y,k]):i(at,e));const ot=/*@__PURE__*/ m(e=>e===r?d(`GetIntegration`,`{input:#1,output:#2,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>3)@"%Request";$5(>4)@"%Response";$4({id:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/integrations/{id}",code:200}));$4({data:#6:2})`,[_,b,x,l,u,D,__d34,A,F,I,c,v,y,k]):i(ot,e));const st=/*@__PURE__*/ m(e=>e===r?d(`GetIntegrations`,`{input:#1,output:#8:1,errors:[$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$7(>2)@"%Request";$6({cursor:$4($3.pipe($2())),limit:$4($5.pipe($2())),workspaceId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/integrations",code:200}))`,[_,b,S,l,E,s,u,D,__d36,A,c,v,y,k]):i(st,e));const ct=/*@__PURE__*/ m(e=>e===r?d(`GetMeResponse`,`{input:#1,output:#5,errors:[$7],protocol:$8,retry:$9,telemetry:$10,span:"GetMe"};$3(>6)@"GetMeRequest";$3(>7)@"%DataUser";$3(>8)@"%DataCredential";$3(>9)@"%Data";$3(>10)@"%";$2({}).pipe($1({method:"GET",uri:"/v1/me",code:200}));$2({id:$4,email:$4,name:$5($4)});$2({type:$4,id:$5($4),name:$5($4)});$2({user:$5(#2),workspace:$5(#6:0),credential:#3});$2({data:#4})`,[_,b,u,D,l,a,__d4,c,v,y,k]):i(ct,e));const lt=/*@__PURE__*/ m(e=>e===r?d(`GetProject`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({id:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/projects/{id}",code:200}))`,[_,b,x,l,u,D,__d40,A,F,I,c,v,y,k]):i(lt,e));const ut=/*@__PURE__*/ m(e=>e===r?d(`GetProjectBranchAlchemyStateStateStacks`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({projectId:$3.pipe($2()),branchId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/state/stacks",code:200}))`,[_,b,x,l,u,D,__d42,A,F,j,c,v,y,k]):i(ut,e));const dt=/*@__PURE__*/ m(e=>e===r?d(`GetProjectBranchAlchemyStateStateStackStageOutput`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({projectId:$3.pipe($2()),branchId:$3.pipe($2()),stack:$3.pipe($2()),stage:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/state/stacks/{stack}/stages/{stage}/output",code:200}))`,[_,b,x,l,u,D,__d43,A,F,j,c,v,y,k]):i(dt,e));const ft=/*@__PURE__*/ m(e=>e===r?d(`GetProjectBranchAlchemyStateStateStackStageReplacedResources`,`{input:#1,output:#3,errors:[$9,$10,$11,$12],protocol:$13,retry:$14,telemetry:$15,span:"%"};$5(>4)@"%Request";$7($6);$5(>5)@"%Response";$4({projectId:$3.pipe($2()),branchId:$3.pipe($2()),stack:$3.pipe($2()),stage:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/state/stacks/{stack}/stages/{stage}/replaced-resources",code:200}));#2.pipe($8())`,[_,b,x,l,u,D,g,t,C,A,F,j,c,v,y,k]):i(ft,e));const pt=/*@__PURE__*/ m(e=>e===r?d(`GetProjectBranchAlchemyStateStateStackStageResource`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({projectId:$3.pipe($2()),branchId:$3.pipe($2()),stack:$3.pipe($2()),stage:$3.pipe($2()),fqn:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/state/stacks/{stack}/stages/{stage}/resources/{fqn}",code:200}))`,[_,b,x,l,u,D,__d43,A,F,j,c,v,y,k]):i(pt,e));const mt=/*@__PURE__*/ m(e=>e===r?d(`GetProjectBranchAlchemyStateStateStackStageResources`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({projectId:$3.pipe($2()),branchId:$3.pipe($2()),stack:$3.pipe($2()),stage:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/state/stacks/{stack}/stages/{stage}/resources",code:200}))`,[_,b,x,l,u,D,__d42,A,F,j,c,v,y,k]):i(mt,e));const ht=/*@__PURE__*/ m(e=>e===r?d(`GetProjectBranchAlchemyStateStateStackStages`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({projectId:$3.pipe($2()),branchId:$3.pipe($2()),stack:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/state/stacks/{stack}/stages",code:200}))`,[_,b,x,l,u,D,__d42,A,F,j,c,v,y,k]):i(ht,e));const gt=/*@__PURE__*/ m(e=>e===r?d(`GetProjectBranchAlchemyStateVersion`,`{input:#1,output:#2,errors:[$7],protocol:$8,retry:$9,telemetry:$10,span:"%"};$5(>3)@"%Request";$5(>4)@"%Response";$4({projectId:$3.pipe($2()),branchId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/version",code:200}));$4({version:$6})`,[_,b,x,l,u,D,s,c,v,y,k]):i(gt,e));const _t=/*@__PURE__*/ m(e=>e===r?d(`GetProjectBranchApplicationTopology`,`{input:#1,output:#6:8,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({projectId:$3.pipe($2()),branchId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/projects/{projectId}/branches/{branchId}/application-topology",code:200}))`,[_,b,x,l,u,D,__d44,A,F,c,v,y,k]):i(_t,e));const vt=/*@__PURE__*/ m(e=>e===r?d(`GetProjectBranches`,`{input:#1,output:#3,errors:[$12,$13,$14,$15],protocol:$16,retry:$17,telemetry:$18,span:"%"};$8(>4)@"%Request";$10(#9:0);$8(>5)@"%Response";$7({projectId:$3.pipe($2()),cursor:$5($3.pipe($4())),limit:$5($6.pipe($4())),gitName:$5($3.pipe($4())),gitNameContains:$5($3.pipe($4()))}).pipe($1({method:"GET",uri:"/v1/projects/{projectId}/branches",code:200}));$7({data:#2,pagination:#11:0})`,[_,b,x,l,S,E,s,u,D,__d21,t,__d32,A,F,I,c,v,y,k]):i(vt,e));const yt=/*@__PURE__*/ m(e=>e===r?d(`GetProjectBranchUrls`,`{input:#1,output:#8:1,errors:[$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$7(>2)@"%Request";$6({projectId:$3.pipe($2()),branchId:$3.pipe($2()),logicalId:$5($3.pipe($4()))}).pipe($1({method:"GET",uri:"/v1/projects/{projectId}/branches/{branchId}/urls",code:200}))`,[_,b,x,l,S,E,u,D,__d46,A,F,c,v,y,k]):i(yt,e));const bt=/*@__PURE__*/ m(e=>e===r?d(`GetProjectDatabases`,`{input:#1,output:#5,errors:[$19,$20,$21,$22],protocol:$23,retry:$24,telemetry:$25,span:"%"};$8(>6)@"%Request";$8(>7);$8(>8)@"%ResponseDataItem";$17(#3);$8(>9)@"%Response";$7({projectId:$3.pipe($2()),cursor:$5($3.pipe($4())),limit:$5($6.pipe($4()))}).pipe($1({method:"GET",uri:"/v1/projects/{projectId}/databases",code:200}));$11([#9:0,#10:0,#9:1]);$7({id:$3,type:$3,url:$3,name:$3,status:$3,createdAt:$3,isDefault:$12,defaultConnectionId:$13($3),connections:#14:0,project:#15:0,region:$13(#16:0),source:$13(#2),branchId:$13($3),logicalId:$13($3)});$7({data:#4,pagination:#18:0})`,[_,b,x,l,S,E,s,u,D,__d7,__d5,h,n,a,__d10,__d37,__d4,t,__d32,A,F,I,c,v,y,k]):i(bt,e));const xt=/*@__PURE__*/ m(e=>e===r?d(`GetProjects`,`{input:#1,output:#3,errors:[$11,$12],protocol:$13,retry:$14,telemetry:$15,span:"%"};$7(>4)@"%Request";$9(#8:0);$7(>5)@"%Response";$6({cursor:$4($3.pipe($2())),limit:$4($5.pipe($2())),logicalId:$4($3.pipe($2()))}).pipe($1({method:"GET",uri:"/v1/projects",code:200}));$6({data:#2,pagination:#10:0})`,[_,b,S,l,E,s,u,D,__d41,t,__d32,A,c,v,y,k]):i(xt,e));const St=/*@__PURE__*/ m(e=>e===r?d(`GetRegions`,`{input:#1,output:#4,errors:[$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$6(>5)@"%Request";$6(>6)@"%ResponseDataItem";$7(#2);$6(>7)@"%Response";$5({product:$4($3.pipe($2()))}).pipe($1({method:"GET",uri:"/v1/regions",code:200}));$5({id:$3,type:$3,name:$3,product:$3,status:$4($3)});$5({data:#3})`,[_,b,S,l,E,u,D,t,A,c,v,y,k]):i(St,e));const Ct=/*@__PURE__*/ m(e=>e===r?d(`GetRegionsAccelerate`,`{input:#1,output:#4,errors:[$6],protocol:$7,retry:$8,telemetry:$9,span:"%"};$3(>5)@"%Request";$3(>6)@"%ResponseDataItem";$5(#2);$3(>7)@"%Response";$2({}).pipe($1({method:"GET",uri:"/v1/regions/accelerate",code:200}));$2({id:$4,type:$4,name:$4});$2({data:#3})`,[_,b,u,D,l,t,c,v,y,k]):i(Ct,e));const wt=/*@__PURE__*/ m(e=>e===r?d(`GetRegionsPostgres`,`{input:#1,output:#4,errors:[$6],protocol:$7,retry:$8,telemetry:$9,span:"%"};$3(>5)@"%Request";$3(>6)@"%ResponseDataItem";$5(#2);$3(>7)@"%Response";$2({}).pipe($1({method:"GET",uri:"/v1/regions/postgres",code:200}));$2({id:$4,type:$4,name:$4,status:$4});$2({data:#3})`,[_,b,u,D,l,t,c,v,y,k]):i(wt,e));const Tt=/*@__PURE__*/ m(e=>e===r?d(`GetScmInstallationRepositories`,`{input:#1,output:#4,errors:[$12,$13,$14,$15],protocol:$16,retry:$17,telemetry:$18,span:"%"};$8(>5)@"%Request";$8(>6)@"%ResponseDataItem";$10(#2);$8(>7)@"%Response";$7({installationId:$3.pipe($2()),cursor:$5($3.pipe($4())),limit:$5($6.pipe($4()))}).pipe($1({method:"GET",uri:"/v1/scm-installations/{installationId}/repositories",code:200}));$7({id:$6,type:$3,fullName:$3,defaultBranch:$3,isPrivate:$9});$7({data:#3,pagination:#11:0})`,[_,b,x,l,S,E,s,u,D,n,t,__d32,A,F,I,c,v,y,k]):i(Tt,e));const Et=/*@__PURE__*/ m(e=>e===r?d(`GetScmInstallations`,`{input:#1,output:#4,errors:[$11,$12],protocol:$13,retry:$14,telemetry:$15,span:"%"};$7(>5)@"%Request";$7(>6)@"%ResponseDataItem";$9(#2);$7(>7)@"%Response";$6({cursor:$4($3.pipe($2())),limit:$4($5.pipe($2())),workspaceId:$3.pipe($2()),repository:$4($3.pipe($2()))}).pipe($1({method:"GET",uri:"/v1/scm-installations",code:200}));$6({id:$3,type:$3,url:$3,provider:$3,installationId:$5,accountId:$5,accountLogin:$3,accountType:$3,suspended:$8,createdAt:$3,updatedAt:$3});$6({data:#3,pagination:#10:0,hint:$4($3)})`,[_,b,S,l,E,s,u,D,n,t,__d32,A,c,v,y,k]):i(Et,e));const Dt=/*@__PURE__*/ m(e=>e===r?d(`GetService`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({serviceId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/services/{serviceId}",code:200}))`,[_,b,x,l,u,D,__d24,A,P,F,c,v,y,k]):i(Dt,e));const Ot=/*@__PURE__*/ m(e=>e===r?d(`GetServiceDeployments`,`{input:#1,output:#4,errors:[$11,$12,$13,$14],protocol:$15,retry:$16,telemetry:$17,span:"%"};$8(>5)@"%Request";$8(>6)@"%ResponseDataItem";$9(#2);$8(>7)@"%Response";$7({serviceId:$3.pipe($2()),cursor:$5($3.pipe($4())),limit:$5($6.pipe($4()))}).pipe($1({method:"GET",uri:"/v1/services/{serviceId}/deployments",code:200}));$7({id:$3,type:$3,url:$3,serviceId:$3,foundryVersionId:$3,createdAt:$3});$7({data:#3,pagination:#10:0})`,[_,b,x,l,S,E,s,u,D,t,__d32,A,P,F,c,v,y,k]):i(Ot,e));const kt=/*@__PURE__*/ m(e=>e===r?d(`GetServiceDomains`,`{input:#1,output:#3,errors:[$9,$10,$11,$12],protocol:$13,retry:$14,telemetry:$15,span:"%"};$5(>4)@"%Request";$7(#6:2);$5(>5)@"%Response";$4({serviceId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/services/{serviceId}/domains",code:200}));$4({data:#2,pagination:#8:0})`,[_,b,x,l,u,D,__d16,t,__d45,A,P,F,c,v,y,k]):i(kt,e));const At=/*@__PURE__*/ m(e=>e===r?d(`GetServices`,`{input:#1,output:#3,errors:[$11,$12,$13,$14,$15],protocol:$16,retry:$17,telemetry:$18,span:"%"};$7(>4)@"%Request";$9(#8:0);$7(>5)@"%Response";$6({cursor:$4($3.pipe($2())),limit:$4($5.pipe($2())),projectId:$4($3.pipe($2())),logicalId:$4($3.pipe($2())),branchId:$4($3.pipe($2())),branchGitName:$4($3.pipe($2()))}).pipe($1({method:"GET",uri:"/v1/services",code:200}));$6({data:#2,pagination:#10:0})`,[_,b,S,l,E,s,u,D,__d23,t,__d32,A,F,P,I,c,v,y,k]):i(At,e));const jt=/*@__PURE__*/ m(e=>e===r?d(`GetServiceUrls`,`{input:#1,output:#6:1,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({serviceId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/services/{serviceId}/urls",code:200}))`,[_,b,x,l,u,D,__d46,A,F,c,v,y,k]):i(jt,e));const Mt=/*@__PURE__*/ m(e=>e===r?d(`GetSourceRepositories`,`{input:#1,output:#3,errors:[$11,$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$7(>4)@"%Request";$9(#8:0);$7(>5)@"%Response";$6({cursor:$4($3.pipe($2())),limit:$4($5.pipe($2())),projectId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/source-repositories",code:200}));$6({data:#2,pagination:#10:0})`,[_,b,S,l,E,s,u,D,__d28,t,__d32,A,F,c,v,y,k]):i(Mt,e));const Nt=/*@__PURE__*/ m(e=>e===r?d(`GetSourceRepository`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({id:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/source-repositories/{id}",code:200}))`,[_,b,x,l,u,D,__d29,A,F,c,v,y,k]):i(Nt,e));const Pt=/*@__PURE__*/ m(e=>e===r?[`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"GetUrl"};$5(>2)@"GetUrlRequest";$4({id:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/urls/{id}",code:200}))`,[_,b,x,l,u,D,__d26,A,F,c,v,y,k]]:i(Pt,e));const Ft=/*@__PURE__*/ m(e=>e===r?d(`GetWorkspace`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({id:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/workspaces/{id}",code:200}))`,[_,b,x,l,u,D,__d30,A,F,I,c,v,y,k]):i(Ft,e));const It=/*@__PURE__*/ m(e=>e===r?d(`GetWorkspaceDomainOwnerships`,`{input:#1,output:#3,errors:[$12,$13,$14,$15],protocol:$16,retry:$17,telemetry:$18,span:"%"};$8(>4)@"%Request";$10(#9:0);$8(>5)@"%Response";$7({workspaceId:$3.pipe($2()),cursor:$5($3.pipe($4())),limit:$5($6.pipe($4())),domain:$5($3.pipe($4()))}).pipe($1({method:"GET",uri:"/v1/workspaces/{workspaceId}/domain-ownerships",code:200}));$7({data:#2,pagination:#11:0})`,[_,b,x,l,S,E,s,u,D,__d13,t,__d32,A,F,I,c,v,y,k]):i(It,e));const Lt=/*@__PURE__*/ m(e=>e===r?d(`GetWorkspaceDomainOwnershipsVerification`,`{input:#1,output:#2,errors:[$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$6(>3)@"%Request";$6(>4)@"%Response";$5({workspaceId:$3.pipe($2()),domain:$3.pipe($4())}).pipe($1({method:"GET",uri:"/v1/workspaces/{workspaceId}/domain-ownerships/verification",code:200}));$5({data:#7:0})`,[_,b,x,l,S,u,D,__d14,A,F,I,c,v,y,k]):i(Lt,e));const Rt=/*@__PURE__*/ m(e=>e===r?d(`GetWorkspaceIntegrations`,`{input:#1,output:#9:1,errors:[$10,$11,$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$8(>2)@"%Request";$7({workspaceId:$3.pipe($2()),cursor:$5($3.pipe($4())),limit:$5($6.pipe($4()))}).pipe($1({method:"GET",uri:"/v1/workspaces/{workspaceId}/integrations",code:200}))`,[_,b,x,l,S,E,s,u,D,__d36,A,F,I,c,v,y,k]):i(Rt,e));const zt=/*@__PURE__*/ m(e=>e===r?d(`GetWorkspaces`,`{input:#1,output:#3,errors:[$11,$12],protocol:$13,retry:$14,telemetry:$15,span:"%"};$7(>4)@"%Request";$9(#8:0);$7(>5)@"%Response";$6({cursor:$4($3.pipe($2())),limit:$4($5.pipe($2()))}).pipe($1({method:"GET",uri:"/v1/workspaces",code:200}));$6({data:#2,pagination:#10:0})`,[_,b,S,l,E,s,u,D,__d31,t,__d32,A,c,v,y,k]):i(zt,e));const Bt=/*@__PURE__*/ m(e=>e===r?d(`GetWorkspaceServiceTokens`,`{input:#1,output:#4,errors:[$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$8(>5)@"%Request";$8(>6)@"%ResponseDataItem";$10(#2);$8(>7)@"%Response";$7({workspaceId:$3.pipe($2()),cursor:$5($3.pipe($4())),limit:$5($6.pipe($4()))}).pipe($1({method:"GET",uri:"/v1/workspaces/{workspaceId}/service-tokens",code:200}));$7({id:$3,type:$3,name:$3,scope:$3,projectId:$9($3),valueHint:$3,createdAt:$3,expiresAt:$5($9($3))});$7({data:#3,pagination:#11:0})`,[_,b,x,l,S,E,s,u,D,a,t,__d32,A,c,v,y,k]):i(Bt,e));const $=/*@__PURE__*/ m(e=>e===r?d(`GetWorkspaceSubscription`,`{input:#1,output:#3,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>4)@"%Request";$5(>5)@"%ResponseData";$5(>6)@"%Response";$4({id:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/workspaces/{id}/subscription",code:200}));$4({planName:$3,usageBlocked:$6,upgradeUrl:$3});$4({data:#2})`,[_,b,x,l,u,D,n,A,F,c,v,y,k]):i($,e));const Vt=/*@__PURE__*/ m(e=>e===r?d(`PutBuildResource`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({buildId:$3.pipe($2()),resourceType:$3.pipe($2()),resourceId:$3.pipe($2()),action:$3}).pipe($1({method:"PUT",uri:"/v1/builds/{buildId}/resources/{resourceType}/{resourceId}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,c,v,y,k]):i(Vt,e));const Ht=/*@__PURE__*/ m(e=>e===r?d(`PutProjectBranchAlchemyStateStateStackStageOutput`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({projectId:$3.pipe($2()),branchId:$3.pipe($2()),stack:$3.pipe($2()),stage:$3.pipe($2())}).pipe($1({method:"PUT",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/state/stacks/{stack}/stages/{stage}/output",code:200}))`,[_,b,x,l,u,D,__d43,A,F,j,c,v,y,k]):i(Ht,e));const Ut=/*@__PURE__*/ m(e=>e===r?d(`PutProjectBranchAlchemyStateStateStackStageResource`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({projectId:$3.pipe($2()),branchId:$3.pipe($2()),stack:$3.pipe($2()),stage:$3.pipe($2()),fqn:$3.pipe($2())}).pipe($1({method:"PUT",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/state/stacks/{stack}/stages/{stage}/resources/{fqn}",code:200}))`,[_,b,x,l,u,D,__d43,A,F,j,c,v,y,k]):i(Ut,e));const Wt=/*@__PURE__*/ m(e=>e===r?d(`PutProjectBranchApplicationTopology`,`{input:#1,output:#5:8,errors:[$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$7(>2)@"%Request";$6({projectId:$3.pipe($2()),branchId:$3.pipe($2()),contentHash:$4($3),nodes:#5:1,ports:#5:3,edges:#5:6}).pipe($1({method:"PUT",uri:"/v1/projects/{projectId}/branches/{branchId}/application-topology",code:200}))`,[_,b,x,l,E,__d44,u,D,A,F,I,c,v,y,k]):i(Wt,e));const Gt=/*@__PURE__*/ m(e=>e===r?d(`UpdateBranch`,`{input:#1,output:#9:0,errors:[$10,$11,$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$8(>2)@"%Request";$7({branchId:$3.pipe($2()),isDefault:$6($5($4))}).pipe($1({method:"PATCH",uri:"/v1/branches/{branchId}",code:200}))`,[_,b,x,l,n,a,E,u,D,__d20,A,F,I,c,v,y,k]):i(Gt,e));const Kt=/*@__PURE__*/ m(e=>e===r?d(`UpdateBucket`,`{input:#1,output:#8:0,errors:[$9,$10,$11,$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$7(>2)@"%Request";$6({bucketId:$3.pipe($2()),displayName:$4($3),branchId:$4($3),branchGitName:$4($3),logicalId:$4($5($3))}).pipe($1({method:"PATCH",uri:"/v1/buckets/{bucketId}",code:200}))`,[_,b,x,l,E,a,u,D,__d38,A,F,j,I,c,v,y,k]):i(Kt,e));const qt=/*@__PURE__*/ m(e=>e===r?d(`UpdateBuild`,`{input:#1,output:#7:0,errors:[$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$6(>2)@"%Request";$5({buildId:$3.pipe($2()),phase:$4($3),state:$4($3),failingStep:$4($3),errorMessage:$4($3),externalLogUrl:$4($3),projectId:$4($3),branchId:$4($3),deployedUrl:$4($3),applicationTopologyContentHash:$4($3)}).pipe($1({method:"PATCH",uri:"/v1/builds/{buildId}",code:200}))`,[_,b,x,l,E,u,D,__d0,A,F,j,c,v,y,k]):i(qt,e));const Jt=/*@__PURE__*/ m(e=>e===r?d(`UpdateDatabase`,`{input:#1,output:#4,errors:[$15,$16,$17,$18,$19,$20],protocol:$21,retry:$22,telemetry:$23,span:"%"};$7(>5)@"%Request";$7(>6);$7(>7)@"%ResponseData";$7(>8)@"%Response";$6({databaseId:$3.pipe($2()),name:$4($3),branchId:$4($5($3)),branchGitName:$4($5($3)),logicalId:$4($5($3))}).pipe($1({method:"PATCH",uri:"/v1/databases/{databaseId}",code:200}));$10([#8:0,#9:0,#8:1]);$6({id:$3,type:$3,url:$3,name:$3,status:$3,createdAt:$3,isDefault:$11,defaultConnectionId:$5($3),connections:#12:0,project:#13:0,region:$5(#14:0),source:$5(#2),branchId:$5($3),logicalId:$5($3)});$6({data:#3})`,[_,b,x,l,E,a,u,D,__d7,__d5,h,n,__d10,__d37,__d4,A,P,F,j,I,c,v,y,k]):i(Jt,e));const Yt=/*@__PURE__*/ m(e=>e===r?d(`UpdateEnvironmentVariable`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({envVarId:$3.pipe($2()),value:$3}).pipe($1({method:"PATCH",uri:"/v1/environment-variables/{envVarId}",code:200}))`,[_,b,x,l,u,D,__d17,A,F,I,c,v,y,k]):i(Yt,e));const Xt=/*@__PURE__*/ m(e=>e===r?d(`UpdateProject`,`{input:#2,output:#9:0,errors:[$10,$11,$12,$13,$14],protocol:$15,retry:$16,telemetry:$17,span:"%"};$3($1,$2);$8(>3)@"%Request";$7({id:$1.pipe($5()),name:$6($1),settings:$6(#1)}).pipe($4({method:"PATCH",uri:"/v1/projects/{id}",code:200}))`,[_,l,g,ee,b,x,E,u,D,__d40,A,P,F,I,c,v,y,k]):i(Xt,e));const Zt=/*@__PURE__*/ m(e=>e===r?d(`UpdateProjectBranchAlchemyStateLease`,`{input:#1,output:#8:1,errors:[$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$7(>2)@"%Request";$6({projectId:$3.pipe($2()),branchId:$3.pipe($2()),ttlSeconds:$5($4)}).pipe($1({method:"PATCH",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/lease",code:200}))`,[_,b,x,l,s,E,u,D,__d22,A,F,c,v,y,k]):i(Zt,e));const Qt=/*@__PURE__*/ m(e=>e===r?d(`UpdateService`,`{input:#1,output:#8:0,errors:[$9,$10,$11,$12,$13,$14],protocol:$15,retry:$16,telemetry:$17,span:"%"};$7(>2)@"%Request";$6({serviceId:$3.pipe($2()),displayName:$4($3),logicalId:$4($5($3)),branchId:$4($5($3)),branchGitName:$4($5($3))}).pipe($1({method:"PATCH",uri:"/v1/services/{serviceId}",code:200}))`,[_,b,x,l,E,a,u,D,__d24,A,P,F,j,I,c,v,y,k]):i(Qt,e));const $t=/*@__PURE__*/ m(e=>e===r?d(`UpdateUrl`,`{input:#1,output:#9:0,errors:[$10,$11,$12,$13,$14],protocol:$15,retry:$16,telemetry:$17,span:"%"};$8(>2)@"%Request";$7({id:$3.pipe($2()),hostname:$4($3),serviceId:$4($3),logicalId:$4($5($3)),createDomainOwnership:$4($6)}).pipe($1({method:"PATCH",uri:"/v1/urls/{id}",code:200}))`,[_,b,x,l,E,a,n,u,D,__d26,A,F,j,I,c,v,y,k]):i($t,e));function __d0(){return[`$3(>1)@"CreateBuildResponse";$2({data:#1:0})`,[_,__d1,u,D]]}function __d1(){return[`$4(>1)@"CreateBuildResponseData";$3({id:$1,source:$1,state:$1,phase:$2($1),commitSha:$1,branchName:$1,gitRepoId:$2($1),projectId:$2($1),branchId:$2($1),externalLogUrl:$2($1),deployedUrl:$2($1),applicationTopologyContentHash:$2($1),errorMessage:$2($1),failingStep:$2($1),createdAt:$1,startedAt:$2($1),finishedAt:$2($1)})`,[_,l,a,u,D]]}function __d2(){return[`$3(>1)@"CreateConnectionResponseDataDirectConnection";$2({host:$1,pass:$1,user:$1})`,[_,l,u,D]]}function __d3(){return[`$5(>4)@"CreateConnectionResponseDataEndpointsDirect";$5(>5)@"CreateConnectionResponseDataEndpoints";$5(>6)@"CreateConnectionResponseData";$5(>7)@"CreateConnectionResponse";$4({host:$1,port:$2,connectionString:$1.pipe($3({}))});$4({direct:$6(#0),pooled:$6(#0),accelerate:$6(#0)});$4({id:$1,type:$1,url:$1,name:$1,createdAt:$1,kind:$1,endpoints:#1,connectionString:$1.pipe($3({})),directConnection:$6($8(#7:0)),database:#9:0,host:$8($1),pass:$8($1),user:$8($1)});$4({data:#2})`,[_,l,s,w,u,D,E,__d2,a,__d37]]}function __d4(){return[`$3(>1)@"CreateDatabaseResponseDataRegion";$2({id:$1,name:$1})`,[_,l,u,D]]}function __d5(){return[`$3(>1)@"CreateDatabaseRequestSourceCase1";$2({type:$1,databaseId:$1,backupId:$1})`,[_,l,u,D]]}function __d6(){return[`$6(>4)@"CreateDatabaseResponseDataConnectionsItemEndpointsDirect";$6(>5)@"CreateDatabaseResponseDataConnectionsItemEndpoints";$6(>6)@"CreateDatabaseResponseDataConnectionsItem";$10(#2);$5({host:$1,port:$2,connectionString:$4($1.pipe($3({})))});$5({direct:$4(#0),pooled:$4(#0),accelerate:$4(#0)});$5({id:$1,type:$1,url:$1,name:$1,createdAt:$1,kind:$1,endpoints:#1,directConnection:$4($8(#7:0)),database:#9:0})`,[_,l,s,w,E,u,D,__d2,a,__d37,t]]}function __d7(){return[`$3(>2)@"CreateDatabaseRequestSourceCase0";$3(>3)@"CreateDatabaseRequestSourceCase2";$2({type:$1});$2({type:$1,databaseId:$1})`,[_,l,u,D]]}function __d8(){return[`$4(>2)@"CreateDatabaseRestoreResponseDataConnectionsItemEndpointsDirect";$4(>3)@"CreateDatabaseRestoreResponseDataConnectionsItemEndpoints";$3({host:$1,port:$2});$3({direct:$5(#0),pooled:$5(#0),accelerate:$5(#0)})`,[_,l,s,u,D,E]]}function __d9(){return[`$8(>1)@"CreateDatabaseRestoreResponseDataConnectionsItem";$7({id:$1,type:$1,url:$1,name:$1,createdAt:$1,kind:$1,endpoints:#2:1,directConnection:$5($4(#3:0)),database:#6:0})`,[_,l,__d8,__d2,a,E,__d37,u,D]]}function __d10(){return[`$2(#1:0)`,[_,__d9,t]]}function __d11(){return[`$2(>1)@"CreateDeploymentStopResponse";$1({})`,[_,u,D]]}function __d12(){return[`$3(>1)@"CreateDomainOwnershipVerifyResponse";$2({data:#1:0})`,[_,__d13,u,D]]}function __d13(){return[`$6(>1)@"CreateDomainOwnershipVerifyResponseData";$5({id:$1,type:$1,workspaceId:$1,domain:$1,verification:#2:0,status:$1,expiresAt:$3($1),verificationRecordLastSeenAt:$3($1),verificationRecordPresent:$3($4),verificationRecordSyncError:$3($1),createdAt:$1})`,[_,l,__d14,a,n,u,D]]}function __d14(){return[`$4(>1)@"CreateDomainOwnershipVerifyResponseDataVerification";$3({type:$1,name:$1,value:$1,ttl:$2})`,[_,l,s,u,D]]}function __d15(){return[`$3(>1)@"CreateDomainRetryResponse";$2({data:#1:2})`,[_,__d16,u,D]]}function __d16(){return[`$5(>3)@"CreateDomainRetryResponseDataDnsRecordsItem";$6(#0);$5(>4)@"CreateDomainRetryResponseData";$4({type:$1,name:$1,value:$1,ttl:$3($2)});$4({id:$1,type:$1,url:$1,hostname:$1,appId:$1,computeServiceId:$1,status:$1,foundryStatus:$1,failureReason:$3($1),failureCategory:$3($1),certExpiresAt:$3($1),createdAt:$1,updatedAt:$1,dnsRecords:#1})`,[_,l,s,a,u,D,t]]}function __d17(){return[`$3(>1)@"CreateEnvironmentVariableResponse";$2({data:#1:0})`,[_,__d18,u,D]]}function __d18(){return[`$5(>1)@"CreateEnvironmentVariableResponseData";$4({id:$1,type:$1,url:$1,projectId:$1,branchId:$2($1),class:$1,key:$1,valueKid:$1,isManagedBySystem:$3,createdAt:$1,updatedAt:$1})`,[_,l,a,n,u,D]]}function __d19(){return[`$8(>2)@"CreateProjectResponseDataDatabaseApiKeysItem";$9(#0);$7({id:$1,type:$1,url:$1,name:$1,createdAt:$1,kind:$1,endpoints:#2:1,connectionString:$1.pipe($3({})),directConnection:$6($5(#4:0))})`,[_,l,__d8,w,__d2,a,E,u,D,t]]}function __d20(){return[`$3(>1)@"CreateProjectBranchResponse";$2({data:#1:0})`,[_,__d21,u,D]]}function __d21(){return[`$5(>1)@"CreateProjectBranchResponseData";$4({id:$1,type:$1,url:$1,gitName:$1,isDefault:$2,role:$1,createdAt:$1,updatedAt:$1,project:#3:0})`,[_,l,n,__d37,u,D]]}function __d22(){return[`$3(>2)@"CreateProjectBranchAlchemyStateLeaseResponseData";$3(>3)@"CreateProjectBranchAlchemyStateLeaseResponse";$2({leaseId:$1,expiresAt:$1});$2({data:#0})`,[_,l,u,D]]}function __d23(){return[`$5(>1)@"CreateServiceResponseData";$4({id:$1,type:$1,url:$1,name:$1,region:#2:0,projectId:$1,branchId:$3($1),latestDeploymentId:$3($1),appEndpointDomain:$1,createdAt:$1,logicalId:$3($1)})`,[_,l,__d4,a,u,D]]}function __d24(){return[`$3(>1)@"CreateServiceResponse";$2({data:#1:0})`,[_,__d23,u,D]]}function __d25(){return[`$4(>2)@"CreateServicePromoteResponseData";$4(>3)@"CreateServicePromoteResponse";$3({appEndpointDomain:$1,reassignedDomains:$2});$3({data:#0})`,[_,l,s,u,D]]}function __d26(){return[`$3(>1)@"CreateServiceUrlResponse";$2({data:#1:7})`,[_,__d27,u,D]]}function __d27(){return[`$3(>8)@"CreateServiceUrlResponseDataConditions";$3(>9)@"CreateServiceUrlResponseDataOwnershipExpiry";$3(>10)@"CreateServiceUrlResponseDataRecordsItem";$5(#2);$3(>11)@"CreateServiceUrlResponseDataHeldBy";$3(>12)@"CreateServiceUrlResponseDataCustomDomain";$3(>13)@"CreateServiceUrlResponseDataSwitchboardDns";$3(>14)@"CreateServiceUrlResponseData";$2({ownershipVerified:$1,servicePresent:$1,liveDeployment:$1,dnsPointsAtSwitchboard:$1,customDomainBound:$1,certificateActive:$1});$2({expiresAt:$1});$2({condition:$1,type:$1,name:$1,value:$1,ttl:$4});$2({workspaceId:$6($1),projectId:$6($1),serviceId:$6($1),message:$6($1)});$2({id:$1,status:$6($1),failureReason:$6($1),certExpiresAt:$6($1),lastSeenAt:$6($1),certificateRetryRequestedAt:$6($1),certificateIssuanceStuck:$7});$2({accepted:$7,detail:$6($1),lastSeenAt:$1});$2({id:$1,type:$1,branchId:$1,serviceId:$6($1),hostname:$1,logicalId:$6($1),status:$1,conditions:#0,firstUnmetCondition:$6($1),ownershipExpiry:$6(#1),records:#3,heldBy:$6(#4),customDomain:$6(#5),customDomainSyncError:$6($1),switchboardDns:$6(#6),setupUrl:$6($1),createdAt:$1,updatedAt:$1})`,[_,l,u,D,s,t,a,n]]}function __d28(){return[`$5(>1)@"CreateSourceRepositoryResponseData";$4({id:$1,type:$1,url:$1,repoId:$2,provider:$1,repoFullName:$1,defaultBranch:$1,isPrivate:$3,status:$1,projectId:$1,installationId:$1,createdAt:$1,updatedAt:$1})`,[_,l,s,n,u,D]]}function __d29(){return[`$5(>1)@"CreateSourceRepositoryResponse";$4({data:#1:0,hint:$3($2)})`,[_,__d28,l,E,u,D]]}function __d30(){return[`$3(>1)@"CreateWorkspaceResponse";$2({data:#1:0})`,[_,__d31,u,D]]}function __d31(){return[`$3(>1)@"CreateWorkspaceResponseData";$2({id:$1,type:$1,url:$1,name:$1,createdAt:$1})`,[_,l,u,D]]}function __d32(){return[`$5(>1)@"GetBucketKeysResponsePagination";$4({nextCursor:$2($1),hasMore:$3})`,[_,l,a,n,u,D]]}function __d33(){return[`$4(>1)@"GetConnectionsResponse";$3({data:#1:0,pagination:#2:0})`,[_,__d10,__d32,u,D]]}function __d34(){return[`$3(>3)@"GetIntegrationResponseDataClient";$3(>4)@"GetIntegrationResponseDataCreatedByUser";$3(>5)@"GetIntegrationResponseData";$2({id:$1,name:$1,createdAt:$1});$2({id:$1,email:$1,displayName:$4($1)});$2({id:$1,url:$1,createdAt:$1,scopes:#5:0,client:#0,createdByUser:#1})`,[_,l,u,D,a,__d35]]}function __d35(){return[`$2($1)`,[_,l,t]]}function __d36(){return[`$2(#1:2);$5(>2)@"GetIntegrationsResponse";$4({data:#0,pagination:#3:0})`,[_,__d34,t,__d32,u,D]]}function __d37(){return[`$3(>1)@"CreateBucketResponseDataProject";$2({id:$1,url:$1,name:$1})`,[_,l,u,D]]}function __d38(){return[`$3(>1)@"CreateBucketResponse";$2({data:#1:0})`,[_,__d39,u,D]]}function __d39(){return[`$5(>1)@"CreateBucketResponseData";$4({id:$1,type:$1,url:$1,name:$1,providerName:$1,status:$1,createdAt:$1,project:#2:0,branchId:$3($1),logicalId:$3($1)})`,[_,l,__d37,a,u,D]]}function __d40(){return[`$3(>1)@"GetProjectResponse";$2({data:#1:0})`,[_,__d41,u,D]]}function __d41(){return[`$5(>1)@"GetProjectResponseData";$4({id:$1,type:$1,url:$1,name:$1,logicalId:$2($1),createdAt:$1,defaultRegion:$2($1),workspace:#3:0})`,[_,l,a,__d37,u,D]]}function __d42(){return[`$3(>1)@"GetProjectBranchAlchemyStateStateStacksResponse";#2:0.pipe($1())`,[_,C,__d35,D]]}function __d43(){return[`$3(>1)@"GetProjectBranchAlchemyStateStateStackStageOutputResponse";$2.pipe($1())`,[_,C,g,D]]}function __d44(){return[`$5(>9)@"GetProjectBranchApplicationTopologyResponseDataNodesItem";$6(#0);$5(>10)@"GetProjectBranchApplicationTopologyResponseDataPortsItem";$6(#2);$5(>11)@"GetProjectBranchApplicationTopologyResponseDataEdgesItemFrom";$5(>12)@"GetProjectBranchApplicationTopologyResponseDataEdgesItem";$6(#5);$5(>13)@"GetProjectBranchApplicationTopologyResponseData";$5(>14)@"GetProjectBranchApplicationTopologyResponse";$4({logicalId:$1,parentLogicalId:$2($1),kind:$1,type:$3($1)});$4({logicalId:$1,direction:$1,name:$1,contractKind:$3($1),contractHash:$3($1)});$4({logicalId:$1,direction:$1,name:$1});$4({from:#4,to:#4,family:$1,style:$3($1)});$4({nodes:#1,ports:#3,edges:#6,contentHash:$3($1),writtenAt:$3($1)});$4({data:#7})`,[_,l,a,E,u,D,t]]}function __d45(){return[`$5(>1)@"GetProjectBranchUrlsResponsePagination";$4({hasMore:$1,nextCursor:$3($2)})`,[_,n,g,a,u,D]]}function __d46(){return[`$2(#1:7);$5(>2)@"GetProjectBranchUrlsResponse";$4({data:#0,pagination:#3:0})`,[_,__d27,t,__d45,u,D]]}export{A as BadRequest,j as Conflict,M as DomainDnsNotConfigured,N as DomainOwnershipRequired,P as Forbidden,F as NotFound,te as S3BucketName,ne as S3CredentialsError,I as UnprocessableEntity,L as createAuthGithubActionsToken,R as createBucket,z as createBucketKey,B as createBuild,V as createConnection,H as createConnectionRotate,U as createDatabase,W as createDatabaseConnection,G as createDatabaseRestore,K as createDeploymentStart,q as createDeploymentStop,J as createDomainOwnershipVerify,Y as createDomainRetry,X as createEnvironmentVariable,Z as createProject,Q as createProjectBranch,oe as createProjectBranchAlchemyStateLease,se as createProjectDatabase,ce as createProjectTransfer,le as createScmInstallationsInstallIntent,ue as createService,de as createServiceDeployment,fe as createServiceDomain,pe as createServicePromote,me as createServiceRollback,he as createServiceUrl,ge as createSourceRepository,_e as createUrlCheck,ve as createWorkspace,ye as createWorkspaceDomainOwnership,be as createWorkspaceServiceToken,xe as deleteBranch,Se as deleteBucket,Ce as deleteBucketKey,we as deleteConnection,Te as deleteDatabase,Ee as deleteDeployment,De as deleteDomain,Oe as deleteDomainOwnership,ke as deleteEnvironmentVariable,Ae as deleteIntegration,je as deleteProject,Me as deleteProjectBranchAlchemyStateLease,Ne as deleteProjectBranchAlchemyStateStateStack,Pe as deleteProjectBranchAlchemyStateStateStackStageResource,Fe as deleteService,Ie as deleteSourceRepository,Le as deleteUrl,Re as deleteWorkspaceIntegration,ze as deleteWorkspaceServiceToken,Be as getAgentApproval,Ve as getBranch,He as getBucket,Ue as getBucketKeys,We as getBuckets,Ge as getBuild,Ke as getBuilds,qe as getConnection,Je as getConnections,Ye as getDatabase,Xe as getDatabaseBackups,Ze as getDatabaseConnections,$e as getDatabaseUsage,Qe as getDatabases,et as getDeployment,tt as getDeploymentLogs,nt as getDomain,rt as getDomainOwnership,it as getEnvironmentVariable,at as getEnvironmentVariables,ot as getIntegration,st as getIntegrations,ct as getMe,lt as getProject,dt as getProjectBranchAlchemyStateStateStackStageOutput,ft as getProjectBranchAlchemyStateStateStackStageReplacedResources,pt as getProjectBranchAlchemyStateStateStackStageResource,mt as getProjectBranchAlchemyStateStateStackStageResources,ht as getProjectBranchAlchemyStateStateStackStages,ut as getProjectBranchAlchemyStateStateStacks,gt as getProjectBranchAlchemyStateVersion,_t as getProjectBranchApplicationTopology,yt as getProjectBranchUrls,vt as getProjectBranches,bt as getProjectDatabases,xt as getProjects,St as getRegions,Ct as getRegionsAccelerate,wt as getRegionsPostgres,Tt as getScmInstallationRepositories,Et as getScmInstallations,Dt as getService,Ot as getServiceDeployments,kt as getServiceDomains,jt as getServiceUrls,At as getServices,Mt as getSourceRepositories,Nt as getSourceRepository,Pt as getUrl,Ft as getWorkspace,It as getWorkspaceDomainOwnerships,Lt as getWorkspaceDomainOwnershipsVerification,Rt as getWorkspaceIntegrations,Bt as getWorkspaceServiceTokens,$ as getWorkspaceSubscription,zt as getWorkspaces,re as layerS3,Vt as putBuildResource,Ht as putProjectBranchAlchemyStateStateStackStageOutput,Ut as putProjectBranchAlchemyStateStateStackStageResource,Wt as putProjectBranchApplicationTopology,Gt as updateBranch,Kt as updateBucket,qt as updateBuild,Jt as updateDatabase,Yt as updateEnvironmentVariable,Xt as updateProject,Zt as updateProjectBranchAlchemyStateLease,Qt as updateService,$t as updateUrl}; ++import{Ba as e,Wb as t,Xb as n,a as r,c as i,dc as a,e as o,ec as s,errors$UnknownPrismaError as c,fc as ee,hc as l,ic as u,k as d,kc as f,l as p,layer_s3$S3BucketName as te,layer_s3$S3CredentialsError as ne,layer_s3$layerS3 as re,m,mc as h,nc as g,pc as _,protocol$PrismaProtocol as v,retry$Retry as y,traits$Http as b,traits$Label as x,traits$Query as S,traits$RawResponseRoot as C,traits$SensitiveValue as w,traits$StringEncoded as ie,traits$applyErrorMatchers as T,uc as E,vc as D,xa as ae,ya as O}from"../_bundle/sdk.js";const k={system:`prisma-api`,responseHeaders:[{header:`x-request-id`,name:`http.response.header.x-request-id`,transform:`list`},{header:`request-id`,name:`http.response.header.request-id`,transform:`list`}],prefix:`Prisma`,service:`Prisma`,labels:`prisma`,propagate:`w3c`};const A=/*@__PURE__*/ o(function BadRequest(e){return p(e,new.target,[`$5($4()("BadRequest",{code:$2,message:$3}).pipe($1),[{status:400}])`,[_,O,s,l,f,T]])});const j=/*@__PURE__*/ o(function Conflict(t){return p(t,new.target,[`$5($4()("Conflict",{code:$2,message:$3}).pipe($1),[{status:409}])`,[_,e,s,l,f,T]])});const M=/*@__PURE__*/ o(function DomainDnsNotConfigured(e){return p(e,new.target,[`$4($3()("DomainDnsNotConfigured",{message:$2}).pipe($1),[{status:400,message:{includes:"DNS is not configured"}},{status:400,body:{"/error/hint":{includes:"DNS is not configured"}}}])`,[_,O,l,f,T]])});const N=/*@__PURE__*/ o(function DomainOwnershipRequired(e){return p(e,new.target,[`$5($4()("DomainOwnershipRequired",{message:$2,body:$3}).pipe($1),[{status:422,body:{"/error/code":"domain-ownership-required"}}])`,[_,O,l,g,f,T]])});const P=/*@__PURE__*/ o(function Forbidden(e){return p(e,new.target,[`$5($4()("Forbidden",{code:$2,message:$3}).pipe($1),[{status:403}])`,[_,ae,s,l,f,T]])});const F=/*@__PURE__*/ o(function NotFound(e){return p(e,new.target,[`$5($4()("NotFound",{code:$2,message:$3}).pipe($1),[{status:404}])`,[_,O,s,l,f,T]])});const I=/*@__PURE__*/ o(function UnprocessableEntity(e){return p(e,new.target,[`$5($4()("UnprocessableEntity",{code:$2,message:$3}).pipe($1),[{status:422}])`,[_,O,s,l,f,T]])});const L=/*@__PURE__*/ m(e=>e===r?d(`CreateAuthGithubActionsToken`,`{input:#1,output:#3,errors:[$7,$8],protocol:$9,retry:$10,telemetry:$11,span:"%"};$6(>4)@"%Request";$6(>5)@"%ResponseData";$6(>6)@"%Response";$5({token:$2,expiresInSeconds:$4($3)}).pipe($1({method:"POST",uri:"/v1/auth/github-actions/token",code:200}));$5({id:$2,type:$2,value:$2,expiresAt:$2,workspaceId:$2});$5({data:#2})`,[_,b,l,s,E,u,D,A,c,v,y,k]):i(L,e));const R=/*@__PURE__*/ m(e=>e===r?d(`CreateBucket`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$5(>2)@"%Request";$4({projectId:$2,name:$3($2),branchId:$3($2),branchGitName:$3($2),logicalId:$3($2)}).pipe($1({method:"POST",uri:"/v1/buckets",code:200}))`,[_,b,l,E,u,D,__d38,A,P,F,j,c,v,y,k]):i(R,e));const z=/*@__PURE__*/ m(e=>e===r?d(`CreateBucketKey`,`{input:#1,output:#3,errors:[$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$6(>4)@"%Request";$6(>5)@"%ResponseData";$6(>6)@"%Response";$5({bucketId:$3.pipe($2()),name:$4($3),role:$3}).pipe($1({method:"POST",uri:"/v1/buckets/{bucketId}/keys",code:200}));$5({id:$3,type:$3,name:$3,valueHint:$3,role:$3,createdAt:$3,secretAccessKey:$3.pipe($7({})),accessKeyId:$3.pipe($7({})),endpoint:$3,bucketName:$3});$5({data:#2})`,[_,b,x,l,E,u,D,w,A,F,c,v,y,k]):i(z,e));const B=/*@__PURE__*/ m(e=>e===r?d(`CreateBuild`,`{input:#2,output:#7:0,errors:[$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$4(>3)@"%RequestRunIdentity";$4(>4)@"%Request";$3({provider:$1,repositoryId:$1,runId:$1,runAttempt:$2});$3({source:$1,commitSha:$1,branchName:$1,runIdentity:$6(#1),externalLogUrl:$6($1),projectId:$6($1),branchId:$6($1),applicationTopologyContentHash:$6($1)}).pipe($5({method:"POST",uri:"/v1/builds",code:200}))`,[_,l,s,u,D,b,E,__d0,A,F,c,v,y,k]):i(B,e));const V=/*@__PURE__*/ m(e=>e===r?d(`CreateConnection`,`{input:#1,output:#5:3,errors:[$6,$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$4(>2)@"%Request";$3({databaseId:$2,name:$2}).pipe($1({method:"POST",uri:"/v1/connections",code:200}))`,[_,b,l,u,D,__d3,A,j,F,I,c,v,y,k]):i(V,e));const H=/*@__PURE__*/ m(e=>e===r?d(`CreateConnectionRotate`,`{input:#1,output:#6:3,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({id:$3.pipe($2())}).pipe($1({method:"POST",uri:"/v1/connections/{id}/rotate",code:200}))`,[_,b,x,l,u,D,__d3,A,F,c,v,y,k]):i(H,e));const U=/*@__PURE__*/ m(e=>e===r?d(`CreateDatabase`,`{input:#2,output:#5,errors:[$14,$15,$16,$17,$18,$19],protocol:$20,retry:$21,telemetry:$22,span:"%"};$4(>6);$4(>7)@"%Request";$4(>8);$4(>9)@"%ResponseData";$4(>10)@"%Response";$3([#1:0,#2:0,#1:1]);$10({projectId:$6,region:$7($6),name:$7($6),isDefault:$7($8),source:$7(#1),branchId:$7($9($6)),branchGitName:$7($9($6)),logicalId:$7($6)}).pipe($5({method:"POST",uri:"/v1/databases",code:200}));$3([#1:0,#2:0,#1:1]);$10({id:$6,type:$6,url:$6,name:$6,status:$6,createdAt:$6,isDefault:$8,defaultConnectionId:$9($6),connections:#11:3,project:#12:0,region:$9(#13:0),source:$9(#3),branchId:$9($6),logicalId:$9($6)});$10({data:#4})`,[_,__d7,__d5,h,D,b,l,E,n,a,u,__d6,__d37,__d4,A,P,F,j,I,c,v,y,k]):i(U,e));const W=/*@__PURE__*/ m(e=>e===r?d(`CreateDatabaseConnection`,`{input:#1,output:#6:3,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({databaseId:$3.pipe($2()),name:$3}).pipe($1({method:"POST",uri:"/v1/databases/{databaseId}/connections",code:200}))`,[_,b,x,l,u,D,__d3,A,F,I,c,v,y,k]):i(W,e));const G=/*@__PURE__*/ m(e=>e===r?d(`CreateDatabaseRestore`,`{input:#1,output:#3,errors:[$12,$13,$14,$15,$16],protocol:$17,retry:$18,telemetry:$19,span:"%"};$6(>4)@"%Request";$6(>5)@"%ResponseData";$6(>6)@"%Response";$5({targetDatabaseId:$3.pipe($2()),source:#4:0}).pipe($1({method:"POST",uri:"/v1/databases/{targetDatabaseId}/restore",code:200}));$5({id:$3,type:$3,url:$3,name:$3,status:$3,createdAt:$3,isDefault:$7,defaultConnectionId:$8($3),connections:#9:0,project:#10:0,region:$8(#11:0),source:#4:0,branchId:$8($3),logicalId:$8($3)});$5({data:#2})`,[_,b,x,l,__d5,u,D,n,a,__d10,__d37,__d4,A,F,j,I,c,v,y,k]):i(G,e));const K=/*@__PURE__*/ m(e=>e===r?d(`CreateDeploymentStart`,`{input:#1,output:#3,errors:[$6,$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>4)@"%Request";$5(>5)@"%ResponseData";$5(>6)@"%Response";$4({deploymentId:$3.pipe($2())}).pipe($1({method:"POST",uri:"/v1/deployments/{deploymentId}/start",code:200}));$4({previewDomain:$3});$4({data:#2})`,[_,b,x,l,u,D,A,P,F,j,c,v,y,k]):i(K,e));const q=/*@__PURE__*/ m(e=>e===r?d(`CreateDeploymentStop`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$5(>2)@"%Request";$4({deploymentId:$3.pipe($2())}).pipe($1({method:"POST",uri:"/v1/deployments/{deploymentId}/stop",code:200}))`,[_,b,x,l,u,D,__d11,A,P,F,j,c,v,y,k]):i(q,e));const J=/*@__PURE__*/ m(e=>e===r?d(`CreateDomainOwnershipVerify`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({domainOwnershipId:$3.pipe($2())}).pipe($1({method:"POST",uri:"/v1/domain-ownerships/{domainOwnershipId}/verify",code:200}))`,[_,b,x,l,u,D,__d12,A,F,c,v,y,k]):i(J,e));const Y=/*@__PURE__*/ m(e=>e===r?d(`CreateDomainRetry`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$5(>2)@"%Request";$4({domainId:$3.pipe($2())}).pipe($1({method:"POST",uri:"/v1/domains/{domainId}/retry",code:200}))`,[_,b,x,l,u,D,__d15,A,P,F,j,c,v,y,k]):i(Y,e));const X=/*@__PURE__*/ m(e=>e===r?d(`CreateEnvironmentVariable`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$5(>2)@"%Request";$4({projectId:$2,branchId:$3($2),class:$2,key:$2,value:$2}).pipe($1({method:"POST",uri:"/v1/environment-variables",code:200}))`,[_,b,l,E,u,D,__d17,A,F,j,I,c,v,y,k]):i(X,e));const Z=/*@__PURE__*/ m(e=>e===r?d(`CreateProject`,`{input:#1,output:#5,errors:[$17,$18,$19,$20],protocol:$21,retry:$22,telemetry:$23,span:"%"};$6(>6)@"%Request";$6(>7);$6(>8)@"%ResponseDataDatabase";$6(>9)@"%ResponseData";$6(>10)@"%Response";$5({createDatabase:$3($2),name:$3($4),region:$3($4),logicalId:$3($4),workspaceId:$3($4)}).pipe($1({method:"POST",uri:"/v1/projects",code:200}));$9([#7:0,#8:0,#7:1]);$5({id:$4,type:$4,url:$4,name:$4,status:$4,createdAt:$4,isDefault:$2,defaultConnectionId:$10($4),connections:#11:3,region:#12:0,source:$10(#2),branchId:$10($4),logicalId:$10($4),apiKeys:#13:1,connectionString:$10($4).pipe($14({})),directConnection:$10(#15:0)});$5({id:$4,type:$4,url:$4,name:$4,logicalId:$10($4),createdAt:$4,defaultRegion:$10($4),workspace:#16:0,database:$10(#3)});$5({data:#4})`,[_,b,n,E,l,u,D,__d7,__d5,h,a,__d6,__d4,__d19,w,__d2,__d37,A,j,I,c,v,y,k]):i(Z,e));const Q=/*@__PURE__*/ m(e=>e===r?d(`CreateProjectBranch`,`{input:#1,output:#8:0,errors:[$9,$10,$11,$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$7(>2)@"%Request";$6({projectId:$3.pipe($2()),gitName:$3,isDefault:$5($4)}).pipe($1({method:"POST",uri:"/v1/projects/{projectId}/branches",code:200}))`,[_,b,x,l,n,E,u,D,__d20,A,F,j,I,c,v,y,k]):i(Q,e));const oe=/*@__PURE__*/ m(e=>e===r?d(`CreateProjectBranchAlchemyStateLease`,`{input:#1,output:#8:1,errors:[$9,$10,$11,$12],protocol:$13,retry:$14,telemetry:$15,span:"%"};$7(>2)@"%Request";$6({projectId:$3.pipe($2()),branchId:$3.pipe($2()),stack:$3,stage:$3,ttlSeconds:$5($4),holderDescription:$5($3)}).pipe($1({method:"POST",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/lease",code:200}))`,[_,b,x,l,s,E,u,D,__d22,A,F,j,c,v,y,k]):i(oe,e));const se=/*@__PURE__*/ m(e=>e===r?d(`CreateProjectDatabase`,`{input:#3,output:#6,errors:[$18,$19,$20,$21,$22,$23],protocol:$24,retry:$25,telemetry:$26,span:"%"};$4(>7)@"%RequestFromDatabase";$4(>8);$4(>9)@"%Request";$4(>10);$4(>11)@"%ResponseData";$4(>12)@"%Response";$3({id:$1,backupId:$2($1)});$7([#5:0,#6:0,#5:1]);$3({projectId:$1.pipe($9()),region:$2($1),name:$2($1),isDefault:$2($10),fromDatabase:$2(#1),source:$2(#2)}).pipe($8({method:"POST",uri:"/v1/projects/{projectId}/databases",code:200}));$7([#5:0,#6:0,#5:1]);$3({id:$1,type:$1,url:$1,name:$1,status:$1,createdAt:$1,isDefault:$10,defaultConnectionId:$11($1),connections:#12:3,project:#13:0,region:#14:0,source:$11(#4),branchId:$11($1),logicalId:$11($1),apiKeys:#15:1,connectionString:$11($1).pipe($16({})),directConnection:$11(#17:0)});$3({data:#5})`,[_,l,E,u,D,__d7,__d5,h,b,x,n,a,__d6,__d37,__d4,__d19,w,__d2,A,P,F,j,I,c,v,y,k]):i(se,e));const ce=/*@__PURE__*/ m(e=>e===r?d(`CreateProjectTransfer`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$5(>2)@"%Request";$4({id:$3.pipe($2()),recipientAccessToken:$3}).pipe($1({method:"POST",uri:"/v1/projects/{id}/transfer",code:200}))`,[_,b,x,l,u,D,__d11,A,F,j,I,c,v,y,k]):i(ce,e));const le=/*@__PURE__*/ m(e=>e===r?d(`CreateScmInstallationsInstallIntent`,`{input:#1,output:#3,errors:[$7,$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$5(>4)@"%Request";$5(>5)@"%ResponseData";$5(>6)@"%Response";$4({provider:$2,workspaceId:$2,repository:$3($2)}).pipe($1({method:"POST",uri:"/v1/scm-installations/install-intents",code:200}));$4({type:$2,provider:$2,workspaceId:$2,installUrl:$2,alreadyLinked:$3($6),accountLogin:$3($2),hint:$3($2)});$4({data:#2})`,[_,b,l,E,u,D,n,A,P,F,I,c,v,y,k]):i(le,e));const ue=/*@__PURE__*/ m(e=>e===r?d(`CreateService`,`{input:#1,output:#7:0,errors:[$8,$9,$10,$11,$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$6(>2)@"%Request";$5({displayName:$2,regionId:$3($2),branchId:$3($4($2)),branchGitName:$3($4($2)),projectId:$2,logicalId:$3($2)}).pipe($1({method:"POST",uri:"/v1/services",code:200}))`,[_,b,l,E,a,u,D,__d24,A,P,F,j,I,c,v,y,k]):i(ue,e));const de=/*@__PURE__*/ m(e=>e===r?d(`CreateServiceDeployment`,`{input:#2,output:#4,errors:[$10,$11,$12,$13,$14],protocol:$15,retry:$16,telemetry:$17,span:"%"};$5(>5)@"%RequestPortMapping";$5(>6)@"%Request";$5(>7)@"%ResponseData";$5(>8)@"%Response";$4({http:$3($2($1))});$4({serviceId:$8.pipe($7()),portMapping:$3(#1),skipCodeUpload:$3($9),variables:$3($18($8,$2($8)))}).pipe($6({method:"POST",uri:"/v1/services/{serviceId}/deployments",code:200}));$4({id:$8,type:$8,url:$8,foundryVersionId:$8,uploadUrl:$2($8)});$4({data:#3})`,[_,s,a,E,u,D,b,x,l,n,A,P,F,I,c,v,y,k,ee]):i(de,e));const fe=/*@__PURE__*/ m(e=>e===r?d(`CreateServiceDomain`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10,$11,$12,$13,$14],protocol:$15,retry:$16,telemetry:$17,span:"%"};$5(>2)@"%Request";$4({serviceId:$3.pipe($2()),hostname:$3}).pipe($1({method:"POST",uri:"/v1/services/{serviceId}/domains",code:200}))`,[_,b,x,l,u,D,__d15,A,P,F,j,I,N,M,c,v,y,k]):i(fe,e));const pe=/*@__PURE__*/ m(e=>e===r?d(`CreateServicePromote`,`{input:#1,output:#7:1,errors:[$8,$9,$10,$11,$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$6(>2)@"%Request";$5({serviceId:$3.pipe($2()),deploymentId:$4($3),versionId:$4($3)}).pipe($1({method:"POST",uri:"/v1/services/{serviceId}/promote",code:200}))`,[_,b,x,l,E,u,D,__d25,A,P,F,j,I,c,v,y,k]):i(pe,e));const me=/*@__PURE__*/ m(e=>e===r?d(`CreateServiceRollback`,`{input:#1,output:#7:1,errors:[$8,$9,$10,$11,$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$6(>2)@"%Request";$5({serviceId:$3.pipe($2()),deploymentId:$4($3),versionId:$4($3)}).pipe($1({method:"POST",uri:"/v1/services/{serviceId}/rollback",code:200}))`,[_,b,x,l,E,u,D,__d25,A,P,F,j,I,c,v,y,k]):i(me,e));const he=/*@__PURE__*/ m(e=>e===r?d(`CreateServiceUrl`,`{input:#1,output:#8:0,errors:[$9,$10,$11,$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$7(>2)@"%Request";$6({serviceId:$3.pipe($2()),hostname:$3,logicalId:$4($3),createDomainOwnership:$4($5)}).pipe($1({method:"POST",uri:"/v1/services/{serviceId}/urls",code:200}))`,[_,b,x,l,E,n,u,D,__d26,A,F,j,I,c,v,y,k]):i(he,e));const ge=/*@__PURE__*/ m(e=>e===r?d(`CreateSourceRepository`,`{input:#1,output:#7:0,errors:[$8,$9,$10,$11,$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$6(>2)@"%Request";$5({projectId:$2,provider:$2,providerRepositoryId:$3,installationId:$4($2)}).pipe($1({method:"POST",uri:"/v1/source-repositories",code:200}))`,[_,b,l,s,E,u,D,__d29,A,P,F,j,I,c,v,y,k]):i(ge,e));const _e=/*@__PURE__*/ m(e=>e===r?d(`CreateUrlCheck`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({id:$3.pipe($2())}).pipe($1({method:"POST",uri:"/v1/urls/{id}/check",code:200}))`,[_,b,x,l,u,D,__d26,A,F,c,v,y,k]):i(_e,e));const ve=/*@__PURE__*/ m(e=>e===r?d(`CreateWorkspace`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({displayName:$3($2)}).pipe($1({method:"POST",uri:"/v1/workspaces",code:200}))`,[_,b,l,E,u,D,__d30,A,P,c,v,y,k]):i(ve,e));const ye=/*@__PURE__*/ m(e=>e===r?d(`CreateWorkspaceDomainOwnership`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$5(>2)@"%Request";$4({workspaceId:$3.pipe($2()),domain:$3}).pipe($1({method:"POST",uri:"/v1/workspaces/{workspaceId}/domain-ownerships",code:200}))`,[_,b,x,l,u,D,__d12,A,F,I,N,c,v,y,k]):i(ye,e));const be=/*@__PURE__*/ m(e=>e===r?d(`CreateWorkspaceServiceToken`,`{input:#1,output:#3,errors:[$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$7(>4)@"%Request";$7(>5)@"%ResponseData";$7(>6)@"%Response";$6({workspaceId:$3.pipe($2()),projectId:$5($4($3)),expiresAt:$5($4($3)),name:$3}).pipe($1({method:"POST",uri:"/v1/workspaces/{workspaceId}/service-tokens",code:200}));$6({id:$3,type:$3,name:$3,scope:$3,projectId:$4($3),valueHint:$3,createdAt:$3,expiresAt:$5($4($3)),value:$3});$6({data:#2})`,[_,b,x,l,a,E,u,D,A,F,I,c,v,y,k]):i(be,e));const xe=/*@__PURE__*/ m(e=>e===r?d(`DeleteBranch`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$5(>2)@"%Request";$4({branchId:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/branches/{branchId}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,j,I,c,v,y,k]):i(xe,e));const Se=/*@__PURE__*/ m(e=>e===r?d(`DeleteBucket`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({bucketId:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/buckets/{bucketId}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,c,v,y,k]):i(Se,e));const Ce=/*@__PURE__*/ m(e=>e===r?d(`DeleteBucketKey`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({bucketId:$3.pipe($2()),keyId:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/buckets/{bucketId}/keys/{keyId}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,c,v,y,k]):i(Ce,e));const we=/*@__PURE__*/ m(e=>e===r?d(`DeleteConnection`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({id:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/connections/{id}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,I,c,v,y,k]):i(we,e));const Te=/*@__PURE__*/ m(e=>e===r?d(`DeleteDatabase`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$5(>2)@"%Request";$4({databaseId:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/databases/{databaseId}",code:200}))`,[_,b,x,l,u,D,__d11,A,P,F,I,c,v,y,k]):i(Te,e));const Ee=/*@__PURE__*/ m(e=>e===r?d(`DeleteDeployment`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$5(>2)@"%Request";$4({deploymentId:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/deployments/{deploymentId}",code:200}))`,[_,b,x,l,u,D,__d11,A,P,F,j,c,v,y,k]):i(Ee,e));const De=/*@__PURE__*/ m(e=>e===r?d(`DeleteDomain`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({domainId:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/domains/{domainId}",code:200}))`,[_,b,x,l,u,D,__d11,A,P,F,c,v,y,k]):i(De,e));const Oe=/*@__PURE__*/ m(e=>e===r?d(`DeleteDomainOwnership`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({domainOwnershipId:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/domain-ownerships/{domainOwnershipId}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,c,v,y,k]):i(Oe,e));const ke=/*@__PURE__*/ m(e=>e===r?d(`DeleteEnvironmentVariable`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({envVarId:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/environment-variables/{envVarId}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,I,c,v,y,k]):i(ke,e));const Ae=/*@__PURE__*/ m(e=>e===r?d(`DeleteIntegration`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({id:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/integrations/{id}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,I,c,v,y,k]):i(Ae,e));const je=/*@__PURE__*/ m(e=>e===r?d(`DeleteProject`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$5(>2)@"%Request";$4({id:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/projects/{id}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,j,I,c,v,y,k]):i(je,e));const Me=/*@__PURE__*/ m(e=>e===r?d(`DeleteProjectBranchAlchemyStateLease`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({projectId:$3.pipe($2()),branchId:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/lease",code:200}))`,[_,b,x,l,u,D,__d11,A,F,c,v,y,k]):i(Me,e));const Ne=/*@__PURE__*/ m(e=>e===r?d(`DeleteProjectBranchAlchemyStateStateStack`,`{input:#1,output:#8:0,errors:[$9,$10,$11,$12],protocol:$13,retry:$14,telemetry:$15,span:"%"};$7(>2)@"%Request";$6({projectId:$3.pipe($2()),branchId:$3.pipe($2()),stack:$3.pipe($2()),stage:$5($3.pipe($4()))}).pipe($1({method:"DELETE",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/state/stacks/{stack}",code:200}))`,[_,b,x,l,S,E,u,D,__d11,A,F,j,c,v,y,k]):i(Ne,e));const Pe=/*@__PURE__*/ m(e=>e===r?d(`DeleteProjectBranchAlchemyStateStateStackStageResource`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({projectId:$3.pipe($2()),branchId:$3.pipe($2()),stack:$3.pipe($2()),stage:$3.pipe($2()),fqn:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/state/stacks/{stack}/stages/{stage}/resources/{fqn}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,j,c,v,y,k]):i(Pe,e));const Fe=/*@__PURE__*/ m(e=>e===r?d(`DeleteService`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$5(>2)@"%Request";$4({serviceId:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/services/{serviceId}",code:200}))`,[_,b,x,l,u,D,__d11,A,P,F,j,c,v,y,k]):i(Fe,e));const Ie=/*@__PURE__*/ m(e=>e===r?d(`DeleteSourceRepository`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({id:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/source-repositories/{id}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,c,v,y,k]):i(Ie,e));const Le=/*@__PURE__*/ m(e=>e===r?d(`DeleteUrl`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({id:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/urls/{id}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,c,v,y,k]):i(Le,e));const Re=/*@__PURE__*/ m(e=>e===r?d(`DeleteWorkspaceIntegration`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({workspaceId:$3.pipe($2()),clientId:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/workspaces/{workspaceId}/integrations/{clientId}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,I,c,v,y,k]):i(Re,e));const ze=/*@__PURE__*/ m(e=>e===r?d(`DeleteWorkspaceServiceToken`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({workspaceId:$3.pipe($2()),serviceTokenId:$3.pipe($2())}).pipe($1({method:"DELETE",uri:"/v1/workspaces/{workspaceId}/service-tokens/{serviceTokenId}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,c,v,y,k]):i(ze,e));const Be=/*@__PURE__*/ m(e=>e===r?d(`GetAgentApproval`,`{input:#1,output:#2,errors:[$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>3)@"%Request";$5(>4)@"%Response";$4({approvalId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/agent-approvals/{approvalId}",code:200}));$4({id:$3,status:$3,expiresAt:$3,windowExpiresAt:$6($3),decidedAt:$6($3),hint:$7($3)})`,[_,b,x,l,u,D,a,E,F,c,v,y,k]):i(Be,e));const Ve=/*@__PURE__*/ m(e=>e===r?d(`GetBranch`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({branchId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/branches/{branchId}",code:200}))`,[_,b,x,l,u,D,__d20,A,F,c,v,y,k]):i(Ve,e));const He=/*@__PURE__*/ m(e=>e===r?d(`GetBucket`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({bucketId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/buckets/{bucketId}",code:200}))`,[_,b,x,l,u,D,__d38,A,F,c,v,y,k]):i(He,e));const Ue=/*@__PURE__*/ m(e=>e===r?d(`GetBucketKeys`,`{input:#1,output:#4,errors:[$11,$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$8(>5)@"%Request";$8(>6)@"%ResponseDataItem";$9(#2);$8(>7)@"%Response";$7({bucketId:$3.pipe($2()),cursor:$5($3.pipe($4())),limit:$5($6.pipe($4()))}).pipe($1({method:"GET",uri:"/v1/buckets/{bucketId}/keys",code:200}));$7({id:$3,type:$3,name:$3,valueHint:$3,role:$3,createdAt:$3});$7({data:#3,pagination:#10:0})`,[_,b,x,l,S,E,s,u,D,t,__d32,A,F,c,v,y,k]):i(Ue,e));const We=/*@__PURE__*/ m(e=>e===r?d(`GetBuckets`,`{input:#1,output:#3,errors:[$11,$12],protocol:$13,retry:$14,telemetry:$15,span:"%"};$7(>4)@"%Request";$9(#8:0);$7(>5)@"%Response";$6({cursor:$4($3.pipe($2())),limit:$4($5.pipe($2())),projectId:$4($3.pipe($2())),logicalId:$4($3.pipe($2())),branchId:$4($3.pipe($2())),branchGitName:$4($3.pipe($2()))}).pipe($1({method:"GET",uri:"/v1/buckets",code:200}));$6({data:#2,pagination:#10:0})`,[_,b,S,l,E,s,u,D,__d39,t,__d32,A,c,v,y,k]):i(We,e));const Ge=/*@__PURE__*/ m(e=>e===r?d(`GetBuildResponse`,`{input:#1,output:#5,errors:[$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"GetBuild"};$5(>6)@"GetBuildRequest";$5(>7)@"%DataResourcesItem";$6(#2);$5(>8)@"%Data";$5(>9)@"%";$4({buildId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/builds/{buildId}",code:200}));$4({resourceType:$3,resourceId:$3,action:$3,createdAt:$3});$4({id:$3,source:$3,state:$3,phase:$7($3),commitSha:$3,branchName:$3,gitRepoId:$7($3),projectId:$7($3),branchId:$7($3),externalLogUrl:$7($3),deployedUrl:$7($3),applicationTopologyContentHash:$7($3),errorMessage:$7($3),failingStep:$7($3),createdAt:$3,startedAt:$7($3),finishedAt:$7($3),resources:#3});$4({data:#4})`,[_,b,x,l,u,D,t,a,A,F,c,v,y,k]):i(Ge,e));const Ke=/*@__PURE__*/ m(e=>e===r?d(`GetBuilds`,`{input:#1,output:#3,errors:[$11,$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$7(>4)@"%Request";$9(#8:0);$7(>5)@"%Response";$6({cursor:$4($3.pipe($2())),limit:$4($5.pipe($2())),projectId:$4($3.pipe($2())),branchId:$4($3.pipe($2())),state:$4($3.pipe($2()))}).pipe($1({method:"GET",uri:"/v1/builds",code:200}));$6({data:#2,pagination:#10:0})`,[_,b,S,l,E,s,u,D,__d1,t,__d32,A,F,c,v,y,k]):i(Ke,e));const qe=/*@__PURE__*/ m(e=>e===r?d(`GetConnection`,`{input:#1,output:#2,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>3)@"%Request";$5(>4)@"%Response";$4({id:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/connections/{id}",code:200}));$4({data:#6:0})`,[_,b,x,l,u,D,__d9,A,F,I,c,v,y,k]):i(qe,e));const Je=/*@__PURE__*/ m(e=>e===r?d(`GetConnections`,`{input:#1,output:#8:0,errors:[$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$7(>2)@"%Request";$6({cursor:$4($3.pipe($2())),limit:$4($5.pipe($2())),databaseId:$4($3.pipe($2()))}).pipe($1({method:"GET",uri:"/v1/connections",code:200}))`,[_,b,S,l,E,s,u,D,__d33,A,c,v,y,k]):i(Je,e));const Ye=/*@__PURE__*/ m(e=>e===r?d(`GetDatabase`,`{input:#1,output:#4,errors:[$14,$15,$16,$17,$18],protocol:$19,retry:$20,telemetry:$21,span:"%"};$5(>5)@"%Request";$5(>6);$5(>7)@"%ResponseData";$5(>8)@"%Response";$4({databaseId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/databases/{databaseId}",code:200}));$8([#6:0,#7:0,#6:1]);$4({id:$3,type:$3,url:$3,name:$3,status:$3,createdAt:$3,isDefault:$9,defaultConnectionId:$10($3),connections:#11:0,project:#12:0,region:$10(#13:0),source:$10(#2),branchId:$10($3),logicalId:$10($3)});$4({data:#3})`,[_,b,x,l,u,D,__d7,__d5,h,n,a,__d10,__d37,__d4,A,P,F,I,c,v,y,k]):i(Ye,e));const Xe=/*@__PURE__*/ m(e=>e===r?d(`GetDatabaseBackups`,`{input:#1,output:#6,errors:[$12,$13,$14,$15],protocol:$16,retry:$17,telemetry:$18,span:"%"};$8(>7)@"%Request";$8(>8)@"%ResponseDataItem";$9(#2);$8(>9)@"%ResponseMeta";$8(>10)@"%ResponsePagination";$8(>11)@"%Response";$7({databaseId:$3.pipe($2()),limit:$6($5.pipe($4()))}).pipe($1({method:"GET",uri:"/v1/databases/{databaseId}/backups",code:200}));$7({id:$3,backupType:$3,createdAt:$3,size:$6($5),status:$3,type:$6($3)});$7({backupRetentionDays:$5});$7({hasMore:$10,limit:$11($5)});$7({data:#3,meta:#4,pagination:#5})`,[_,b,x,l,S,s,E,u,D,t,n,a,A,F,I,c,v,y,k]):i(Xe,e));const Ze=/*@__PURE__*/ m(e=>e===r?d(`GetDatabaseConnections`,`{input:#1,output:#9:0,errors:[$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$8(>2)@"%Request";$7({databaseId:$3.pipe($2()),cursor:$5($3.pipe($4())),limit:$5($6.pipe($4()))}).pipe($1({method:"GET",uri:"/v1/databases/{databaseId}/connections",code:200}))`,[_,b,x,l,S,E,s,u,D,__d33,I,c,v,y,k]):i(Ze,e));const Qe=/*@__PURE__*/ m(e=>e===r?d(`GetDatabases`,`{input:#1,output:#5,errors:[$18,$19,$20],protocol:$21,retry:$22,telemetry:$23,span:"%"};$7(>6)@"%Request";$7(>7);$7(>8)@"%ResponseDataItem";$16(#3);$7(>9)@"%Response";$6({cursor:$4($3.pipe($2())),limit:$4($5.pipe($2())),projectId:$4($3.pipe($2())),logicalId:$4($3.pipe($2())),branchId:$4($3.pipe($2())),branchGitName:$4($3.pipe($2()))}).pipe($1({method:"GET",uri:"/v1/databases",code:200}));$10([#8:0,#9:0,#8:1]);$6({id:$3,type:$3,url:$3,name:$3,status:$3,createdAt:$3,isDefault:$11,defaultConnectionId:$12($3),connections:#13:0,project:#14:0,region:$12(#15:0),source:$12(#2),branchId:$12($3),logicalId:$12($3)});$6({data:#4,pagination:#17:0})`,[_,b,S,l,E,s,u,D,__d7,__d5,h,n,a,__d10,__d37,__d4,t,__d32,A,P,c,v,y,k]):i(Qe,e));const $e=/*@__PURE__*/ m(e=>e===r?d(`GetDatabaseUsage`,`{input:#1,output:#5,errors:[$9,$10,$11,$12],protocol:$13,retry:$14,telemetry:$15,span:"%"};$7(>6)@"%Request";$7(>7)@"%ResponsePeriod";$7(>8)@"%ResponseMetricsOperations";$7(>9)@"%ResponseMetrics";$7(>10)@"%Response";$6({databaseId:$3.pipe($2()),startDate:$5($3.pipe($4())),endDate:$5($3.pipe($4()))}).pipe($1({method:"GET",uri:"/v1/databases/{databaseId}/usage",code:200}));$6({start:$3,end:$3});$6({used:$8,unit:$3});$6({operations:#3,storage:#3});$6({period:#2,metrics:#4,generatedAt:$3})`,[_,b,x,l,S,E,u,D,s,A,F,I,c,v,y,k]):i($e,e));const et=/*@__PURE__*/ m(e=>e===r?d(`GetDeployment`,`{input:#1,output:#5,errors:[$10,$11,$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$5(>6)@"%Request";$6($3,$3);$5(>7)@"%ResponseDataPortMapping";$5(>8)@"%ResponseData";$5(>9)@"%Response";$4({deploymentId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/deployments/{deploymentId}",code:200}));$4({http:$8($7)});$4({id:$3,type:$3,url:$3,serviceId:$3,foundryVersionId:$3,status:$3,previewDomain:$9($3),envVars:$8(#2),portMapping:$8(#3),createdAt:$3});$4({data:#4})`,[_,b,x,l,u,D,ee,s,E,a,A,P,F,c,v,y,k]):i(et,e));const tt=/*@__PURE__*/ m(e=>e===r?d(`GetDeploymentLogs`,`{input:#1,output:#11:0,errors:[$12,$13,$14,$15],protocol:$16,retry:$17,telemetry:$18,span:"%"};$10(>2)@"%Request";$9({deploymentId:$3.pipe($2()),tail:$6($5.pipe($4())),from_start:$6($8.pipe($4(),$7())),cursor:$6($3.pipe($4()))}).pipe($1({method:"GET",uri:"/v1/deployments/{deploymentId}/logs",code:200}))`,[_,b,x,l,S,s,E,ie,n,u,D,__d11,A,P,F,c,v,y,k]):i(tt,e));const nt=/*@__PURE__*/ m(e=>e===r?d(`GetDomain`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({domainId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/domains/{domainId}",code:200}))`,[_,b,x,l,u,D,__d15,A,P,F,c,v,y,k]):i(nt,e));const rt=/*@__PURE__*/ m(e=>e===r?d(`GetDomainOwnership`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({domainOwnershipId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/domain-ownerships/{domainOwnershipId}",code:200}))`,[_,b,x,l,u,D,__d12,A,F,c,v,y,k]):i(rt,e));const it=/*@__PURE__*/ m(e=>e===r?d(`GetEnvironmentVariable`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({envVarId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/environment-variables/{envVarId}",code:200}))`,[_,b,x,l,u,D,__d17,A,F,I,c,v,y,k]):i(it,e));const at=/*@__PURE__*/ m(e=>e===r?d(`GetEnvironmentVariables`,`{input:#1,output:#3,errors:[$11,$12,$13,$14],protocol:$15,retry:$16,telemetry:$17,span:"%"};$7(>4)@"%Request";$9(#8:0);$7(>5)@"%Response";$6({cursor:$4($3.pipe($2())),limit:$4($5.pipe($2())),projectId:$4($3.pipe($2())),class:$4($3.pipe($2())),key:$4($3.pipe($2())),branchId:$4($3.pipe($2()))}).pipe($1({method:"GET",uri:"/v1/environment-variables",code:200}));$6({data:#2,pagination:#10:0})`,[_,b,S,l,E,s,u,D,__d18,t,__d32,F,A,I,c,v,y,k]):i(at,e));const ot=/*@__PURE__*/ m(e=>e===r?d(`GetIntegration`,`{input:#1,output:#2,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>3)@"%Request";$5(>4)@"%Response";$4({id:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/integrations/{id}",code:200}));$4({data:#6:2})`,[_,b,x,l,u,D,__d34,A,F,I,c,v,y,k]):i(ot,e));const st=/*@__PURE__*/ m(e=>e===r?d(`GetIntegrations`,`{input:#1,output:#8:1,errors:[$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$7(>2)@"%Request";$6({cursor:$4($3.pipe($2())),limit:$4($5.pipe($2())),workspaceId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/integrations",code:200}))`,[_,b,S,l,E,s,u,D,__d36,A,c,v,y,k]):i(st,e));const ct=/*@__PURE__*/ m(e=>e===r?d(`GetMeResponse`,`{input:#1,output:#5,errors:[$7],protocol:$8,retry:$9,telemetry:$10,span:"GetMe"};$3(>6)@"GetMeRequest";$3(>7)@"%DataUser";$3(>8)@"%DataCredential";$3(>9)@"%Data";$3(>10)@"%";$2({}).pipe($1({method:"GET",uri:"/v1/me",code:200}));$2({id:$4,email:$4,name:$5($4)});$2({type:$4,id:$5($4),name:$5($4)});$2({user:$5(#2),workspace:$5(#6:0),credential:#3});$2({data:#4})`,[_,b,u,D,l,a,__d4,c,v,y,k]):i(ct,e));const lt=/*@__PURE__*/ m(e=>e===r?d(`GetProject`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({id:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/projects/{id}",code:200}))`,[_,b,x,l,u,D,__d40,A,F,I,c,v,y,k]):i(lt,e));const ut=/*@__PURE__*/ m(e=>e===r?d(`GetProjectBranchAlchemyStateStateStacks`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({projectId:$3.pipe($2()),branchId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/state/stacks",code:200}))`,[_,b,x,l,u,D,__d42,A,F,j,c,v,y,k]):i(ut,e));const dt=/*@__PURE__*/ m(e=>e===r?d(`GetProjectBranchAlchemyStateStateStackStageOutput`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({projectId:$3.pipe($2()),branchId:$3.pipe($2()),stack:$3.pipe($2()),stage:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/state/stacks/{stack}/stages/{stage}/output",code:200}))`,[_,b,x,l,u,D,__d43,A,F,j,c,v,y,k]):i(dt,e));const ft=/*@__PURE__*/ m(e=>e===r?d(`GetProjectBranchAlchemyStateStateStackStageReplacedResources`,`{input:#1,output:#3,errors:[$9,$10,$11,$12],protocol:$13,retry:$14,telemetry:$15,span:"%"};$5(>4)@"%Request";$7($6);$5(>5)@"%Response";$4({projectId:$3.pipe($2()),branchId:$3.pipe($2()),stack:$3.pipe($2()),stage:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/state/stacks/{stack}/stages/{stage}/replaced-resources",code:200}));#2.pipe($8())`,[_,b,x,l,u,D,g,t,C,A,F,j,c,v,y,k]):i(ft,e));const pt=/*@__PURE__*/ m(e=>e===r?d(`GetProjectBranchAlchemyStateStateStackStageResource`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({projectId:$3.pipe($2()),branchId:$3.pipe($2()),stack:$3.pipe($2()),stage:$3.pipe($2()),fqn:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/state/stacks/{stack}/stages/{stage}/resources/{fqn}",code:200}))`,[_,b,x,l,u,D,__d43,A,F,j,c,v,y,k]):i(pt,e));const mt=/*@__PURE__*/ m(e=>e===r?d(`GetProjectBranchAlchemyStateStateStackStageResources`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({projectId:$3.pipe($2()),branchId:$3.pipe($2()),stack:$3.pipe($2()),stage:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/state/stacks/{stack}/stages/{stage}/resources",code:200}))`,[_,b,x,l,u,D,__d42,A,F,j,c,v,y,k]):i(mt,e));const ht=/*@__PURE__*/ m(e=>e===r?d(`GetProjectBranchAlchemyStateStateStackStages`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({projectId:$3.pipe($2()),branchId:$3.pipe($2()),stack:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/state/stacks/{stack}/stages",code:200}))`,[_,b,x,l,u,D,__d42,A,F,j,c,v,y,k]):i(ht,e));const gt=/*@__PURE__*/ m(e=>e===r?d(`GetProjectBranchAlchemyStateVersion`,`{input:#1,output:#2,errors:[$7],protocol:$8,retry:$9,telemetry:$10,span:"%"};$5(>3)@"%Request";$5(>4)@"%Response";$4({projectId:$3.pipe($2()),branchId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/version",code:200}));$4({version:$6})`,[_,b,x,l,u,D,s,c,v,y,k]):i(gt,e));const _t=/*@__PURE__*/ m(e=>e===r?d(`GetProjectBranchApplicationTopology`,`{input:#1,output:#6:8,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({projectId:$3.pipe($2()),branchId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/projects/{projectId}/branches/{branchId}/application-topology",code:200}))`,[_,b,x,l,u,D,__d44,A,F,c,v,y,k]):i(_t,e));const vt=/*@__PURE__*/ m(e=>e===r?d(`GetProjectBranches`,`{input:#1,output:#3,errors:[$12,$13,$14,$15],protocol:$16,retry:$17,telemetry:$18,span:"%"};$8(>4)@"%Request";$10(#9:0);$8(>5)@"%Response";$7({projectId:$3.pipe($2()),cursor:$5($3.pipe($4())),limit:$5($6.pipe($4())),gitName:$5($3.pipe($4())),gitNameContains:$5($3.pipe($4()))}).pipe($1({method:"GET",uri:"/v1/projects/{projectId}/branches",code:200}));$7({data:#2,pagination:#11:0})`,[_,b,x,l,S,E,s,u,D,__d21,t,__d32,A,F,I,c,v,y,k]):i(vt,e));const yt=/*@__PURE__*/ m(e=>e===r?d(`GetProjectBranchUrls`,`{input:#1,output:#8:1,errors:[$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$7(>2)@"%Request";$6({projectId:$3.pipe($2()),branchId:$3.pipe($2()),logicalId:$5($3.pipe($4()))}).pipe($1({method:"GET",uri:"/v1/projects/{projectId}/branches/{branchId}/urls",code:200}))`,[_,b,x,l,S,E,u,D,__d46,A,F,c,v,y,k]):i(yt,e));const bt=/*@__PURE__*/ m(e=>e===r?d(`GetProjectDatabases`,`{input:#1,output:#5,errors:[$19,$20,$21,$22],protocol:$23,retry:$24,telemetry:$25,span:"%"};$8(>6)@"%Request";$8(>7);$8(>8)@"%ResponseDataItem";$17(#3);$8(>9)@"%Response";$7({projectId:$3.pipe($2()),cursor:$5($3.pipe($4())),limit:$5($6.pipe($4()))}).pipe($1({method:"GET",uri:"/v1/projects/{projectId}/databases",code:200}));$11([#9:0,#10:0,#9:1]);$7({id:$3,type:$3,url:$3,name:$3,status:$3,createdAt:$3,isDefault:$12,defaultConnectionId:$13($3),connections:#14:0,project:#15:0,region:$13(#16:0),source:$13(#2),branchId:$13($3),logicalId:$13($3)});$7({data:#4,pagination:#18:0})`,[_,b,x,l,S,E,s,u,D,__d7,__d5,h,n,a,__d10,__d37,__d4,t,__d32,A,F,I,c,v,y,k]):i(bt,e));const xt=/*@__PURE__*/ m(e=>e===r?d(`GetProjects`,`{input:#1,output:#3,errors:[$11,$12],protocol:$13,retry:$14,telemetry:$15,span:"%"};$7(>4)@"%Request";$9(#8:0);$7(>5)@"%Response";$6({cursor:$4($3.pipe($2())),limit:$4($5.pipe($2())),logicalId:$4($3.pipe($2()))}).pipe($1({method:"GET",uri:"/v1/projects",code:200}));$6({data:#2,pagination:#10:0})`,[_,b,S,l,E,s,u,D,__d41,t,__d32,A,c,v,y,k]):i(xt,e));const St=/*@__PURE__*/ m(e=>e===r?d(`GetRegions`,`{input:#1,output:#4,errors:[$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$6(>5)@"%Request";$6(>6)@"%ResponseDataItem";$7(#2);$6(>7)@"%Response";$5({product:$4($3.pipe($2()))}).pipe($1({method:"GET",uri:"/v1/regions",code:200}));$5({id:$3,type:$3,name:$3,product:$3,status:$4($3)});$5({data:#3})`,[_,b,S,l,E,u,D,t,A,c,v,y,k]):i(St,e));const Ct=/*@__PURE__*/ m(e=>e===r?d(`GetRegionsAccelerate`,`{input:#1,output:#4,errors:[$6],protocol:$7,retry:$8,telemetry:$9,span:"%"};$3(>5)@"%Request";$3(>6)@"%ResponseDataItem";$5(#2);$3(>7)@"%Response";$2({}).pipe($1({method:"GET",uri:"/v1/regions/accelerate",code:200}));$2({id:$4,type:$4,name:$4});$2({data:#3})`,[_,b,u,D,l,t,c,v,y,k]):i(Ct,e));const wt=/*@__PURE__*/ m(e=>e===r?d(`GetRegionsPostgres`,`{input:#1,output:#4,errors:[$6],protocol:$7,retry:$8,telemetry:$9,span:"%"};$3(>5)@"%Request";$3(>6)@"%ResponseDataItem";$5(#2);$3(>7)@"%Response";$2({}).pipe($1({method:"GET",uri:"/v1/regions/postgres",code:200}));$2({id:$4,type:$4,name:$4,status:$4});$2({data:#3})`,[_,b,u,D,l,t,c,v,y,k]):i(wt,e));const Tt=/*@__PURE__*/ m(e=>e===r?d(`GetScmInstallationRepositories`,`{input:#1,output:#4,errors:[$12,$13,$14,$15],protocol:$16,retry:$17,telemetry:$18,span:"%"};$8(>5)@"%Request";$8(>6)@"%ResponseDataItem";$10(#2);$8(>7)@"%Response";$7({installationId:$3.pipe($2()),cursor:$5($3.pipe($4())),limit:$5($6.pipe($4()))}).pipe($1({method:"GET",uri:"/v1/scm-installations/{installationId}/repositories",code:200}));$7({id:$6,type:$3,fullName:$3,defaultBranch:$3,isPrivate:$9});$7({data:#3,pagination:#11:0})`,[_,b,x,l,S,E,s,u,D,n,t,__d32,A,F,I,c,v,y,k]):i(Tt,e));const Et=/*@__PURE__*/ m(e=>e===r?d(`GetScmInstallations`,`{input:#1,output:#4,errors:[$11,$12],protocol:$13,retry:$14,telemetry:$15,span:"%"};$7(>5)@"%Request";$7(>6)@"%ResponseDataItem";$9(#2);$7(>7)@"%Response";$6({cursor:$4($3.pipe($2())),limit:$4($5.pipe($2())),workspaceId:$3.pipe($2()),repository:$4($3.pipe($2()))}).pipe($1({method:"GET",uri:"/v1/scm-installations",code:200}));$6({id:$3,type:$3,url:$3,provider:$3,installationId:$5,accountId:$5,accountLogin:$3,accountType:$3,suspended:$8,createdAt:$3,updatedAt:$3});$6({data:#3,pagination:#10:0,hint:$4($3)})`,[_,b,S,l,E,s,u,D,n,t,__d32,A,c,v,y,k]):i(Et,e));const Dt=/*@__PURE__*/ m(e=>e===r?d(`GetService`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({serviceId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/services/{serviceId}",code:200}))`,[_,b,x,l,u,D,__d24,A,P,F,c,v,y,k]):i(Dt,e));const Ot=/*@__PURE__*/ m(e=>e===r?d(`GetServiceDeployments`,`{input:#1,output:#4,errors:[$11,$12,$13,$14],protocol:$15,retry:$16,telemetry:$17,span:"%"};$8(>5)@"%Request";$8(>6)@"%ResponseDataItem";$9(#2);$8(>7)@"%Response";$7({serviceId:$3.pipe($2()),cursor:$5($3.pipe($4())),limit:$5($6.pipe($4()))}).pipe($1({method:"GET",uri:"/v1/services/{serviceId}/deployments",code:200}));$7({id:$3,type:$3,url:$3,serviceId:$3,foundryVersionId:$3,createdAt:$3});$7({data:#3,pagination:#10:0})`,[_,b,x,l,S,E,s,u,D,t,__d32,A,P,F,c,v,y,k]):i(Ot,e));const kt=/*@__PURE__*/ m(e=>e===r?d(`GetServiceDomains`,`{input:#1,output:#3,errors:[$9,$10,$11,$12],protocol:$13,retry:$14,telemetry:$15,span:"%"};$5(>4)@"%Request";$7(#6:2);$5(>5)@"%Response";$4({serviceId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/services/{serviceId}/domains",code:200}));$4({data:#2,pagination:#8:0})`,[_,b,x,l,u,D,__d16,t,__d45,A,P,F,c,v,y,k]):i(kt,e));const At=/*@__PURE__*/ m(e=>e===r?d(`GetServices`,`{input:#1,output:#3,errors:[$11,$12,$13,$14,$15],protocol:$16,retry:$17,telemetry:$18,span:"%"};$7(>4)@"%Request";$9(#8:0);$7(>5)@"%Response";$6({cursor:$4($3.pipe($2())),limit:$4($5.pipe($2())),projectId:$4($3.pipe($2())),logicalId:$4($3.pipe($2())),branchId:$4($3.pipe($2())),branchGitName:$4($3.pipe($2()))}).pipe($1({method:"GET",uri:"/v1/services",code:200}));$6({data:#2,pagination:#10:0})`,[_,b,S,l,E,s,u,D,__d23,t,__d32,A,F,P,I,c,v,y,k]):i(At,e));const jt=/*@__PURE__*/ m(e=>e===r?d(`GetServiceUrls`,`{input:#1,output:#6:1,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({serviceId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/services/{serviceId}/urls",code:200}))`,[_,b,x,l,u,D,__d46,A,F,c,v,y,k]):i(jt,e));const Mt=/*@__PURE__*/ m(e=>e===r?d(`GetSourceRepositories`,`{input:#1,output:#3,errors:[$11,$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$7(>4)@"%Request";$9(#8:0);$7(>5)@"%Response";$6({cursor:$4($3.pipe($2())),limit:$4($5.pipe($2())),projectId:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/source-repositories",code:200}));$6({data:#2,pagination:#10:0})`,[_,b,S,l,E,s,u,D,__d28,t,__d32,A,F,c,v,y,k]):i(Mt,e));const Nt=/*@__PURE__*/ m(e=>e===r?d(`GetSourceRepository`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({id:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/source-repositories/{id}",code:200}))`,[_,b,x,l,u,D,__d29,A,F,c,v,y,k]):i(Nt,e));const Pt=/*@__PURE__*/ m(e=>e===r?[`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"GetUrl"};$5(>2)@"GetUrlRequest";$4({id:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/urls/{id}",code:200}))`,[_,b,x,l,u,D,__d26,A,F,c,v,y,k]]:i(Pt,e));const Ft=/*@__PURE__*/ m(e=>e===r?d(`GetWorkspace`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({id:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/workspaces/{id}",code:200}))`,[_,b,x,l,u,D,__d30,A,F,I,c,v,y,k]):i(Ft,e));const It=/*@__PURE__*/ m(e=>e===r?d(`GetWorkspaceDomainOwnerships`,`{input:#1,output:#3,errors:[$12,$13,$14,$15],protocol:$16,retry:$17,telemetry:$18,span:"%"};$8(>4)@"%Request";$10(#9:0);$8(>5)@"%Response";$7({workspaceId:$3.pipe($2()),cursor:$5($3.pipe($4())),limit:$5($6.pipe($4())),domain:$5($3.pipe($4()))}).pipe($1({method:"GET",uri:"/v1/workspaces/{workspaceId}/domain-ownerships",code:200}));$7({data:#2,pagination:#11:0})`,[_,b,x,l,S,E,s,u,D,__d13,t,__d32,A,F,I,c,v,y,k]):i(It,e));const Lt=/*@__PURE__*/ m(e=>e===r?d(`GetWorkspaceDomainOwnershipsVerification`,`{input:#1,output:#2,errors:[$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$6(>3)@"%Request";$6(>4)@"%Response";$5({workspaceId:$3.pipe($2()),domain:$3.pipe($4())}).pipe($1({method:"GET",uri:"/v1/workspaces/{workspaceId}/domain-ownerships/verification",code:200}));$5({data:#7:0})`,[_,b,x,l,S,u,D,__d14,A,F,I,c,v,y,k]):i(Lt,e));const Rt=/*@__PURE__*/ m(e=>e===r?d(`GetWorkspaceIntegrations`,`{input:#1,output:#9:1,errors:[$10,$11,$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$8(>2)@"%Request";$7({workspaceId:$3.pipe($2()),cursor:$5($3.pipe($4())),limit:$5($6.pipe($4()))}).pipe($1({method:"GET",uri:"/v1/workspaces/{workspaceId}/integrations",code:200}))`,[_,b,x,l,S,E,s,u,D,__d36,A,F,I,c,v,y,k]):i(Rt,e));const zt=/*@__PURE__*/ m(e=>e===r?d(`GetWorkspaces`,`{input:#1,output:#3,errors:[$11,$12],protocol:$13,retry:$14,telemetry:$15,span:"%"};$7(>4)@"%Request";$9(#8:0);$7(>5)@"%Response";$6({cursor:$4($3.pipe($2())),limit:$4($5.pipe($2()))}).pipe($1({method:"GET",uri:"/v1/workspaces",code:200}));$6({data:#2,pagination:#10:0})`,[_,b,S,l,E,s,u,D,__d31,t,__d32,A,c,v,y,k]):i(zt,e));const Bt=/*@__PURE__*/ m(e=>e===r?d(`GetWorkspaceServiceTokens`,`{input:#1,output:#4,errors:[$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$8(>5)@"%Request";$8(>6)@"%ResponseDataItem";$10(#2);$8(>7)@"%Response";$7({workspaceId:$3.pipe($2()),cursor:$5($3.pipe($4())),limit:$5($6.pipe($4()))}).pipe($1({method:"GET",uri:"/v1/workspaces/{workspaceId}/service-tokens",code:200}));$7({id:$3,type:$3,name:$3,scope:$3,projectId:$9($3),valueHint:$3,createdAt:$3,expiresAt:$5($9($3))});$7({data:#3,pagination:#11:0})`,[_,b,x,l,S,E,s,u,D,a,t,__d32,A,c,v,y,k]):i(Bt,e));const $=/*@__PURE__*/ m(e=>e===r?d(`GetWorkspaceSubscription`,`{input:#1,output:#3,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>4)@"%Request";$5(>5)@"%ResponseData";$5(>6)@"%Response";$4({id:$3.pipe($2())}).pipe($1({method:"GET",uri:"/v1/workspaces/{id}/subscription",code:200}));$4({planName:$3,usageBlocked:$6,upgradeUrl:$3});$4({data:#2})`,[_,b,x,l,u,D,n,A,F,c,v,y,k]):i($,e));const Vt=/*@__PURE__*/ m(e=>e===r?d(`PutBuildResource`,`{input:#1,output:#6:0,errors:[$7,$8,$9],protocol:$10,retry:$11,telemetry:$12,span:"%"};$5(>2)@"%Request";$4({buildId:$3.pipe($2()),resourceType:$3.pipe($2()),resourceId:$3.pipe($2()),action:$3}).pipe($1({method:"PUT",uri:"/v1/builds/{buildId}/resources/{resourceType}/{resourceId}",code:200}))`,[_,b,x,l,u,D,__d11,A,F,c,v,y,k]):i(Vt,e));const Ht=/*@__PURE__*/ m(e=>e===r?d(`PutProjectBranchAlchemyStateStateStackStageOutput`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({projectId:$3.pipe($2()),branchId:$3.pipe($2()),stack:$3.pipe($2()),stage:$3.pipe($2())}).pipe($1({method:"PUT",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/state/stacks/{stack}/stages/{stage}/output",code:200}))`,[_,b,x,l,u,D,__d43,A,F,j,c,v,y,k]):i(Ht,e));const Ut=/*@__PURE__*/ m(e=>e===r?d(`PutProjectBranchAlchemyStateStateStackStageResource`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({projectId:$3.pipe($2()),branchId:$3.pipe($2()),stack:$3.pipe($2()),stage:$3.pipe($2()),fqn:$3.pipe($2())}).pipe($1({method:"PUT",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/state/stacks/{stack}/stages/{stage}/resources/{fqn}",code:200}))`,[_,b,x,l,u,D,__d43,A,F,j,c,v,y,k]):i(Ut,e));const Wt=/*@__PURE__*/ m(e=>e===r?d(`PutProjectBranchApplicationTopology`,`{input:#1,output:#5:8,errors:[$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$7(>2)@"%Request";$6({projectId:$3.pipe($2()),branchId:$3.pipe($2()),contentHash:$4($3),nodes:#5:1,ports:#5:3,edges:#5:6}).pipe($1({method:"PUT",uri:"/v1/projects/{projectId}/branches/{branchId}/application-topology",code:200}))`,[_,b,x,l,E,__d44,u,D,A,F,I,c,v,y,k]):i(Wt,e));const Gt=/*@__PURE__*/ m(e=>e===r?d(`UpdateBranch`,`{input:#1,output:#9:0,errors:[$10,$11,$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$8(>2)@"%Request";$7({branchId:$3.pipe($2()),isDefault:$6($5($4))}).pipe($1({method:"PATCH",uri:"/v1/branches/{branchId}",code:200}))`,[_,b,x,l,n,a,E,u,D,__d20,A,F,I,c,v,y,k]):i(Gt,e));const Kt=/*@__PURE__*/ m(e=>e===r?d(`UpdateBucket`,`{input:#1,output:#8:0,errors:[$9,$10,$11,$12,$13],protocol:$14,retry:$15,telemetry:$16,span:"%"};$7(>2)@"%Request";$6({bucketId:$3.pipe($2()),displayName:$4($3),branchId:$4($3),branchGitName:$4($3),logicalId:$4($5($3))}).pipe($1({method:"PATCH",uri:"/v1/buckets/{bucketId}",code:200}))`,[_,b,x,l,E,a,u,D,__d38,A,F,j,I,c,v,y,k]):i(Kt,e));const qt=/*@__PURE__*/ m(e=>e===r?d(`UpdateBuild`,`{input:#1,output:#7:0,errors:[$8,$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$6(>2)@"%Request";$5({buildId:$3.pipe($2()),phase:$4($3),state:$4($3),failingStep:$4($3),errorMessage:$4($3),externalLogUrl:$4($3),projectId:$4($3),branchId:$4($3),deployedUrl:$4($3),applicationTopologyContentHash:$4($3)}).pipe($1({method:"PATCH",uri:"/v1/builds/{buildId}",code:200}))`,[_,b,x,l,E,u,D,__d0,A,F,j,c,v,y,k]):i(qt,e));const Jt=/*@__PURE__*/ m(e=>e===r?d(`UpdateDatabase`,`{input:#1,output:#4,errors:[$15,$16,$17,$18,$19,$20],protocol:$21,retry:$22,telemetry:$23,span:"%"};$7(>5)@"%Request";$7(>6);$7(>7)@"%ResponseData";$7(>8)@"%Response";$6({databaseId:$3.pipe($2()),name:$4($3),branchId:$4($5($3)),branchGitName:$4($5($3)),logicalId:$4($5($3))}).pipe($1({method:"PATCH",uri:"/v1/databases/{databaseId}",code:200}));$10([#8:0,#9:0,#8:1]);$6({id:$3,type:$3,url:$3,name:$3,status:$3,createdAt:$3,isDefault:$11,defaultConnectionId:$5($3),connections:#12:0,project:#13:0,region:$5(#14:0),source:$5(#2),branchId:$5($3),logicalId:$5($3)});$6({data:#3})`,[_,b,x,l,E,a,u,D,__d7,__d5,h,n,__d10,__d37,__d4,A,P,F,j,I,c,v,y,k]):i(Jt,e));const Yt=/*@__PURE__*/ m(e=>e===r?d(`UpdateEnvironmentVariable`,`{input:#1,output:#6:0,errors:[$7,$8,$9,$10],protocol:$11,retry:$12,telemetry:$13,span:"%"};$5(>2)@"%Request";$4({envVarId:$3.pipe($2()),value:$3}).pipe($1({method:"PATCH",uri:"/v1/environment-variables/{envVarId}",code:200}))`,[_,b,x,l,u,D,__d17,A,F,I,c,v,y,k]):i(Yt,e));const Xt=/*@__PURE__*/ m(e=>e===r?d(`UpdateProject`,`{input:#2,output:#9:0,errors:[$10,$11,$12,$13,$14],protocol:$15,retry:$16,telemetry:$17,span:"%"};$3($1,$2);$8(>3)@"%Request";$7({id:$1.pipe($5()),name:$6($1),settings:$6(#1)}).pipe($4({method:"PATCH",uri:"/v1/projects/{id}",code:200}))`,[_,l,g,ee,b,x,E,u,D,__d40,A,P,F,I,c,v,y,k]):i(Xt,e));const Zt=/*@__PURE__*/ m(e=>e===r?d(`UpdateProjectBranchAlchemyStateLease`,`{input:#1,output:#8:1,errors:[$9,$10,$11],protocol:$12,retry:$13,telemetry:$14,span:"%"};$7(>2)@"%Request";$6({projectId:$3.pipe($2()),branchId:$3.pipe($2()),ttlSeconds:$5($4)}).pipe($1({method:"PATCH",uri:"/v1/projects/{projectId}/branches/{branchId}/alchemy-state/lease",code:200}))`,[_,b,x,l,s,E,u,D,__d22,A,F,c,v,y,k]):i(Zt,e));const Qt=/*@__PURE__*/ m(e=>e===r?d(`UpdateService`,`{input:#1,output:#8:0,errors:[$9,$10,$11,$12,$13,$14],protocol:$15,retry:$16,telemetry:$17,span:"%"};$7(>2)@"%Request";$6({serviceId:$3.pipe($2()),displayName:$4($3),logicalId:$4($5($3)),branchId:$4($5($3)),branchGitName:$4($5($3))}).pipe($1({method:"PATCH",uri:"/v1/services/{serviceId}",code:200}))`,[_,b,x,l,E,a,u,D,__d24,A,P,F,j,I,c,v,y,k]):i(Qt,e));const $t=/*@__PURE__*/ m(e=>e===r?d(`UpdateUrl`,`{input:#1,output:#9:0,errors:[$10,$11,$12,$13,$14],protocol:$15,retry:$16,telemetry:$17,span:"%"};$8(>2)@"%Request";$7({id:$3.pipe($2()),hostname:$4($3),serviceId:$4($3),logicalId:$4($5($3)),createDomainOwnership:$4($6)}).pipe($1({method:"PATCH",uri:"/v1/urls/{id}",code:200}))`,[_,b,x,l,E,a,n,u,D,__d26,A,F,j,I,c,v,y,k]):i($t,e));function __d0(){return[`$3(>1)@"CreateBuildResponse";$2({data:#1:0})`,[_,__d1,u,D]]}function __d1(){return[`$4(>1)@"CreateBuildResponseData";$3({id:$1,source:$1,state:$1,phase:$2($1),commitSha:$1,branchName:$1,gitRepoId:$2($1),projectId:$2($1),branchId:$2($1),externalLogUrl:$2($1),deployedUrl:$2($1),applicationTopologyContentHash:$2($1),errorMessage:$2($1),failingStep:$2($1),createdAt:$1,startedAt:$2($1),finishedAt:$2($1)})`,[_,l,a,u,D]]}function __d2(){return[`$3(>1)@"CreateConnectionResponseDataDirectConnection";$2({host:$1,pass:$1,user:$1})`,[_,l,u,D]]}function __d3(){return[`$5(>4)@"CreateConnectionResponseDataEndpointsDirect";$5(>5)@"CreateConnectionResponseDataEndpoints";$5(>6)@"CreateConnectionResponseData";$5(>7)@"CreateConnectionResponse";$4({host:$1,port:$2,connectionString:$1.pipe($3({}))});$4({direct:$6(#0),pooled:$6(#0),accelerate:$6(#0)});$4({id:$1,type:$1,url:$1,name:$1,createdAt:$1,kind:$1,endpoints:#1,connectionString:$1.pipe($3({})),directConnection:$6($8(#7:0)),database:#9:0,host:$8($1),pass:$8($1),user:$8($1)});$4({data:#2})`,[_,l,s,w,u,D,E,__d2,a,__d37]]}function __d4(){return[`$3(>1)@"CreateDatabaseResponseDataRegion";$2({id:$1,name:$1})`,[_,l,u,D]]}function __d5(){return[`$3(>1)@"CreateDatabaseRequestSourceCase1";$2({type:$1,databaseId:$1,backupId:$1})`,[_,l,u,D]]}function __d6(){return[`$6(>4)@"CreateDatabaseResponseDataConnectionsItemEndpointsDirect";$6(>5)@"CreateDatabaseResponseDataConnectionsItemEndpoints";$6(>6)@"CreateDatabaseResponseDataConnectionsItem";$10(#2);$5({host:$1,port:$2,connectionString:$4($1.pipe($3({})))});$5({direct:$4(#0),pooled:$4(#0),accelerate:$4(#0)});$5({id:$1,type:$1,url:$1,name:$1,createdAt:$1,kind:$1,endpoints:#1,directConnection:$4($8(#7:0)),database:#9:0})`,[_,l,s,w,E,u,D,__d2,a,__d37,t]]}function __d7(){return[`$3(>2)@"CreateDatabaseRequestSourceCase0";$3(>3)@"CreateDatabaseRequestSourceCase2";$2({type:$1});$2({type:$1,databaseId:$1})`,[_,l,u,D]]}function __d8(){return[`$4(>2)@"CreateDatabaseRestoreResponseDataConnectionsItemEndpointsDirect";$4(>3)@"CreateDatabaseRestoreResponseDataConnectionsItemEndpoints";$3({host:$1,port:$2});$3({direct:$5(#0),pooled:$5(#0),accelerate:$5(#0)})`,[_,l,s,u,D,E]]}function __d9(){return[`$8(>1)@"CreateDatabaseRestoreResponseDataConnectionsItem";$7({id:$1,type:$1,url:$1,name:$1,createdAt:$1,kind:$1,endpoints:#2:1,directConnection:$5($4(#3:0)),database:#6:0})`,[_,l,__d8,__d2,a,E,__d37,u,D]]}function __d10(){return[`$2(#1:0)`,[_,__d9,t]]}function __d11(){return[`$2(>1)@"CreateDeploymentStopResponse";$1({})`,[_,u,D]]}function __d12(){return[`$3(>1)@"CreateDomainOwnershipVerifyResponse";$2({data:#1:0})`,[_,__d13,u,D]]}function __d13(){return[`$6(>1)@"CreateDomainOwnershipVerifyResponseData";$5({id:$1,type:$1,workspaceId:$1,domain:$1,verification:#2:0,status:$1,expiresAt:$3($1),verificationRecordLastSeenAt:$3($1),verificationRecordPresent:$3($4),verificationRecordSyncError:$3($1),createdAt:$1})`,[_,l,__d14,a,n,u,D]]}function __d14(){return[`$4(>1)@"CreateDomainOwnershipVerifyResponseDataVerification";$3({type:$1,name:$1,value:$1,ttl:$2})`,[_,l,s,u,D]]}function __d15(){return[`$3(>1)@"CreateDomainRetryResponse";$2({data:#1:2})`,[_,__d16,u,D]]}function __d16(){return[`$5(>3)@"CreateDomainRetryResponseDataDnsRecordsItem";$6(#0);$5(>4)@"CreateDomainRetryResponseData";$4({type:$1,name:$1,value:$1,ttl:$3($2)});$4({id:$1,type:$1,url:$1,hostname:$1,appId:$1,computeServiceId:$1,status:$1,foundryStatus:$1,failureReason:$3($1),failureCategory:$3($1),certExpiresAt:$3($1),createdAt:$1,updatedAt:$1,dnsRecords:#1})`,[_,l,s,a,u,D,t]]}function __d17(){return[`$3(>1)@"CreateEnvironmentVariableResponse";$2({data:#1:0})`,[_,__d18,u,D]]}function __d18(){return[`$5(>1)@"CreateEnvironmentVariableResponseData";$4({id:$1,type:$1,url:$1,projectId:$1,branchId:$2($1),class:$1,key:$1,valueKid:$1,isManagedBySystem:$3,createdAt:$1,updatedAt:$1})`,[_,l,a,n,u,D]]}function __d19(){return[`$8(>2)@"CreateProjectResponseDataDatabaseApiKeysItem";$9(#0);$7({id:$1,type:$1,url:$1,name:$1,createdAt:$1,kind:$1,endpoints:#2:1,connectionString:$1.pipe($3({})),directConnection:$6($5(#4:0))})`,[_,l,__d8,w,__d2,a,E,u,D,t]]}function __d20(){return[`$3(>1)@"CreateProjectBranchResponse";$2({data:#1:0})`,[_,__d21,u,D]]}function __d21(){return[`$5(>1)@"CreateProjectBranchResponseData";$4({id:$1,type:$1,url:$1,gitName:$1,isDefault:$2,role:$1,createdAt:$1,updatedAt:$1,project:#3:0})`,[_,l,n,__d37,u,D]]}function __d22(){return[`$3(>2)@"CreateProjectBranchAlchemyStateLeaseResponseData";$3(>3)@"CreateProjectBranchAlchemyStateLeaseResponse";$2({leaseId:$1,expiresAt:$1});$2({data:#0})`,[_,l,u,D]]}function __d23(){return[`$5(>1)@"CreateServiceResponseData";$4({id:$1,type:$1,url:$1,name:$1,region:#2:0,projectId:$1,branchId:$3($1),latestDeploymentId:$3($1),appEndpointDomain:$1,createdAt:$1,logicalId:$3($1)})`,[_,l,__d4,a,u,D]]}function __d24(){return[`$3(>1)@"CreateServiceResponse";$2({data:#1:0})`,[_,__d23,u,D]]}function __d25(){return[`$4(>2)@"CreateServicePromoteResponseData";$4(>3)@"CreateServicePromoteResponse";$3({appEndpointDomain:$1,reassignedDomains:$2});$3({data:#0})`,[_,l,s,u,D]]}function __d26(){return[`$3(>1)@"CreateServiceUrlResponse";$2({data:#1:7})`,[_,__d27,u,D]]}function __d27(){return[`$3(>8)@"CreateServiceUrlResponseDataConditions";$3(>9)@"CreateServiceUrlResponseDataOwnershipExpiry";$3(>10)@"CreateServiceUrlResponseDataRecordsItem";$5(#2);$3(>11)@"CreateServiceUrlResponseDataHeldBy";$3(>12)@"CreateServiceUrlResponseDataCustomDomain";$3(>13)@"CreateServiceUrlResponseDataSwitchboardDns";$3(>14)@"CreateServiceUrlResponseData";$2({ownershipVerified:$1,servicePresent:$1,liveDeployment:$1,dnsPointsAtSwitchboard:$1,customDomainBound:$1,certificateActive:$1});$2({expiresAt:$1});$2({condition:$1,type:$1,name:$1,value:$1,ttl:$4});$2({workspaceId:$6($1),projectId:$6($1),serviceId:$6($1),message:$6($1)});$2({id:$1,status:$6($1),failureReason:$6($1),certExpiresAt:$6($1),lastSeenAt:$6($1),certificateRetryRequestedAt:$6($1),certificateIssuanceStuck:$7});$2({accepted:$7,detail:$6($1),lastSeenAt:$1});$2({id:$1,type:$1,branchId:$1,serviceId:$6($1),hostname:$1,logicalId:$6($1),status:$1,conditions:#0,firstUnmetCondition:$6($1),ownershipExpiry:$6(#1),records:#3,heldBy:$6(#4),customDomain:$6(#5),customDomainSyncError:$6($1),switchboardDns:$6(#6),setupUrl:$6($1),createdAt:$1,updatedAt:$1})`,[_,l,u,D,s,t,a,n]]}function __d28(){return[`$5(>1)@"CreateSourceRepositoryResponseData";$4({id:$1,type:$1,url:$1,repoId:$2,provider:$1,repoFullName:$1,defaultBranch:$1,isPrivate:$3,status:$1,projectId:$1,installationId:$1,createdAt:$1,updatedAt:$1})`,[_,l,s,n,u,D]]}function __d29(){return[`$5(>1)@"CreateSourceRepositoryResponse";$4({data:#1:0,hint:$3($2)})`,[_,__d28,l,E,u,D]]}function __d30(){return[`$3(>1)@"CreateWorkspaceResponse";$2({data:#1:0})`,[_,__d31,u,D]]}function __d31(){return[`$3(>1)@"CreateWorkspaceResponseData";$2({id:$1,type:$1,url:$1,name:$1,createdAt:$1})`,[_,l,u,D]]}function __d32(){return[`$5(>1)@"GetBucketKeysResponsePagination";$4({nextCursor:$2($1),hasMore:$3})`,[_,l,a,n,u,D]]}function __d33(){return[`$4(>1)@"GetConnectionsResponse";$3({data:#1:0,pagination:#2:0})`,[_,__d10,__d32,u,D]]}function __d34(){return[`$3(>3)@"GetIntegrationResponseDataClient";$3(>4)@"GetIntegrationResponseDataCreatedByUser";$3(>5)@"GetIntegrationResponseData";$2({id:$1,name:$1,createdAt:$1});$2({id:$1,email:$1,displayName:$4($1)});$2({id:$1,url:$1,createdAt:$1,scopes:#5:0,client:#0,createdByUser:#1})`,[_,l,u,D,a,__d35]]}function __d35(){return[`$2($1)`,[_,l,t]]}function __d36(){return[`$2(#1:2);$5(>2)@"GetIntegrationsResponse";$4({data:#0,pagination:#3:0})`,[_,__d34,t,__d32,u,D]]}function __d37(){return[`$3(>1)@"CreateBucketResponseDataProject";$2({id:$1,url:$1,name:$1})`,[_,l,u,D]]}function __d38(){return[`$3(>1)@"CreateBucketResponse";$2({data:#1:0})`,[_,__d39,u,D]]}function __d39(){return[`$5(>1)@"CreateBucketResponseData";$4({id:$1,type:$1,url:$1,name:$1,providerName:$1,status:$1,createdAt:$1,project:#2:0,branchId:$3($1),logicalId:$3($1)})`,[_,l,__d37,a,u,D]]}function __d40(){return[`$3(>1)@"GetProjectResponse";$2({data:#1:0})`,[_,__d41,u,D]]}function __d41(){return[`$5(>1)@"GetProjectResponseData";$4({id:$1,type:$1,url:$1,name:$1,logicalId:$2($1),createdAt:$1,defaultRegion:$2($1),workspace:#3:0})`,[_,l,a,__d37,u,D]]}function __d42(){return[`$3(>1)@"GetProjectBranchAlchemyStateStateStacksResponse";#2:0.pipe($1())`,[_,C,__d35,D]]}function __d43(){return[`$3(>1)@"GetProjectBranchAlchemyStateStateStackStageOutputResponse";$2.pipe($1())`,[_,C,g,D]]}function __d44(){return[`$5(>9)@"GetProjectBranchApplicationTopologyResponseDataNodesItem";$6(#0);$5(>10)@"GetProjectBranchApplicationTopologyResponseDataPortsItem";$6(#2);$5(>11)@"GetProjectBranchApplicationTopologyResponseDataEdgesItemFrom";$5(>12)@"GetProjectBranchApplicationTopologyResponseDataEdgesItem";$6(#5);$5(>13)@"GetProjectBranchApplicationTopologyResponseData";$5(>14)@"GetProjectBranchApplicationTopologyResponse";$4({logicalId:$1,parentLogicalId:$2($1),kind:$1,type:$3($1)});$4({logicalId:$1,direction:$1,name:$1,contractKind:$3($1),contractHash:$3($1)});$4({logicalId:$1,direction:$1,name:$1});$4({from:#4,to:#4,family:$1,style:$3($1)});$4({nodes:#1,ports:#3,edges:#6,contentHash:$3($1),writtenAt:$3($1)});$4({data:#7})`,[_,l,a,E,u,D,t]]}function __d45(){return[`$5(>1)@"GetProjectBranchUrlsResponsePagination";$4({hasMore:$1,nextCursor:$3($2)})`,[_,n,g,a,u,D]]}function __d46(){return[`$2(#1:7);$5(>2)@"GetProjectBranchUrlsResponse";$4({data:#0,pagination:#3:0})`,[_,__d27,t,__d45,u,D]]}export{A as BadRequest,j as Conflict,M as DomainDnsNotConfigured,N as DomainOwnershipRequired,P as Forbidden,F as NotFound,te as S3BucketName,ne as S3CredentialsError,I as UnprocessableEntity,L as createAuthGithubActionsToken,R as createBucket,z as createBucketKey,B as createBuild,V as createConnection,H as createConnectionRotate,U as createDatabase,W as createDatabaseConnection,G as createDatabaseRestore,K as createDeploymentStart,q as createDeploymentStop,J as createDomainOwnershipVerify,Y as createDomainRetry,X as createEnvironmentVariable,Z as createProject,Q as createProjectBranch,oe as createProjectBranchAlchemyStateLease,se as createProjectDatabase,ce as createProjectTransfer,le as createScmInstallationsInstallIntent,ue as createService,de as createServiceDeployment,fe as createServiceDomain,pe as createServicePromote,me as createServiceRollback,he as createServiceUrl,ge as createSourceRepository,_e as createUrlCheck,ve as createWorkspace,ye as createWorkspaceDomainOwnership,be as createWorkspaceServiceToken,xe as deleteBranch,Se as deleteBucket,Ce as deleteBucketKey,we as deleteConnection,Te as deleteDatabase,Ee as deleteDeployment,De as deleteDomain,Oe as deleteDomainOwnership,ke as deleteEnvironmentVariable,Ae as deleteIntegration,je as deleteProject,Me as deleteProjectBranchAlchemyStateLease,Ne as deleteProjectBranchAlchemyStateStateStack,Pe as deleteProjectBranchAlchemyStateStateStackStageResource,Fe as deleteService,Ie as deleteSourceRepository,Le as deleteUrl,Re as deleteWorkspaceIntegration,ze as deleteWorkspaceServiceToken,Be as getAgentApproval,Ve as getBranch,He as getBucket,Ue as getBucketKeys,We as getBuckets,Ge as getBuild,Ke as getBuilds,qe as getConnection,Je as getConnections,Ye as getDatabase,Xe as getDatabaseBackups,Ze as getDatabaseConnections,$e as getDatabaseUsage,Qe as getDatabases,et as getDeployment,tt as getDeploymentLogs,nt as getDomain,rt as getDomainOwnership,it as getEnvironmentVariable,at as getEnvironmentVariables,ot as getIntegration,st as getIntegrations,ct as getMe,lt as getProject,dt as getProjectBranchAlchemyStateStateStackStageOutput,ft as getProjectBranchAlchemyStateStateStackStageReplacedResources,pt as getProjectBranchAlchemyStateStateStackStageResource,mt as getProjectBranchAlchemyStateStateStackStageResources,ht as getProjectBranchAlchemyStateStateStackStages,ut as getProjectBranchAlchemyStateStateStacks,gt as getProjectBranchAlchemyStateVersion,_t as getProjectBranchApplicationTopology,yt as getProjectBranchUrls,vt as getProjectBranches,bt as getProjectDatabases,xt as getProjects,St as getRegions,Ct as getRegionsAccelerate,wt as getRegionsPostgres,Tt as getScmInstallationRepositories,Et as getScmInstallations,Dt as getService,Ot as getServiceDeployments,kt as getServiceDomains,jt as getServiceUrls,At as getServices,Mt as getSourceRepositories,Nt as getSourceRepository,Pt as getUrl,Ft as getWorkspace,It as getWorkspaceDomainOwnerships,Lt as getWorkspaceDomainOwnershipsVerification,Rt as getWorkspaceIntegrations,Bt as getWorkspaceServiceTokens,$ as getWorkspaceSubscription,zt as getWorkspaces,re as layerS3,Vt as putBuildResource,Ht as putProjectBranchAlchemyStateStateStackStageOutput,Ut as putProjectBranchAlchemyStateStateStackStageResource,Wt as putProjectBranchApplicationTopology,Gt as updateBranch,Kt as updateBucket,qt as updateBuild,Jt as updateDatabase,Yt as updateEnvironmentVariable,Xt as updateProject,Zt as updateProjectBranchAlchemyStateLease,Qt as updateService,$t as updateUrl}; + /* + 35 174 + e:0:Ba t:0:Wb n:0:Xb r:0:a i:0:c a:0:dc o:0:e s:0:ec c:0:errors$UnknownPrismaError ee:0:fc l:0:hc u:0:ic d:0:k f:0:kc p:0:l te:0:layer_s3$S3BucketName ne:0:layer_s3$S3CredentialsError re:0:layer_s3$layerS3 m:0:m h:0:mc g:0:nc _:0:pc v:0:protocol$PrismaProtocol y:0:retry$Retry b:0:traits$Http x:0:traits$Label S:0:traits$Query C:0:traits$RawResponseRoot w:0:traits$SensitiveValue ie:0:traits$StringEncoded T:0:traits$applyErrorMatchers E:0:uc D:0:vc ae:0:xa O:0:ya +diff --git a/src/services/management.ts b/src/services/management.ts +index 464d59f0190c0b0674cb766b42df020c2cb2aa49..596f7bda0156706c6c379cb6567df83f2264a329 100644 +--- a/src/services/management.ts ++++ b/src/services/management.ts +@@ -1013,6 +1013,7 @@ export interface CreateServiceDeploymentRequest { + serviceId: string; + portMapping?: CreateServiceDeploymentRequestPortMapping | undefined; + skipCodeUpload?: boolean | undefined; ++ variables?: { [key: string]: string | null } | undefined; + } + export interface CreateServiceDeploymentResponseData { + id: string; +@@ -7286,6 +7287,7 @@ function __c69(j: number): any { + serviceId: S.String.pipe(T.Label()), + portMapping: S.optional(__S(1104, __c69, 0)), + skipCodeUpload: S.optional(S.Boolean), ++ variables: S.optional(S.Record(S.String, S.NullOr(S.String))), + }).pipe(T.Http({ method: "POST", uri: "/v1/services/{serviceId}/deployments", code: 200 })), + ).annotate({ identifier: "CreateServiceDeploymentRequest" }); + case 2: diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 59d0976f5..c484f5247 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -35,6 +35,14 @@ overrides: '@prisma/composer-cli': workspace:* '@prisma/cli-engine': 0.10.0 +patchedDependencies: + '@alchemy.run/prisma@2.0.0-beta.87': + hash: 85fa0ad02c14a798351cf4a6d96d12a64a04c1170106dd9dcecdca985a082e69 + path: patches/@alchemy.run__prisma@2.0.0-beta.87.patch + '@distilled.cloud/prisma@1.0.0-rc.20': + hash: cafb260be033a6bc0e7293f22afc601715dd32c47e1d826d9c99fccde7639dea + path: patches/@distilled.cloud__prisma@1.0.0-rc.20.patch + importers: .: @@ -847,7 +855,7 @@ importers: devDependencies: '@alchemy.run/prisma': specifier: 'catalog:' - version: 2.0.0-beta.87(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@prisma/orm-postgres@8.0.0-rc.24(@prisma/cli-engine@0.10.0(@prisma/management-api-sdk@1.80.0)(magicast@0.5.5))(magicast@0.5.5)(temporal-polyfill@1.0.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(@vercel/nft@1.10.2)(alchemy@2.0.0-beta.87(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@types/react@19.2.17)(effect@4.1.4)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2))(effect@4.1.4)(prisma@8.0.0-rc.34(magicast@0.5.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2) + version: 2.0.0-beta.87(patch_hash=85fa0ad02c14a798351cf4a6d96d12a64a04c1170106dd9dcecdca985a082e69)(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@prisma/orm-postgres@8.0.0-rc.24(@prisma/cli-engine@0.10.0(@prisma/management-api-sdk@1.80.0)(magicast@0.5.5))(magicast@0.5.5)(temporal-polyfill@1.0.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(@vercel/nft@1.10.2)(alchemy@2.0.0-beta.87(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@types/react@19.2.17)(effect@4.1.4)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2))(effect@4.1.4)(prisma@8.0.0-rc.34(magicast@0.5.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2) '@internal/tsdown-config': specifier: workspace:0.39.0 version: link:../../0-foundation/tsdown-config @@ -942,7 +950,7 @@ importers: dependencies: '@alchemy.run/prisma': specifier: 'catalog:' - version: 2.0.0-beta.87(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@prisma/orm-postgres@8.0.0-rc.24(@prisma/cli-engine@0.10.0(@prisma/management-api-sdk@1.80.0)(magicast@0.5.5))(magicast@0.5.5)(temporal-polyfill@1.0.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(@vercel/nft@1.10.2)(alchemy@2.0.0-beta.87(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@types/react@19.2.17)(effect@4.1.4)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2))(effect@4.1.4)(prisma@8.0.0-rc.34(magicast@0.5.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2) + version: 2.0.0-beta.87(patch_hash=85fa0ad02c14a798351cf4a6d96d12a64a04c1170106dd9dcecdca985a082e69)(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@prisma/orm-postgres@8.0.0-rc.24(@prisma/cli-engine@0.10.0(@prisma/management-api-sdk@1.80.0)(magicast@0.5.5))(magicast@0.5.5)(temporal-polyfill@1.0.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(@vercel/nft@1.10.2)(alchemy@2.0.0-beta.87(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@types/react@19.2.17)(effect@4.1.4)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2))(effect@4.1.4)(prisma@8.0.0-rc.34(magicast@0.5.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2) '@internal/bundle-paths': specifier: workspace:0.39.0 version: link:../../../0-framework/2-authoring/bundle-paths @@ -1006,10 +1014,10 @@ importers: dependencies: '@alchemy.run/prisma': specifier: 'catalog:' - version: 2.0.0-beta.87(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@prisma/orm-postgres@8.0.0-rc.24(@prisma/cli-engine@0.10.0(@prisma/management-api-sdk@1.80.0)(magicast@0.5.5))(magicast@0.5.5)(temporal-polyfill@1.0.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(@vercel/nft@1.10.2)(alchemy@2.0.0-beta.87(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@types/react@19.2.17)(effect@4.1.4)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2))(effect@4.1.4)(prisma@8.0.0-rc.34(magicast@0.5.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2) + version: 2.0.0-beta.87(patch_hash=85fa0ad02c14a798351cf4a6d96d12a64a04c1170106dd9dcecdca985a082e69)(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@prisma/orm-postgres@8.0.0-rc.24(@prisma/cli-engine@0.10.0(@prisma/management-api-sdk@1.80.0)(magicast@0.5.5))(magicast@0.5.5)(temporal-polyfill@1.0.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(@vercel/nft@1.10.2)(alchemy@2.0.0-beta.87(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@types/react@19.2.17)(effect@4.1.4)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2))(effect@4.1.4)(prisma@8.0.0-rc.34(magicast@0.5.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2) '@distilled.cloud/prisma': specifier: 'catalog:' - version: 1.0.0-rc.20(effect@4.1.4) + version: 1.0.0-rc.20(patch_hash=cafb260be033a6bc0e7293f22afc601715dd32c47e1d826d9c99fccde7639dea)(effect@4.1.4) '@effect/platform-node': specifier: 'catalog:' version: 4.1.4(effect@4.1.4)(redis@6.2.1) @@ -1076,7 +1084,7 @@ importers: dependencies: '@alchemy.run/prisma': specifier: 'catalog:' - version: 2.0.0-beta.87(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@prisma/orm-postgres@8.0.0-rc.24(@prisma/cli-engine@0.10.0(@prisma/management-api-sdk@1.80.0)(magicast@0.5.5))(magicast@0.5.5)(temporal-polyfill@1.0.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.2)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(@vercel/nft@1.10.2)(alchemy@2.0.0-beta.87(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@types/react@19.2.17)(effect@4.1.4)(vite@8.1.2(@types/node@26.1.2)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2))(effect@4.1.4)(prisma@8.0.0-rc.34(magicast@0.5.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.2)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.2)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2) + version: 2.0.0-beta.87(patch_hash=85fa0ad02c14a798351cf4a6d96d12a64a04c1170106dd9dcecdca985a082e69)(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@prisma/orm-postgres@8.0.0-rc.24(@prisma/cli-engine@0.10.0(@prisma/management-api-sdk@1.80.0)(magicast@0.5.5))(magicast@0.5.5)(temporal-polyfill@1.0.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.2)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(@vercel/nft@1.10.2)(alchemy@2.0.0-beta.87(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@types/react@19.2.17)(effect@4.1.4)(vite@8.1.2(@types/node@26.1.2)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2))(effect@4.1.4)(prisma@8.0.0-rc.34(magicast@0.5.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.2)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.2)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2) '@internal/core': specifier: workspace:0.39.0 version: link:../../../0-framework/1-core/core @@ -1137,7 +1145,7 @@ importers: version: 3.1087.0 '@distilled.cloud/prisma': specifier: 'catalog:' - version: 1.0.0-rc.20(effect@4.1.4) + version: 1.0.0-rc.20(patch_hash=cafb260be033a6bc0e7293f22afc601715dd32c47e1d826d9c99fccde7639dea)(effect@4.1.4) '@internal/tsdown-config': specifier: workspace:0.39.0 version: link:../../../0-framework/0-foundation/tsdown-config @@ -1525,10 +1533,10 @@ importers: dependencies: '@alchemy.run/prisma': specifier: 'catalog:' - version: 2.0.0-beta.87(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@prisma/orm-postgres@8.0.0-rc.24(@prisma/cli-engine@0.10.0(@prisma/management-api-sdk@1.80.0)(magicast@0.5.5))(magicast@0.5.5)(temporal-polyfill@1.0.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(@vercel/nft@1.10.2)(alchemy@2.0.0-beta.87(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@types/react@19.2.17)(effect@4.1.4)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2))(effect@4.1.4)(prisma@8.0.0-rc.34(magicast@0.5.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2) + version: 2.0.0-beta.87(patch_hash=85fa0ad02c14a798351cf4a6d96d12a64a04c1170106dd9dcecdca985a082e69)(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@prisma/orm-postgres@8.0.0-rc.24(@prisma/cli-engine@0.10.0(@prisma/management-api-sdk@1.80.0)(magicast@0.5.5))(magicast@0.5.5)(temporal-polyfill@1.0.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(@vercel/nft@1.10.2)(alchemy@2.0.0-beta.87(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@types/react@19.2.17)(effect@4.1.4)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2))(effect@4.1.4)(prisma@8.0.0-rc.34(magicast@0.5.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2) '@distilled.cloud/prisma': specifier: 'catalog:' - version: 1.0.0-rc.20(effect@4.1.4) + version: 1.0.0-rc.20(patch_hash=cafb260be033a6bc0e7293f22afc601715dd32c47e1d826d9c99fccde7639dea)(effect@4.1.4) '@effect/platform-bun': specifier: 'catalog:' version: 4.1.4(effect@4.1.4) @@ -5717,11 +5725,11 @@ snapshots: chokidar: 5.0.0 rolldown: 1.2.16 - '@alchemy.run/prisma@2.0.0-beta.87(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@prisma/orm-postgres@8.0.0-rc.24(@prisma/cli-engine@0.10.0(@prisma/management-api-sdk@1.80.0)(magicast@0.5.5))(magicast@0.5.5)(temporal-polyfill@1.0.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(@vercel/nft@1.10.2)(alchemy@2.0.0-beta.87(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@types/react@19.2.17)(effect@4.1.4)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2))(effect@4.1.4)(prisma@8.0.0-rc.34(magicast@0.5.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2)': + '@alchemy.run/prisma@2.0.0-beta.87(patch_hash=85fa0ad02c14a798351cf4a6d96d12a64a04c1170106dd9dcecdca985a082e69)(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@prisma/orm-postgres@8.0.0-rc.24(@prisma/cli-engine@0.10.0(@prisma/management-api-sdk@1.80.0)(magicast@0.5.5))(magicast@0.5.5)(temporal-polyfill@1.0.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(@vercel/nft@1.10.2)(alchemy@2.0.0-beta.87(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@types/react@19.2.17)(effect@4.1.4)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2))(effect@4.1.4)(prisma@8.0.0-rc.34(magicast@0.5.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2)': dependencies: '@distilled.cloud/aws': 1.0.0-rc.20(effect@4.1.4) '@distilled.cloud/core': 1.0.0-rc.20(effect@4.1.4) - '@distilled.cloud/prisma': 1.0.0-rc.20(effect@4.1.4) + '@distilled.cloud/prisma': 1.0.0-rc.20(patch_hash=cafb260be033a6bc0e7293f22afc601715dd32c47e1d826d9c99fccde7639dea)(effect@4.1.4) '@prisma/dev': 0.25.2(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)) alchemy: 2.0.0-beta.87(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@types/react@19.2.17)(effect@4.1.4)(vite@8.1.2(@types/node@26.1.1)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2) effect: 4.1.4 @@ -5737,11 +5745,11 @@ snapshots: - typescript - vite - '@alchemy.run/prisma@2.0.0-beta.87(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@prisma/orm-postgres@8.0.0-rc.24(@prisma/cli-engine@0.10.0(@prisma/management-api-sdk@1.80.0)(magicast@0.5.5))(magicast@0.5.5)(temporal-polyfill@1.0.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.2)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(@vercel/nft@1.10.2)(alchemy@2.0.0-beta.87(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@types/react@19.2.17)(effect@4.1.4)(vite@8.1.2(@types/node@26.1.2)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2))(effect@4.1.4)(prisma@8.0.0-rc.34(magicast@0.5.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.2)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.2)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2)': + '@alchemy.run/prisma@2.0.0-beta.87(patch_hash=85fa0ad02c14a798351cf4a6d96d12a64a04c1170106dd9dcecdca985a082e69)(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@prisma/orm-postgres@8.0.0-rc.24(@prisma/cli-engine@0.10.0(@prisma/management-api-sdk@1.80.0)(magicast@0.5.5))(magicast@0.5.5)(temporal-polyfill@1.0.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.2)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(@vercel/nft@1.10.2)(alchemy@2.0.0-beta.87(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@types/react@19.2.17)(effect@4.1.4)(vite@8.1.2(@types/node@26.1.2)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2))(effect@4.1.4)(prisma@8.0.0-rc.34(magicast@0.5.5)(typanion@3.14.0)(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.2)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.2)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2)': dependencies: '@distilled.cloud/aws': 1.0.0-rc.20(effect@4.1.4) '@distilled.cloud/core': 1.0.0-rc.20(effect@4.1.4) - '@distilled.cloud/prisma': 1.0.0-rc.20(effect@4.1.4) + '@distilled.cloud/prisma': 1.0.0-rc.20(patch_hash=cafb260be033a6bc0e7293f22afc601715dd32c47e1d826d9c99fccde7639dea)(effect@4.1.4) '@prisma/dev': 0.25.2(typescript@6.0.3)(vite@8.1.2(@types/node@26.1.2)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)) alchemy: 2.0.0-beta.87(@effect/platform-bun@4.1.4(effect@4.1.4))(@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1))(@types/react@19.2.17)(effect@4.1.4)(vite@8.1.2(@types/node@26.1.2)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))(ws@8.22.2) effect: 4.1.4 @@ -6138,7 +6146,7 @@ snapshots: dependencies: effect: 4.1.4 - '@distilled.cloud/prisma@1.0.0-rc.20(effect@4.1.4)': + '@distilled.cloud/prisma@1.0.0-rc.20(patch_hash=cafb260be033a6bc0e7293f22afc601715dd32c47e1d826d9c99fccde7639dea)(effect@4.1.4)': dependencies: '@distilled.cloud/core': 1.0.0-rc.20(effect@4.1.4) '@distilled.cloud/s3': 1.0.0-rc.20(effect@4.1.4) diff --git a/scripts/check-patched-dependencies.test.ts b/scripts/check-patched-dependencies.test.ts new file mode 100644 index 000000000..9fe883c9b --- /dev/null +++ b/scripts/check-patched-dependencies.test.ts @@ -0,0 +1,149 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; + +import { + failureMessage, + type Lockfile, + packageNameOf, + patchedNames, + patchedRuntimeDependencies, +} from './check-patched-dependencies.ts'; + +const lockfile: Lockfile = { + patchedDependencies: { '@alchemy.run/prisma@2.0.0': { path: 'patches/a.patch' } }, + importers: { + 'packages/9-public/cloud': { + dependencies: { + '@alchemy.run/prisma': { version: '2.0.0(patch_hash=abc)' }, + '@prisma/composer': { version: 'link:../composer' }, + 'third-party': { version: '1.0.0' }, + }, + }, + 'packages/9-public/composer': { + dependencies: { effect: { version: '4.1.4' } }, + }, + 'packages/1-prisma-cloud/lowering': { + dependencies: { 'bundled-only': { version: '1.0.0' } }, + }, + }, + snapshots: { + '@alchemy.run/prisma@2.0.0(patch_hash=abc)': { + dependencies: { '@distilled.cloud/prisma': '1.0.0(patch_hash=def)' }, + }, + '@distilled.cloud/prisma@1.0.0(patch_hash=def)': {}, + 'third-party@1.0.0': { dependencies: { 'deep-patched': '3.0.0' } }, + 'deep-patched@3.0.0': {}, + 'effect@4.1.4': {}, + 'bundled-only@1.0.0': {}, + }, +}; + +const published = new Map([ + ['packages/9-public/cloud', '@prisma/composer-prisma-cloud'], + ['packages/9-public/composer', '@prisma/composer'], +]); + +describe('patchedRuntimeDependencies', () => { + it('names a patched package a published package lists', () => { + assert.deepEqual( + patchedRuntimeDependencies(new Set(['@alchemy.run/prisma']), published, lockfile), + [ + { + patched: '@alchemy.run/prisma', + publishedPackage: '@prisma/composer-prisma-cloud', + via: [], + }, + ], + ); + }); + + it('finds a patched package that only a third-party dependency pulls in', () => { + assert.deepEqual(patchedRuntimeDependencies(new Set(['deep-patched']), published, lockfile), [ + { + patched: 'deep-patched', + publishedPackage: '@prisma/composer-prisma-cloud', + via: ['third-party'], + }, + ]); + assert.deepEqual( + patchedRuntimeDependencies(new Set(['@distilled.cloud/prisma']), published, lockfile), + [ + { + patched: '@distilled.cloud/prisma', + publishedPackage: '@prisma/composer-prisma-cloud', + via: ['@alchemy.run/prisma'], + }, + ], + ); + }); + + it('follows the workspace packages a published package installs', () => { + assert.deepEqual(patchedRuntimeDependencies(new Set(['effect']), published, lockfile), [ + { + patched: 'effect', + publishedPackage: '@prisma/composer-prisma-cloud', + via: ['@prisma/composer'], + }, + { patched: 'effect', publishedPackage: '@prisma/composer', via: [] }, + ]); + }); + + it('ignores a patched package reached only through a bundled workspace package', () => { + assert.deepEqual( + patchedRuntimeDependencies(new Set(['bundled-only']), published, lockfile), + [], + ); + }); + + it('passes when nothing is patched', () => { + assert.deepEqual(patchedRuntimeDependencies(new Set(), published, lockfile), []); + }); +}); + +describe('patchedNames', () => { + it('takes a patch declared only in pnpm-workspace.yaml', () => { + assert.deepEqual( + patchedNames({ + rootManifest: {}, + workspaceFile: { patchedDependencies: { 'only-in-workspace@1.0.0': 'patches/w.patch' } }, + lockfile: { importers: {} }, + }), + new Set(['only-in-workspace']), + ); + }); + + it('takes patches from the root manifest and the lockfile', () => { + assert.deepEqual( + patchedNames({ + rootManifest: { pnpm: { patchedDependencies: { 'in-manifest@1.0.0': 'p' } } }, + workspaceFile: null, + lockfile, + }), + new Set(['in-manifest', '@alchemy.run/prisma']), + ); + }); +}); + +describe('packageNameOf', () => { + it('drops the version from a scoped and an unscoped patch key', () => { + assert.equal(packageNameOf('@alchemy.run/prisma@2.0.0-beta.87'), '@alchemy.run/prisma'); + assert.equal(packageNameOf('alchemy@2.0.0-beta.87'), 'alchemy'); + }); +}); + +describe('failureMessage', () => { + it('names the dependency and the published package, and says why it fails', () => { + const message = failureMessage([ + { + patched: '@distilled.cloud/prisma', + publishedPackage: '@prisma/composer-prisma-cloud', + via: ['@alchemy.run/prisma'], + }, + ]); + assert.match( + message, + /@prisma\/composer-prisma-cloud depends on @distilled\.cloud\/prisma \(through @alchemy\.run\/prisma\)/, + ); + assert.match(message, /gets the unpatched dependency/); + }); +}); diff --git a/scripts/check-patched-dependencies.ts b/scripts/check-patched-dependencies.ts new file mode 100644 index 000000000..de9abcf1e --- /dev/null +++ b/scripts/check-patched-dependencies.ts @@ -0,0 +1,162 @@ +#!/usr/bin/env bun +/** + * Fails when a package this workspace patches with `pnpm patch` is in the run-time install of a published package, by any path. + * A patch applies only to this workspace's install; a user's install gets the unpatched package. + */ +import { readFileSync } from 'node:fs'; +import * as path from 'node:path'; + +const usage = 'Usage: bun scripts/check-patched-dependencies.ts, run from the repository root'; + +type Resolved = Readonly>; + +/** The parts of `pnpm-lock.yaml` the check reads. */ +export interface Lockfile { + readonly patchedDependencies?: Readonly>; + readonly importers: Readonly< + Record + >; + readonly snapshots?: Readonly< + Record< + string, + { + readonly dependencies?: Readonly>; + readonly optionalDependencies?: Readonly>; + } | null + > + >; +} + +export interface PatchedRuntimeDependency { + readonly patched: string; + readonly publishedPackage: string; + readonly via: readonly string[]; +} + +/** `@scope/name@1.2.3` → `@scope/name`. */ +export function packageNameOf(patchKey: string): string { + const at = patchKey.lastIndexOf('@'); + return at > 0 ? patchKey.slice(0, at) : patchKey; +} + +/** Every package name a patch is declared for: in the root manifest, in the workspace file, or recorded in the lockfile. */ +export function patchedNames(declared: { + readonly rootManifest?: { readonly pnpm?: { readonly patchedDependencies?: object } }; + readonly workspaceFile?: { readonly patchedDependencies?: object } | null; + readonly lockfile: Lockfile; +}): Set { + return new Set( + [ + ...Object.keys(declared.rootManifest?.pnpm?.patchedDependencies ?? {}), + ...Object.keys(declared.workspaceFile?.patchedDependencies ?? {}), + ...Object.keys(declared.lockfile.patchedDependencies ?? {}), + ].map(packageNameOf), + ); +} + +/** + * Walks each published importer's `dependencies` and `optionalDependencies` through the lockfile: the workspace + * packages it installs (`link:`) and every third-party package below them. A workspace package that is only a + * devDependency is bundled, and its imports are inlined unless the published package lists them, so only listed + * dependencies reach a user's install. + */ +export function patchedRuntimeDependencies( + patched: ReadonlySet, + published: ReadonlyMap, + lockfile: Lockfile, +): PatchedRuntimeDependency[] { + const found: PatchedRuntimeDependency[] = []; + for (const [importerPath, publishedPackage] of published) { + const seen = new Set(); + const reported = new Set(); + const walkImporter = (importer: string, via: readonly string[]): void => { + if (seen.has(`importer:${importer}`)) return; + seen.add(`importer:${importer}`); + const entry = lockfile.importers[importer]; + for (const [dependency, { version }] of Object.entries({ + ...entry?.dependencies, + ...entry?.optionalDependencies, + })) { + visit(dependency, version, importer, via); + } + }; + const visit = (name: string, version: string, from: string, via: readonly string[]): void => { + if (patched.has(name) && !reported.has(name)) { + reported.add(name); + found.push({ patched: name, publishedPackage, via }); + } + if (version.startsWith('link:')) { + const linked = path.posix.normalize(path.posix.join(from, version.slice('link:'.length))); + walkImporter(linked, [...via, name]); + return; + } + const key = `${name}@${version}`; + if (seen.has(key)) return; + seen.add(key); + const snapshot = lockfile.snapshots?.[key]; + for (const [dependency, dependencyVersion] of Object.entries({ + ...snapshot?.dependencies, + ...snapshot?.optionalDependencies, + })) { + visit(dependency, dependencyVersion, from, [...via, name]); + } + }; + walkImporter(importerPath, []); + } + return found; +} + +export function failureMessage(found: readonly PatchedRuntimeDependency[]): string { + const lines = found.map( + ({ patched, publishedPackage, via }) => + `- ${publishedPackage} depends on ${patched}${via.length > 0 ? ` (through ${via.join(' → ')})` : ''}`, + ); + return ( + 'A published package depends at run time on a package this workspace patches with `pnpm patch`:\n' + + `${lines.join('\n')}\n` + + 'A patch applies only to this workspace. A user who installs the published package gets the unpatched dependency, ' + + 'so the release would behave differently from what was tested. Release the change upstream, raise the pin to that ' + + 'release and remove the patch before publishing.' + ); +} + +const isRecord = (value: unknown): value is Record => + typeof value === 'object' && value !== null; + +const isLockfile = (value: unknown): value is Lockfile => + isRecord(value) && isRecord(value['importers']); + +function readText(file: string): string { + try { + return readFileSync(file, 'utf8'); + } catch { + console.error(`Cannot read ${file}. ${usage}`); + process.exit(1); + } +} + +if (import.meta.main) { + const root = process.cwd(); + const lockfile = Bun.YAML.parse(readText(path.join(root, 'pnpm-lock.yaml'))); + if (!isLockfile(lockfile)) { + console.error(`pnpm-lock.yaml has no importers. ${usage}`); + process.exit(1); + } + const workspaceFile = Bun.YAML.parse(readText(path.join(root, 'pnpm-workspace.yaml'))); + const patched = patchedNames({ + rootManifest: JSON.parse(readText(path.join(root, 'package.json'))), + workspaceFile: isRecord(workspaceFile) ? workspaceFile : null, + lockfile, + }); + const published = new Map(); + for (const importer of Object.keys(lockfile.importers)) { + if (!importer.startsWith('packages/9-public/')) continue; + published.set(importer, JSON.parse(readText(path.join(root, importer, 'package.json'))).name); + } + const found = patchedRuntimeDependencies(patched, published, lockfile); + if (found.length > 0) { + console.error(failureMessage(found)); + process.exit(1); + } + console.log(`No published package depends on a patched package (${published.size} checked).`); +} diff --git a/test/integration/test/local-dev.integration.ts b/test/integration/test/local-dev.integration.ts index 83d20c508..7e9b356b5 100644 --- a/test/integration/test/local-dev.integration.ts +++ b/test/integration/test/local-dev.integration.ts @@ -545,31 +545,15 @@ async function main(): Promise { assert(typeof webInfo.pid === 'number', 'web service must report a pid'); assert(typeof bkgInfo.pid === 'number', 'bkg service must report a pid'); - // 10. env store correct: every row lives in the COMPOSER_ namespace. - // Composer writes no unprefixed variable — an unprefixed name is a - // platform-owned one (DATABASE_URL and friends), and the platform manages - // those itself. The port-override row - // (COMPOSER_
_PORT) is deliberately NEVER persisted to env.json - // (local-dev spec § 4: "Ports live nowhere here" — the Deployment - // provider materializes it fresh into each deployment's own env, in - // memory, and never writes it back) — so it is verified through the - // fixture's own /health response (captured above, before webInfo existed - // to compare against) rather than by reading env.json for a key it never - // receives. - const envRaw = readJson(path.join(devDir, 'env.json')); - assert( - typeof envRaw === 'object' && envRaw !== null, - 'env.json exists and parses to an object', - ); - const env = envRaw as Record; - // Non-empty first: an empty object would vacuously pass every check below. - assert(Object.keys(env).length > 0, 'env.json carries the deploy-written rows'); - assertEqual(env['DATABASE_URL'], undefined, 'env.json holds no DATABASE_URL row'); - assertEqual(env['DATABASE_URL_POOLED'], undefined, 'env.json holds no DATABASE_URL_POOLED row'); + // 10. A service that runs its artifact takes its COMPOSER_ keys from its + // deployment's variables, so nothing is written to env.json; the port is + // the emulator's, laid over the one in the variables. + const envFile = path.join(devDir, 'env.json'); + const env = fs.existsSync(envFile) ? (readJson(envFile) as Record) : {}; assertEqual( - Object.keys(env).every((key) => key.startsWith('COMPOSER_')), - true, - 'every env.json row lives in the COMPOSER_ namespace', + Object.keys(env).length, + 0, + 'env.json holds no row for a service that runs its artifact', ); assertEqual( health.portEnv,