diff --git a/docs/product/command-principles.md b/docs/product/command-principles.md index 19142fbed..65e15f4a3 100644 --- a/docs/product/command-principles.md +++ b/docs/product/command-principles.md @@ -93,6 +93,26 @@ No current branch command uses `use`; branch targeting follows explicit flags or Build and release an app into a target branch. +`deploy` has two paths, and the repository decides which one runs: + +- **Composer deploy.** A loaded `prisma.config.ts` declares a `composer` section. Composer's own `deploy` command runs, unchanged. The test is Composer's own: its section validator decides whether the section is missing. +- **Single-app deploy.** No loaded `prisma.config.ts` declares a `composer` section. The CLI deploys the one app in the current folder from the repository's own install, build and start commands. It holds no framework rules. + +A repository that shows another sign of a Composer app still takes the Composer path, and fails with Composer's `CONFIG.SECTION_MISSING` error: `--entry` names a file that exists, or a `prisma-composer.config.*` file is present. A single-app deploy ignores an `--entry` that names no file, because prisma/cloud-deploy-action always passes `--entry module.ts`. + +A single-app deploy works like this: + +- **Build settings.** Install, Build, Start or Static folder, and Port. Each has a Source: `prisma.config.ts`, `package.json`, the lockfile, the build output, an entry file, or a default. The rules live in `@prisma/compute-sdk/app`; the CLI calls `resolveBuildSettings`, `buildApp` and `deployApp` and adds none of its own. +- **App config.** The `app` section of `prisma.config.ts`: `install`, `build`, `start`, `static`, `port`. Every field is optional and replaces the rule for that setting. An unknown field is an error. +- **Project.** The project the directory is linked to, or `--project`. It is resolved the way the `service` commands resolve it. A single-app deploy never creates a project. +- **Branch.** `--environment production` (the default) is the project's default Branch. Any other name is the Branch with that git name, created when it does not exist. +- **Service.** Named by `--name`, else the `name` in `package.json` without its scope, else the folder name. The service on the Branch with that name is reused; otherwise one is created. +- **Start check.** The app is started on Prisma Cloud before it gets traffic. The version is promoted only when the app listens on the routed port. When the app listens on another port and no port was stated, the deploy runs once more with that port. An app that exits, or opens no port within 60 seconds, fails the deploy and leaves the live version unchanged. +- **Environment variables.** The platform gives a new version the project's variables for the Branch's scope. `deploy` sends none of its own. +- **Exit code.** Every failure is a structured error and exits non-zero: a failed install or build, no start command, a failed start, a failed API call. + +Human output is a card with the target and the Build settings, one line per finished step, then the URL. On stdout, a single-app deploy writes the same data line as a Composer deploy: the service name, `compute-service`, the service id and the URL, separated by tabs. + ### `init` Prepare the current repository for Prisma development, entirely locally: add the `postinstall` script that keeps the Prisma agent skills in sync (`prisma skills sync || exit 0`), add `prisma` to `devDependencies` at the CLI's exact version when no dependency field declares it, scaffold a `prisma.config.ts` recording which agents get skills, then sync the skills once now. diff --git a/docs/reference/error-reference.md b/docs/reference/error-reference.md index 5996d976f..21efe001d 100644 --- a/docs/reference/error-reference.md +++ b/docs/reference/error-reference.md @@ -20,7 +20,7 @@ Namespaces: | `BUCKET` | Bucket and bucket-key management (`prisma bucket`) | | `CLI` | Engine-level invocation: arguments, config loading, prompts, consent, credentials, child processes | | `CONFIG` | The `composer` section of `prisma.config.ts` and its `config` and `secrets` adapters (`prisma dev`, `prisma deploy`) | -| `DEPLOY` | Deploying, listing and destroying a Composer app (`prisma deploy`, `prisma deploy list`, and the `deploy` and `destroy` operations of `@prisma/composer/control`) | +| `DEPLOY` | Deploying, listing and destroying a Composer app (`prisma deploy`, `prisma deploy list`, and the `deploy` and `destroy` operations of `@prisma/composer/control`), and a single-app deploy (`prisma deploy` in a repository with no Composer config), whose codes start with `DEPLOY.APP_` | | `DEV` | Running an app on this machine with Composer (`prisma dev`, `prisma dev url`, `prisma dev stop`, `prisma emulator list`) | | `FEEDBACK` | Sending product feedback (`prisma feedback`) | | `GIT` | Git repository connections (`prisma git`) | @@ -320,6 +320,34 @@ These codes come from Composer, the command family behind `prisma deploy`, `pris Composer starts the deploy engine from the `alchemy` package installed beside `@prisma/composer`, and either `@prisma/composer` itself could not be resolved from the app, or no runnable engine entry could be resolved beside it. Layouts without a `node_modules` directory, such as Yarn Plug'n'Play, are not supported. The fix is to check that the app depends on `@prisma/composer` and to reinstall dependencies so `@prisma/composer` and its `alchemy` dependency sit in a `node_modules` directory. Meta: none. +### DEPLOY.APP_BUILD_FAILED + +A single-app deploy ran the app's build command and it exited with an error. Nothing was uploaded. The end of the command's output is printed before the error (in `--json` mode, as `output` events with `source: "build"`). The fix is to run the build command in the app folder and fix what it reports, or to set `build` in the `app` section of `prisma.config.ts`. Meta: `command`, `seconds`. + +### DEPLOY.APP_EXITED + +A single-app deploy uploaded a version and started it, and the app exited. The version was not promoted, so the version that serves traffic did not change. The app's own output is printed before the error (in `--json` mode, as `output` events with `source: "app"`), and `meta.start.output` carries it. A common cause is an environment variable the app needs: set it with `prisma project env add`, then deploy again. Meta: `serviceId`, `versionId`, `url` (the version's own URL), `port`, `start` (`state`, `code`, `output`). + +### DEPLOY.APP_INSTALL_FAILED + +A single-app deploy ran the app's install command and it exited with an error. Nothing was built or uploaded. The end of the command's output is printed before the error (in `--json` mode, as `output` events with `source: "install"`). The fix is to run the install command in the app folder and fix what it reports, or to set `install` in the `app` section of `prisma.config.ts`. Meta: `command`, `seconds`. + +### DEPLOY.APP_NO_START + +A single-app deploy found no way to start the app, so nothing was uploaded. No rule matched: the `start` script is missing or runs a development server, the build wrote no server file and no static site, and the folder holds no entry file such as `index.ts`. The fix is to add a `start` script to `package.json`, or to set `start` (a command) or `static` (a folder of static files) in the `app` section of `prisma.config.ts`. Meta: none. + +### DEPLOY.APP_PORT_MISMATCH + +A single-app deploy started the app, and the app listens on another port than the one requests are sent to. The version was not promoted. This happens when `port` in the `app` section names a port the app does not use, or when the app picks a different port on each start. The fix is to set `port` to the port the app listens on, or to make the app listen on the port in the `PORT` environment variable. Meta: `serviceId`, `versionId`, `url`, `port` (the routed port), `start` (`state`, `port`). + +### DEPLOY.APP_SILENT + +A single-app deploy started the app, and the app neither opened a port nor exited within 60 seconds. The version was not promoted. The app's output so far is printed before the error. The fix is to make the app listen on the port in the `PORT` environment variable. Meta: `serviceId`, `versionId`, `url`, `port`, `start` (`state`, `output`). + +### DEPLOY.APP_USAGE_ERROR + +`--project` was passed to a deploy of a Prisma Composer app. The flag names the Project of a single-app deploy only; a Composer app is deployed into the project named after the app, so the flag is refused instead of ignored. The fix is to remove `--project`, or to pass `--name` to deploy the app under another name. Meta: none. + ### DEPLOY.BUILD_REQUIRED Assembling a service failed during a destroy. Destroy evaluates the same stack program as deploy, which packages the built artifacts, so an app must be built before it can be torn down. The fix is to run the build, then retry the destroy. The underlying assemble error rides as the cause. diff --git a/packages/cli/README.md b/packages/cli/README.md index 23dbd2cc9..0872ddc8e 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -77,7 +77,7 @@ This package exposes `prisma-cli` so it can coexist with the existing | `postgres` | Create, inspect, back up, restore, and delete Prisma Postgres databases and their connections. | | `bucket` | Create, list, and delete object-store buckets and their access keys. | | `service` | Inspect services: versions, logs, domains, promote, roll back, delete. | -| `dev`, `deploy` | Run a Composer app locally; deploy it to the platform. `dev url` prints a running node's local URL and `dev stop` stops the app. | +| `dev`, `deploy` | Run a Composer app locally; deploy it to the platform. `dev url` prints a running node's local URL and `dev stop` stops the app. In a repository with no Composer config, `deploy` deploys the one app in the folder from its own install, build and start commands. | | `emulator` | List the local emulators `prisma dev` runs services, databases and buckets on. | | `contract`, `db`, `migration`, `orm init`, `lsp` | The Prisma ORM workflow. | diff --git a/packages/cli/e2e/deploy.e2e.ts b/packages/cli/e2e/deploy.e2e.ts new file mode 100644 index 000000000..bb8dffe88 --- /dev/null +++ b/packages/cli/e2e/deploy.e2e.ts @@ -0,0 +1,86 @@ +/** + * `deploy` in a repository with no Composer config: a single-app deploy. + * The app is one file with a `start` script and no dependencies, so the + * run needs no package manager and builds nothing. + */ +import { writeFile } from "node:fs/promises"; +import path from "node:path"; +import { expect, it } from "vitest"; + +import { useScratchProject } from "./scratch"; +import { describeCommand, session } from "./suite"; + +const scratch = useScratchProject("deploy"); + +const SERVER = + 'require("node:http").createServer((_, response) => response.end("single-app e2e")).listen(process.env.PORT);\n'; + +interface DeployResult { + readonly app: string; + readonly project: { readonly id: string }; + readonly branch: { readonly production: boolean }; + readonly service: { readonly id: string; readonly name: string }; + readonly settings: { + readonly start: { readonly value: string; readonly from: string } | null; + }; + readonly versionId: string; + readonly url: string; + readonly start: { readonly state: string; readonly port?: number }; + readonly promoted: boolean; +} + +/** A new deployment's URL can take a moment to route. */ +async function fetchText(url: string): Promise { + let last = ""; + for (let attempt = 0; attempt < 15; attempt += 1) { + // biome-ignore lint/performance/noAwaitInLoops: each attempt waits for the one before it. + const response = await fetch(url).catch(() => undefined); + if (response?.ok) { + return response.text(); + } + last = response === undefined ? "no response" : `HTTP ${response.status}`; + await new Promise((resolve) => setTimeout(resolve, 2000)); + } + throw new Error(`${url} did not answer: ${last}`); +} + +describeCommand("deploy", () => { + it("deploys an app that has no Composer config, from its own start script", async () => { + const cli = await session(); + const app = await cli.workdir(); + await writeFile( + path.join(app, "package.json"), + JSON.stringify({ + name: "@e2e/web", + private: true, + scripts: { start: "node server.js" }, + }), + ); + await writeFile(path.join(app, "server.js"), SERVER); + + const run = await cli.run(["deploy", "--project", scratch.project().id], { + cwd: app, + timeoutMs: 170_000, + }); + const result = run.envelope.result as DeployResult; + + expect(result.app).toBe("web"); + expect(result.project.id).toBe(scratch.project().id); + expect(result.branch.production).toBe(true); + expect(result.settings.start).toEqual({ + value: "node server.js", + from: "package.json", + }); + expect(result.start).toEqual({ state: "listening", port: 8080 }); + expect(result.promoted).toBe(true); + expect(await fetchText(result.url)).toBe("single-app e2e"); + + const shown = await scratch.run(["service", "show", result.service.id]); + const service = shown.envelope.result as { + readonly service: { readonly name: string }; + readonly liveDeployment?: { readonly id: string } | null; + }; + expect(service.service.name).toBe("web"); + expect(JSON.stringify(shown.envelope.result)).toContain(result.versionId); + }); +}); diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index 79007cc87..c784fb3b7 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -23,6 +23,11 @@ import { bucketKeyCreateCommand } from "./commands/bucket/key-create"; import { bucketKeyDeleteCommand } from "./commands/bucket/key-delete"; import { bucketKeyListCommand } from "./commands/bucket/key-list"; import { bucketListCommand } from "./commands/bucket/list"; +import { createDeployCommand } from "./commands/deploy/command"; +import { + appConfigSection, + deployConfigSection, +} from "./commands/deploy/config"; import { feedbackCommand } from "./commands/feedback"; import { gitConnectCommand } from "./commands/git/connect"; import { gitDisconnectCommand } from "./commands/git/disconnect"; @@ -72,6 +77,9 @@ import { getCliVersion } from "./lib/version"; import { v7CommandFamily } from "./v7-redirects"; export const platformCommandFamily: CommandFamily = defineCommandFamily({ + // The `app` section holds the App config of a single-app deploy. `deploy` + // reads it; it is declared here so prisma.config.ts may carry it. + configSection: appConfigSection, docsBaseUrl: DOCS_ERRORS_BASE_URL, commands: { login: authLoginCommand, @@ -141,6 +149,21 @@ export const platformCommandFamily: CommandFamily = defineCommandFamily({ */ export const composerCommandFamily: CommandFamily = createComposerFamily(); +/** + * `deploy` is the shell's own command: Composer's deploy when the + * repository has a Composer config, a single-app deploy otherwise. It is + * a family of its own because it reads the `composer` section through a + * validator that accepts a missing section. + */ +export const deployCommand = createDeployCommand( + composerCommandFamily.commands.deploy, +); +export const deployCommandFamily: CommandFamily = defineCommandFamily({ + configSection: deployConfigSection, + docsBaseUrl: DOCS_ERRORS_BASE_URL, + commands: { deploy: deployCommand }, +}); + /** * The ORM commands, contributed by orm-toolchain's own package, mounted * as shipped: the family keys are the mount paths, so the shell adds @@ -426,9 +449,10 @@ export const mountedCommands: Readonly> = { "service domain delete": serviceDomainDeleteCommand, "service domain retry": serviceDomainRetryCommand, "service domain wait": serviceDomainWaitCommand, - // Composer's product verbs: deploy and dev at the root, their - // children beneath them, and the local emulators under their own group. - deploy: composerCommandFamily.commands.deploy, + // `deploy` chooses between Composer's deploy and a single-app deploy. + // Composer's other verbs mount as shipped: deploy list, dev and its + // children, and the local emulators under their own group. + deploy: deployCommand, "deploy list": composerCommandFamily.commands["deploy list"], dev: composerCommandFamily.commands.dev, "dev url": composerCommandFamily.commands["dev url"], @@ -478,6 +502,7 @@ export function buildCli(): Cli { commandFamilies: [ platformCommandFamily, composerCommandFamily, + deployCommandFamily, ormCommandFamily, skillsCommandFamily, v7CommandFamily, diff --git a/packages/cli/src/commands/deploy/command.ts b/packages/cli/src/commands/deploy/command.ts new file mode 100644 index 000000000..93148045e --- /dev/null +++ b/packages/cli/src/commands/deploy/command.ts @@ -0,0 +1,108 @@ +import { + type AnyCommand, + type CommandContext, + defineCommand, + flag, + type PresentedResult, +} from "@prisma/cli-engine"; +import { + type CliStructuredError, + notOk, + type Result, +} from "@prisma/cli-engine/protocol"; +import { + type ComposerConfig, + composerAppSign, + composerSectionMissingError, + deployConfigSection, +} from "./config"; +import { projectFlagOnComposerDeployError } from "./errors"; +import { deploySingleApp } from "./single-app"; + +/** Composer's `deploy` handler, as the engine calls it: Composer's own flags and its validated section. */ +type ComposerDeployHandler = ( + args: { + readonly flags: Record; + readonly positionals: Record; + }, + ctx: CommandContext, +) => Promise, CliStructuredError>>; + +function stringFlag(value: unknown): string | undefined { + return typeof value === "string" ? value : undefined; +} + +/** + * `deploy`: Composer's deploy for a repository with a Composer config, a + * single-app deploy for every other repository. Composer's command is + * taken as a parameter so its flags stay Composer's own definitions. + */ +export function createDeployCommand(composerDeploy: AnyCommand) { + if (composerDeploy.kind !== "result-command") { + throw new Error("Composer's deploy must be a result command"); + } + const runComposerDeploy = composerDeploy.handler as ComposerDeployHandler; + + return defineCommand({ + help: { + summary: + "Deploy the app in this folder to Prisma Cloud: build it, upload it, start it, and send traffic to it once it listens", + description: + "What is deployed depends on the repository. With a `composer` section in prisma.config.ts, this deploys the Prisma Composer app whose root is the entry module's default export, with its services, databases and buckets. Without one, this is a single-app deploy: it deploys the one app in this folder as a service of a Project, with no framework rules. A single-app deploy runs the app's own commands, called its Build settings. Install comes from the lockfile. Build is the `build` script of package.json. Start is the first of: the `start` script unless it runs a development server, a server file or a static site that the build wrote, an entry file such as index.ts. The app must listen on the port in the PORT environment variable. Each Build setting can be replaced in the `app` section of prisma.config.ts, called the App config: `install`, `build`, `start`, `static` (a folder of static files to serve) and `port`. The Project is the one this folder is linked to, or the one --project names. The app starts on Prisma Cloud before it gets traffic: when it exits or opens no port, the deploy fails and the version that serves traffic stays the same. A single-app deploy does not use --entry, --report or --build-id.", + examples: [ + "{bin} deploy", + "{bin} deploy --environment staging", + "{bin} deploy --project my-project --name web", + "{bin} deploy --entry other-module.ts", + ], + }, + args: { + flags: { + ...composerDeploy.args.flags, + name: flag.string({ + brief: + "Deploy the app under this name. A different name is a separate app on Prisma Cloud. Default for a Composer app: the name its root module declares. Default for a single-app deploy: the `name` in package.json, else the folder name; it names the service", + placeholder: "name", + }), + project: flag.string({ + brief: + "Single-app deploy only: the Project to deploy into, by id or name (default: the project this directory is linked to). A Composer app is deployed into the project named after the app", + placeholder: "id-or-name", + }), + }, + }, + needs: { config: deployConfigSection, credentials: true }, + // A single-app deploy reads the deployment's log over a WebSocket, + // which needs the access token itself. + managesCredentials: true, + handler: async (args, ctx) => { + const { config } = ctx; + // Composer's flags are declared by spreading, so their types are not known here. + const flags: Record = args.flags; + if (config !== undefined) { + if (args.flags.project !== undefined) { + return notOk(projectFlagOnComposerDeployError()); + } + return runComposerDeploy(args, { ...ctx, config }); + } + + const sign = composerAppSign({ + entry: stringFlag(flags.entry), + cwd: ctx.cwd, + configFiles: ctx.configFiles, + }); + if (sign !== undefined) { + return notOk(composerSectionMissingError(sign)); + } + + return deploySingleApp( + { + project: args.flags.project, + name: args.flags.name, + environment: stringFlag(flags.environment), + }, + ctx, + ); + }, + }); +} diff --git a/packages/cli/src/commands/deploy/config.ts b/packages/cli/src/commands/deploy/config.ts new file mode 100644 index 000000000..3c003c374 --- /dev/null +++ b/packages/cli/src/commands/deploy/config.ts @@ -0,0 +1,153 @@ +import { existsSync } from "node:fs"; +import path from "node:path"; +import { + type ConfigSection, + configSchema, + defineConfigSection, + type LoadedConfigFile, + resolveSectionOverChain, +} from "@prisma/cli-engine"; +import { + CliStructuredError, + type Diagnostic, +} from "@prisma/cli-engine/protocol"; +import { composerSection } from "@prisma/composer-cli/family"; +import type { AppConfig } from "@prisma/compute-sdk/app"; + +/** Composer's configuration, as its own section validator returns it. */ +export type ComposerConfig = + typeof composerSection extends ConfigSection ? T : never; + +/** The code Composer's validator gives when no loaded prisma.config.ts declares a `composer` section. */ +const COMPOSER_SECTION_MISSING = "CONFIG.SECTION_MISSING"; + +/** + * The `composer` section as `deploy` reads it. Composer's own validator + * decides everything: when it reports the section missing, the value is + * undefined and the deploy is a single-app deploy. Every other answer, + * valid or not, is Composer's and is passed on unchanged. + */ +export const deployConfigSection = defineConfigSection< + ComposerConfig | undefined +>({ + name: composerSection.name, + ...(composerSection.merge === undefined + ? {} + : { merge: composerSection.merge }), + validate: (raw, provenance) => { + const checked = composerSection.validate(raw, provenance); + const missing = + !checked.ok && + checked.diagnostics.length === 1 && + checked.diagnostics[0]?.code === COMPOSER_SECTION_MISSING; + return missing ? { ok: true, value: undefined, diagnostics: [] } : checked; + }, +}); + +function errorFromDiagnostic( + diagnostic: Diagnostic, + why = diagnostic.why, +): CliStructuredError { + return new CliStructuredError(diagnostic.code, diagnostic.summary, { + why, + nextActions: diagnostic.nextActions, + where: diagnostic.where, + meta: diagnostic.meta, + }); +} + +/** The file names Composer read its configuration from before the `composer` section replaced them. */ +const RETIRED_COMPOSER_CONFIG_FILES = ["ts", "mts", "mjs", "js"].map( + (extension) => `prisma-composer.config.${extension}`, +); + +/** + * Why a repository with no `composer` section is still a Composer app: + * `--entry` names a file that exists, or a prisma-composer.config.* file + * is present. Undefined when neither holds. + */ +export function composerAppSign(input: { + readonly entry: string | undefined; + readonly cwd: string; + readonly configFiles: readonly LoadedConfigFile[]; +}): string | undefined { + if ( + input.entry !== undefined && + existsSync(path.resolve(input.cwd, input.entry)) + ) { + return `--entry names ${input.entry}, which exists, so this is a Prisma Composer app.`; + } + const directories = [ + input.cwd, + ...input.configFiles.map((file) => path.dirname(file.path)), + ]; + const retired = directories + .flatMap((directory) => + RETIRED_COMPOSER_CONFIG_FILES.map((name) => path.join(directory, name)), + ) + .find((file) => existsSync(file)); + return retired === undefined + ? undefined + : `${retired} exists, so this is a Prisma Composer app.`; +} + +/** Composer's own "section missing" error, for a Composer app that has no `composer` section. */ +export function composerSectionMissingError(sign: string): CliStructuredError { + const checked = composerSection.validate(undefined, { files: [], keys: {} }); + const diagnostic = checked.diagnostics[0]; + if (checked.ok || diagnostic === undefined) { + throw new Error( + "Composer's section validator accepted a missing `composer` section", + ); + } + return errorFromDiagnostic( + diagnostic, + diagnostic.why === undefined ? sign : `${sign} ${diagnostic.why}`, + ); +} + +/** + * The `app` section of prisma.config.ts: the App config of a single-app + * deploy. Every field is optional and replaces the Build setting the + * repository's own files would give. + */ +export const appConfigSection = defineConfigSection({ + name: "app", + schema: configSchema({ + "+": "reject", + "install?": "string > 0", + "build?": "string > 0 | null", + "start?": "string > 0", + "static?": "string > 0", + "port?": "1 <= number.integer <= 65535", + }), +}); + +/** The App config the loaded config files declare; empty when none declares an `app` section. */ +export function readAppConfig(files: readonly LoadedConfigFile[]): AppConfig { + const resolved = resolveSectionOverChain(appConfigSection, files); + if (!resolved.ok) { + const message = + resolved.cause instanceof Error + ? resolved.cause.message + : String(resolved.cause); + throw new CliStructuredError( + "CLI.CONFIG_SECTION_INVALID", + `The 'app' section of ${resolved.file} is invalid: reading it threw '${message.split("\n", 1)[0]?.trim()}'.`, + { where: { path: resolved.file } }, + ); + } + const checked = appConfigSection.validate( + resolved.value, + resolved.provenance, + ); + if (!checked.ok) { + const [first] = checked.diagnostics; + if (first === undefined) { + throw new Error("the 'app' section is invalid without a diagnostic"); + } + throw errorFromDiagnostic(first); + } + const { baseDir: _baseDir, ...config } = checked.value; + return config; +} diff --git a/packages/cli/src/commands/deploy/errors.ts b/packages/cli/src/commands/deploy/errors.ts new file mode 100644 index 000000000..c2af54da4 --- /dev/null +++ b/packages/cli/src/commands/deploy/errors.ts @@ -0,0 +1,136 @@ +import { CliStructuredError } from "@prisma/cli-engine/protocol"; +import type { BuildStep, StartReport } from "@prisma/compute-sdk/app"; +import { adviceAction, runCommandAction } from "../service/errors"; + +const APP_CONFIG_ADVICE = + "Or set the command in the app section of prisma.config.ts."; + +/** `--project` names the target of a single-app deploy only, so a Composer deploy refuses it instead of ignoring it. */ +export function projectFlagOnComposerDeployError(): CliStructuredError { + return new CliStructuredError( + "DEPLOY.APP_USAGE_ERROR", + "--project applies only to a single-app deploy", + { + why: "This repository has a `composer` section in prisma.config.ts, so this is a Prisma Composer deploy. A Composer app is deployed into the project named after the app.", + nextActions: [ + adviceAction( + "Remove --project. To deploy the app under another name, pass --name.", + ), + ], + }, + ); +} + +export function installFailedError(step: BuildStep): CliStructuredError { + return new CliStructuredError( + "DEPLOY.APP_INSTALL_FAILED", + `Install failed: ${step.command}`, + { + why: "The install command exited with an error. Its output is above.", + meta: { command: step.command, seconds: step.seconds }, + nextActions: [ + adviceAction( + `Run ${step.command} in this folder and fix what it reports. ${APP_CONFIG_ADVICE}`, + ), + ], + }, + ); +} + +export function buildFailedError(step: BuildStep): CliStructuredError { + return new CliStructuredError( + "DEPLOY.APP_BUILD_FAILED", + `Build failed: ${step.command}`, + { + why: "The build command exited with an error. Its output is above.", + meta: { command: step.command, seconds: step.seconds }, + nextActions: [ + adviceAction( + `Run ${step.command} in this folder and fix what it reports. ${APP_CONFIG_ADVICE}`, + ), + ], + }, + ); +} + +export function noStartError(message: string): CliStructuredError { + return new CliStructuredError("DEPLOY.APP_NO_START", message, { + why: "Nothing was uploaded. The app has no start script that runs it in production, the build wrote no server file or static site, and the folder holds no entry file.", + }); +} + +interface FailedStart { + readonly service: { readonly id: string; readonly name: string }; + readonly versionId: string; + readonly url: string; + readonly port: number; + readonly start: StartReport; + readonly startTimeoutSeconds: number; +} + +function startMeta(failed: FailedStart): Record { + return { + serviceId: failed.service.id, + versionId: failed.versionId, + url: failed.url, + port: failed.port, + start: failed.start, + }; +} + +function logsAction(failed: FailedStart) { + return runCommandAction( + "Read the version's logs", + `service logs ${failed.service.id} --version-id ${failed.versionId}`, + ); +} + +/** The app did not start listening on the routed port, so its version was not promoted. */ +export function startFailedError(failed: FailedStart): CliStructuredError { + const { start } = failed; + if (start.state === "exited") { + return new CliStructuredError( + "DEPLOY.APP_EXITED", + `App exited with code ${start.code}. Not promoted.`, + { + why: "The app stopped when it was started on Prisma Cloud. Its output is above. The version that serves traffic did not change.", + meta: startMeta(failed), + nextActions: [ + adviceAction( + "Fix the error in the app's output. A missing environment variable is set with project env add.", + ), + logsAction(failed), + ], + }, + ); + } + if (start.state === "silent") { + return new CliStructuredError( + "DEPLOY.APP_SILENT", + `App did not open a port within ${failed.startTimeoutSeconds}s. Not promoted.`, + { + why: "The app kept running on Prisma Cloud but did not listen on any port. The version that serves traffic did not change.", + meta: startMeta(failed), + nextActions: [ + adviceAction( + "Make the app listen on the port in the PORT environment variable.", + ), + logsAction(failed), + ], + }, + ); + } + return new CliStructuredError( + "DEPLOY.APP_PORT_MISMATCH", + `App listens on port ${start.port}, not ${failed.port}. Not promoted.`, + { + why: `Requests are sent to port ${failed.port}, and the app does not listen there. The version that serves traffic did not change.`, + meta: startMeta(failed), + nextActions: [ + adviceAction( + `Set port: ${start.port} in the app section of prisma.config.ts, or make the app listen on the port in the PORT environment variable.`, + ), + ], + }, + ); +} diff --git a/packages/cli/src/commands/deploy/presentation.ts b/packages/cli/src/commands/deploy/presentation.ts new file mode 100644 index 000000000..7e0b1f7cd --- /dev/null +++ b/packages/cli/src/commands/deploy/presentation.ts @@ -0,0 +1,169 @@ +import type { Presentations } from "@prisma/cli-engine"; +import { dataLine } from "@prisma/composer-cli/family"; +import type { + BuildSettings, + BuildStep, + DeployAttempt, + Source, + StartReport, +} from "@prisma/compute-sdk/app"; +import { runCommandAction } from "../service/errors"; + +/** What `deploy` returns for a single-app deploy. */ +export interface SingleAppDeployResult { + readonly app: string; + readonly workspace: { readonly id: string; readonly name: string }; + readonly project: { readonly id: string; readonly name: string }; + readonly branch: { readonly name: string; readonly production: boolean }; + readonly service: { + readonly id: string; + readonly name: string; + /** False when this deploy created the service. */ + readonly existing: boolean; + }; + readonly settings: BuildSettings; + readonly steps: readonly BuildStep[]; + readonly versionId: string; + readonly url: string; + readonly port: number; + readonly start: StartReport; + readonly promoted: boolean; + /** One entry for each version this deploy uploaded. */ + readonly attempts: readonly DeployAttempt[]; + readonly durationMs: number; +} + +const SOURCE_TEXT: Readonly> = { + config: "from prisma.config.ts", + "package.json": "from package.json", + lockfile: "from the lockfile", + "build output": "from build output", + "entry file": "from the entry file", + default: "", +}; + +type Row = readonly [label: string, value: string, source?: string]; + +/** The longest label: `Install` and `Project`. */ +const LABEL_WIDTH = 7; + +function table(rows: readonly Row[]): string[] { + const valueWidth = Math.max( + ...rows.filter(([, , source]) => source).map(([, value]) => value.length), + 0, + ); + return rows.map(([label, value, source]) => + ` ${label.padEnd(LABEL_WIDTH)} ${source ? `${value.padEnd(valueWidth)} ${source}` : value}`.trimEnd(), + ); +} + +/** The Start or Static folder row, or undefined while only the build output can decide it. */ +function startRow(settings: BuildSettings): Row | undefined { + if (settings.start) { + return ["Start", settings.start.value, SOURCE_TEXT[settings.start.from]]; + } + if (settings.static) { + return ["Static", settings.static.value, SOURCE_TEXT[settings.static.from]]; + } + return undefined; +} + +/** What is deployed and where, then the Build settings known before the build runs. */ +export function settingsCard(input: { + readonly app: string; + readonly project: string; + readonly branch: { readonly name: string; readonly production: boolean }; + readonly settings: BuildSettings; +}): string { + const { settings } = input; + const start = startRow(settings); + const target = table([ + ["App", input.app], + ["Project", input.project], + [ + "Branch", + input.branch.production + ? `${input.branch.name} (production)` + : input.branch.name, + ], + ]); + const build = table([ + [ + "Install", + settings.install.value || "(nothing to install)", + settings.install.value ? SOURCE_TEXT[settings.install.from] : "", + ], + [ + "Build", + settings.build.value ?? "(no build step)", + settings.build.value ? SOURCE_TEXT[settings.build.from] : "", + ], + ...(start === undefined ? [] : [start]), + settings.port + ? ["Port", String(settings.port.value), SOURCE_TEXT[settings.port.from]] + : ["Port", "$PORT"], + ]); + return ["", ...target, "", ...build, ""].join("\n"); +} + +/** The Start or Static folder row on its own, for a start that only the build output decided. */ +export function startLine(settings: BuildSettings): string | undefined { + const row = startRow(settings); + return row === undefined ? undefined : table([row]).join("\n"); +} + +function seconds(value: number): string { + return `${value}s`; +} + +export function buildStepText(step: BuildStep): string { + const name = step.name === "install" ? "Install" : "Build"; + const done = step.name === "install" ? "Installed" : "Built"; + return `${step.ok ? done : `${name} failed`} ${seconds(step.seconds)}`; +} + +export function uploadedStepText(attemptSeconds: number): string { + return `Uploaded ${seconds(attemptSeconds)}`; +} + +export function startStepText( + start: StartReport, + startTimeoutSeconds: number, +): string { + switch (start.state) { + case "listening": + return `Started listening on port ${start.port}`; + case "exited": + return `Start failed exited with code ${start.code}`; + case "silent": + return `Start failed no port opened within ${seconds(startTimeoutSeconds)}`; + } +} + +export function portChangedText(from: number, to: number): string { + return `⚠ App listens on port ${to}, not ${from}. Deploying again with port ${to}.`; +} + +export function singleAppPresentations( + result: SingleAppDeployResult, +): Presentations { + return { + human: () => [{ kind: "drawing", lines: ["", result.url] }], + // The same fields as a Composer deploy's lines: address, kind, id, URL. + stdout: () => [ + dataLine([ + result.service.name, + "compute-service", + result.service.id, + result.url, + ]), + ], + json: () => result, + next: () => [ + runCommandAction( + "Read the app's logs", + `service logs ${result.service.id}`, + ), + ], + }; +} diff --git a/packages/cli/src/commands/deploy/single-app.ts b/packages/cli/src/commands/deploy/single-app.ts new file mode 100644 index 000000000..e4b1cfb9e --- /dev/null +++ b/packages/cli/src/commands/deploy/single-app.ts @@ -0,0 +1,428 @@ +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { + type CommandContext, + type CredentialManager, + credentialsRequiredError, + type PresentedResult, +} from "@prisma/cli-engine"; +import { + type CliStructuredError, + notOk, + ok, + type Result, +} from "@prisma/cli-engine/protocol"; +import type { + AppArtifact, + AppConfig, + BuildAppResult, + BuildSettings, + DeployAppEvent, + DeployAppResult, +} from "@prisma/compute-sdk/app"; +import { getApiBaseUrl } from "../../auth/client"; +import type { AppRecord } from "../../lib/app/app-provider"; +import { getCliVersion } from "../../lib/version"; +import { deployFailedError, runCommandAction } from "../service/errors"; +import { + listServices, + type ResolvedServiceProjectContext, + resolveServiceProjectContext, + serviceProvider, +} from "../service/target"; +import { readAppConfig } from "./config"; +import { + buildFailedError, + installFailedError, + noStartError, + startFailedError, +} from "./errors"; +import { + buildStepText, + portChangedText, + type SingleAppDeployResult, + settingsCard, + singleAppPresentations, + startLine, + startStepText, + uploadedStepText, +} from "./presentation"; + +/** The environment that means the project's default Branch, as in a Composer deploy. */ +const PRODUCTION_ENVIRONMENT = "production"; + +/** How long the app has to open a port after its first start. */ +const START_TIMEOUT_SECONDS = 60; + +/** A token read for the deployment's log must stay valid while the upload and the start run. */ +const TOKEN_MINIMUM_VALIDITY_MS = 5 * 60_000; + +/** How many lines of a failed command's output are shown. */ +const OUTPUT_TAIL_LINES = 40; + +const NOT_NAME_CHARACTERS = /[^a-zA-Z0-9._-]+/g; +const NOT_NAME_EDGES = /^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$/g; +const PACKAGE_SCOPE = /^@[^/]*\//; + +export type SingleAppContext = CommandContext & { + readonly credentialManager: CredentialManager; +}; + +export interface SingleAppInput { + /** `--project`: the project id or name, when the directory's link is not the target. */ + readonly project: string | undefined; + /** `--name`: the service name, in place of the one taken from package.json. */ + readonly name: string | undefined; + /** `--environment`: `production`, or the name of a Branch. */ + readonly environment: string | undefined; +} + +interface Branch { + readonly name: string; + readonly production: boolean; +} + +/** A name with only letters, digits, dots, dashes and underscores, starting and ending with a letter or digit. */ +function toServiceName(text: string): string { + return text.replace(NOT_NAME_CHARACTERS, "-").replace(NOT_NAME_EDGES, ""); +} + +function packageName(dir: string): string { + try { + const manifest: unknown = JSON.parse( + readFileSync(path.join(dir, "package.json"), "utf8"), + ); + return typeof manifest === "object" && + manifest !== null && + "name" in manifest && + typeof manifest.name === "string" + ? manifest.name + : ""; + } catch { + return ""; + } +} + +/** The service name: `name` from package.json without its scope, else the folder name. */ +export function inferServiceName(dir: string): string { + return ( + toServiceName(packageName(dir).replace(PACKAGE_SCOPE, "")) || + toServiceName(path.basename(dir)) || + "app" + ); +} + +/** The request headers the Management API records in its deploy analytics. */ +export function deploySourceHeaders( + env: Readonly>, +): Record { + return { + "x-prisma-deploy-source": + env.GITHUB_ACTIONS === "true" ? "github-action" : "cli", + "x-prisma-client-name": "prisma-cli", + "x-prisma-client-version": getCliVersion(), + }; +} + +function reportOutputTail( + ctx: SingleAppContext, + source: string, + output: string, +): void { + for (const line of output.trimEnd().split("\n").slice(-OUTPUT_TAIL_LINES)) { + ctx.report({ kind: "output", source, channel: "diagnostic", line }); + } +} + +function buildFailure( + ctx: SingleAppContext, + built: BuildAppResult, + output: string, +): CliStructuredError { + const failedStep = built.steps.find((step) => !step.ok); + if (failedStep === undefined) { + return noStartError(built.failure?.message ?? "No start command."); + } + reportOutputTail(ctx, failedStep.name, output); + return failedStep.name === "install" + ? installFailedError(failedStep) + : buildFailedError(failedStep); +} + +/** Prints the Start row when only the build output could decide it. */ +function reportStartFromBuild( + ctx: SingleAppContext, + planned: BuildSettings, + settings: BuildSettings, +): void { + const line = + planned.start === null && planned.static === null + ? startLine(settings) + : undefined; + if (line !== undefined) { + ctx.report({ kind: "message", severity: "info", text: line }); + } +} + +/** Prints the Build settings, runs install and build, and prints each step. */ +async function build( + ctx: SingleAppContext, + config: AppConfig, + card: { + readonly app: string; + readonly project: { readonly id: string; readonly name: string }; + readonly branch: Branch; + }, +): Promise< + Result +> { + const { buildApp, resolveBuildSettings } = await import( + "@prisma/compute-sdk/app" + ); + const read = (file: string) => + existsSync(path.join(ctx.cwd, file)) + ? readFileSync(path.join(ctx.cwd, file), "utf8") + : null; + const planned = await resolveBuildSettings(read, config); + ctx.report({ + kind: "message", + severity: "info", + text: settingsCard({ + app: card.app, + project: card.project.name, + branch: card.branch, + settings: planned, + }), + data: { ...card, settings: planned }, + }); + for (const note of planned.notes) { + ctx.report({ kind: "message", severity: "warn", text: `⚠ ${note}` }); + } + + let output = ""; + const built = await buildApp({ + dir: ctx.cwd, + config, + log: (text) => { + output += text; + ctx.report({ kind: "message", severity: "verbose", text }); + }, + signal: ctx.signal, + }); + for (const step of built.steps) { + ctx.report({ + kind: "step-finished", + step: buildStepText(step), + id: `deploy.${step.name}`, + outcome: step.ok ? "ok" : "failed", + data: step, + }); + } + const { artifact } = built; + if (!built.ok || artifact === undefined) { + return notOk(buildFailure(ctx, built, output)); + } + + reportStartFromBuild(ctx, planned, built.settings); + return ok({ ...built, artifact }); +} + +/** + * The service to deploy to: the one on the Branch with the app's name, or + * a new one. It is looked up first because creating a service fails when + * the name is taken. + */ +async function findOrCreateService( + ctx: SingleAppContext, + target: ResolvedServiceProjectContext, + app: string, +): Promise<{ service: AppRecord; existing: boolean }> { + const provider = serviceProvider(ctx); + const services = + target.branch.id === null + ? [] + : await listServices( + ctx, + provider, + target.project.id, + target.branch.name, + ); + const existing = services.find((service) => service.name === app); + if (existing !== undefined) { + return { service: existing, existing: true }; + } + + return provider + .createApp({ + projectId: target.project.id, + branchName: target.branch.name, + name: app, + signal: ctx.signal, + }) + .catch((error) => { + throw deployFailedError("Failed to create service", error, [ + runCommandAction("List services", "service list"), + ]); + }); +} + +function reportDeployEvent(ctx: SingleAppContext, event: DeployAppEvent): void { + if (event.type === "started") { + ctx.report({ + kind: "step-finished", + step: uploadedStepText(event.seconds), + id: `deploy.upload.${event.deploymentId}`, + outcome: "ok", + data: event, + }); + } + if (event.type === "port-changed") { + ctx.report({ + kind: "message", + severity: "warn", + text: portChangedText(event.from, event.to), + data: event, + }); + } +} + +/** Uploads the Artifact, waits for the app's first start, and promotes the version when the app listens. */ +async function upload( + ctx: SingleAppContext, + service: AppRecord, + artifact: AppArtifact, + settings: BuildSettings, +): Promise> { + const { ComputeClient } = await import("@prisma/compute-sdk"); + const { deployApp } = await import("@prisma/compute-sdk/app"); + const token = await ctx.credentialManager.activeAccessToken({ + minimumValidityMs: TOKEN_MINIMUM_VALIDITY_MS, + now: new Date(), + signal: ctx.signal, + }); + if (token === null) { + return notOk(credentialsRequiredError("session-ended")); + } + + const deployed = await deployApp({ + artifact, + client: new ComputeClient(ctx.api), + logs: { baseUrl: getApiBaseUrl(ctx.env), token }, + target: { appId: service.id }, + ...(settings.port ? { port: settings.port.value } : {}), + startTimeoutSeconds: START_TIMEOUT_SECONDS, + onEvent: (event) => reportDeployEvent(ctx, event), + signal: ctx.signal, + }); + if (deployed.isErr()) { + return notOk( + deployFailedError("Failed to deploy the app", deployed.error, [ + runCommandAction( + "List the service's versions", + `service version list ${service.id}`, + ), + ]), + ); + } + + const outcome = deployed.value; + ctx.report({ + kind: "step-finished", + step: startStepText(outcome.start, START_TIMEOUT_SECONDS), + id: "deploy.start", + outcome: outcome.ok ? "ok" : "failed", + data: outcome.start, + }); + if (outcome.ok) { + ctx.report({ + kind: "step-finished", + step: "Promoted", + id: "deploy.promote", + outcome: "ok", + }); + return ok(outcome); + } + + if (outcome.start.state !== "listening") { + reportOutputTail(ctx, "app", outcome.start.output); + } + return notOk( + startFailedError({ + service, + versionId: outcome.deploymentId, + url: outcome.url, + port: outcome.port, + start: outcome.start, + startTimeoutSeconds: START_TIMEOUT_SECONDS, + }), + ); +} + +/** + * Deploys the app in the current folder from its own install, build and + * start commands: no Composer config and no framework rules. + */ +export async function deploySingleApp( + input: SingleAppInput, + ctx: SingleAppContext, +): Promise, CliStructuredError>> { + const startedAt = Date.now(); + const headers = deploySourceHeaders(ctx.env); + ctx.api.use({ + onRequest: ({ request }) => { + for (const [name, value] of Object.entries(headers)) { + request.headers.set(name, value); + } + return request; + }, + }); + + const config = readAppConfig(ctx.configFiles); + const app = input.name?.trim() || inferServiceName(ctx.cwd); + const environment = input.environment?.trim() || PRODUCTION_ENVIRONMENT; + const production = environment === PRODUCTION_ENVIRONMENT; + const target = await resolveServiceProjectContext(ctx, input.project, { + commandName: "deploy", + ...(production ? {} : { branchName: environment }), + }); + const project = { id: target.project.id, name: target.project.name }; + const branch: Branch = { + name: target.branch.name, + production: production || target.branch.isDefault, + }; + + const built = await build(ctx, config, { app, project, branch }); + if (!built.ok) { + return built; + } + + const { service, existing } = await findOrCreateService(ctx, target, app); + const uploaded = await upload( + ctx, + service, + built.value.artifact, + built.value.settings, + ); + if (!uploaded.ok) { + return uploaded; + } + + const outcome = uploaded.value; + const result: SingleAppDeployResult = { + app, + workspace: target.workspace, + project, + branch, + service: { id: service.id, name: service.name, existing }, + settings: built.value.settings, + steps: built.value.steps, + versionId: outcome.deploymentId, + url: outcome.url, + port: outcome.port, + start: outcome.start, + promoted: outcome.promoted, + attempts: outcome.attempts, + durationMs: Date.now() - startedAt, + }; + return ok(ctx.present({ data: result }, singleAppPresentations(result))); +} diff --git a/packages/cli/tests/deploy.test.ts b/packages/cli/tests/deploy.test.ts new file mode 100644 index 000000000..a14468f2c --- /dev/null +++ b/packages/cli/tests/deploy.test.ts @@ -0,0 +1,786 @@ +import { mkdir, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { + defineCommandFamily, + type ManagementApiClient, +} from "@prisma/cli-engine"; +import { createTestCli, mintTestJwt } from "@prisma/cli-engine/testing"; +import { defineConfig as composer } from "@prisma/composer/config"; +import { nodeBuild } from "@prisma/composer/node/control"; +import { createComposerFamily } from "@prisma/composer-cli/family"; +import { createOperationsDouble } from "@prisma/composer-cli/testing"; +import type { + BuildAppResult, + BuildSettings, + DeployAppOptions, + DeployAppResult, +} from "@prisma/compute-sdk/app"; +import { Result } from "better-result"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { cliGroups, platformCommandFamily } from "../src/cli"; +import { createDeployCommand } from "../src/commands/deploy/command"; +import { deployConfigSection } from "../src/commands/deploy/config"; +import { getCliVersion } from "../src/lib/version"; +import { + fakeManagementClient, + makeTempCwd, + PROJECT, + page, + type Routes, + readFlowRoutes, + WORKSPACE, +} from "./service-testkit"; + +const sdk = vi.hoisted(() => ({ + buildApp: vi.fn(), + deployApp: vi.fn(), +})); + +vi.mock("@prisma/compute-sdk/app", async (original) => ({ + ...(await original()), + buildApp: sdk.buildApp, + deployApp: sdk.deployApp, +})); + +const build = nodeBuild(); +const COMPOSER_SECTION = composer({ + extensions: [build], + state: { + extension: build.id, + create: () => { + throw new Error("no command in these tests reaches the state store"); + }, + }, +}); + +const SETTINGS: BuildSettings = { + packageManager: "npm", + node: null, + install: { value: "npm ci", from: "lockfile" }, + build: { value: "npm run build", from: "package.json" }, + start: { value: "node dist/index.js", from: "package.json" }, + static: null, + port: null, + notes: [], +}; + +const BUILT: BuildAppResult = { + ok: true, + settings: SETTINGS, + steps: [ + { name: "install", command: "npm ci", seconds: 4, ok: true }, + { name: "build", command: "npm run build", seconds: 3, ok: true }, + ], + artifact: { dir: "/app", entrypoint: ".prisma/launcher.mjs" }, +}; + +const DEPLOYED: DeployAppResult = { + ok: true, + appId: "svc_new", + deploymentId: "cpv_1", + url: "https://web.prisma.build", + port: 8080, + start: { state: "listening", port: 8080 }, + promoted: true, + attempts: [ + { deploymentId: "cpv_1", port: 8080, seconds: 28, start: "listening" }, + ], +}; + +const CREATED = { + id: "svc_new", + name: "web", + region: { id: "eu-central-1" }, + branchId: "br_1", + latestDeploymentId: null, + appEndpointDomain: "web.prisma.build", +}; + +interface Harness { + readonly cwd: string; + readonly created: unknown[]; + readonly asked: unknown[]; + readonly headers: () => Record; + readonly composerCalls: ReturnType["calls"]; + readonly run: ( + argv: readonly string[], + options?: { tty?: boolean; env?: Record }, + ) => ReturnType["run"]>; +} + +async function harness( + options: { config?: Record; routes?: Routes } = {}, +): Promise { + const cwd = await makeTempCwd("deploy-"); + await writeFile( + path.join(cwd, "package.json"), + JSON.stringify({ name: "@acme/web", scripts: { start: "node server.js" } }), + ); + const created: unknown[] = []; + const asked: unknown[] = []; + const client = fakeManagementClient( + readFlowRoutes({ + "GET /v1/apps": (init) => { + asked.push(init.params?.query?.branchGitName); + return { data: page([]) }; + }, + "POST /v1/apps": (init) => { + created.push(init.body); + return { data: { data: CREATED } }; + }, + ...options.routes, + }), + ); + type Middleware = { onRequest: (input: { request: Request }) => Request }; + const middlewares: Middleware[] = []; + Object.assign(client, { + use: (middleware: Middleware) => middlewares.push(middleware), + }); + + const double = createOperationsDouble(); + const deploy = createDeployCommand( + createComposerFamily({ operations: double.operations }).commands.deploy, + ); + const cli = createTestCli({ + commandFamilies: [ + platformCommandFamily, + defineCommandFamily({ + configSection: deployConfigSection, + commands: { deploy }, + }), + ], + commands: { deploy }, + groups: { deploy: cliGroups.deploy }, + config: options.config, + sessions: [ + { + workspaceId: WORKSPACE.id, + workspaceName: WORKSPACE.name, + credential: { + token: mintTestJwt({ sub: "usr_1", workspace_id: WORKSPACE.id }), + refreshToken: undefined, + expiresAt: undefined, + }, + }, + ], + selectedWorkspaceId: WORKSPACE.id, + managementApi: { client: client as ManagementApiClient }, + now: () => new Date(0), + }); + + return { + cwd, + created, + asked, + composerCalls: double.calls, + headers: () => { + const request = new Request("https://api.prisma.io/v1/apps"); + for (const middleware of middlewares) { + middleware.onRequest({ request }); + } + return Object.fromEntries(request.headers.entries()); + }, + run: (argv, run = {}) => + cli.run(argv, { + cwd, + env: { PRISMA_CLI_STATE_DIR: path.join(cwd, ".state"), ...run.env }, + ...(run.tty ? { isTty: { stdout: true } } : {}), + }), + }; +} + +type Run = Awaited>; + +/** The envelope of a --json run: the terminal result frame. */ +function envelopeOf(run: Run) { + const frame = run.json.at(-1); + if (frame?.kind !== "result") { + throw new Error("the run wrote no result frame"); + } + return frame.envelope; +} + +function deployOptions(): DeployAppOptions { + return sdk.deployApp.mock.calls[0]?.[0] as DeployAppOptions; +} + +beforeEach(() => { + sdk.buildApp.mockReset().mockResolvedValue(BUILT); + sdk.deployApp.mockReset().mockResolvedValue(Result.ok(DEPLOYED)); +}); + +describe("deploy: which path runs", () => { + it("runs Composer's deploy when a config file declares a composer section", async () => { + const h = await harness({ config: { composer: COMPOSER_SECTION } }); + + const result = await h.run(["deploy", "--environment", "staging"]); + + expect(result.exitCode).toBe(0); + expect(h.composerCalls.deploy).toHaveLength(1); + expect(h.composerCalls.deploy[0]?.environment).toBe("staging"); + expect(h.composerCalls.deploy[0]?.cwd).toBe(h.cwd); + expect(h.composerCalls.deps.deploy[0]?.credentials?.workspaceId).toBe( + WORKSPACE.id, + ); + expect(sdk.buildApp).not.toHaveBeenCalled(); + }); + + it("refuses --project on a Composer deploy", async () => { + const h = await harness({ config: { composer: COMPOSER_SECTION } }); + + const result = await h.run(["deploy", "--project", PROJECT.id, "--json"]); + + expect(envelopeOf(result)).toMatchObject({ + ok: false, + error: { code: "DEPLOY.APP_USAGE_ERROR" }, + }); + expect(h.composerCalls.deploy).toHaveLength(0); + }); + + it("reports an invalid composer section as Composer does, and deploys nothing", async () => { + const h = await harness({ config: { composer: { extensions: "no" } } }); + + const result = await h.run(["deploy", "--json"]); + + expect(result.exitCode).not.toBe(0); + expect(envelopeOf(result)).toMatchObject({ + ok: false, + error: { code: "CLI.CONFIG_SECTION_INVALID" }, + }); + expect(h.composerCalls.deploy).toHaveLength(0); + expect(sdk.buildApp).not.toHaveBeenCalled(); + }); + + it("runs a single-app deploy when no config file declares a composer section", async () => { + const h = await harness(); + + const result = await h.run(["deploy", "--project", PROJECT.id]); + + expect(result.exitCode).toBe(0); + expect(h.composerCalls.deploy).toHaveLength(0); + expect(sdk.buildApp).toHaveBeenCalledTimes(1); + }); + + it("ignores an --entry that names no file, which the deploy action always passes", async () => { + const h = await harness(); + + const result = await h.run([ + "deploy", + "--entry", + "module.ts", + "--project", + PROJECT.id, + ]); + + expect(result.exitCode).toBe(0); + expect(sdk.deployApp).toHaveBeenCalledTimes(1); + }); + + it("fails with Composer's missing-section error when --entry names a file that exists", async () => { + const h = await harness(); + await writeFile(path.join(h.cwd, "module.ts"), "export default {};\n"); + + const result = await h.run(["deploy", "--entry", "module.ts", "--json"]); + + expect(envelopeOf(result)).toMatchObject({ + ok: false, + error: { code: "CONFIG.SECTION_MISSING" }, + }); + expect(sdk.buildApp).not.toHaveBeenCalled(); + }); + + it("fails with Composer's missing-section error when a prisma-composer.config file exists", async () => { + const h = await harness(); + await writeFile(path.join(h.cwd, "prisma-composer.config.ts"), ""); + + const result = await h.run(["deploy", "--json"]); + + expect(envelopeOf(result)).toMatchObject({ + ok: false, + error: { code: "CONFIG.SECTION_MISSING" }, + }); + expect(sdk.buildApp).not.toHaveBeenCalled(); + }); +}); + +describe("deploy: the single-app target", () => { + it("creates a service named after package.json, without the scope, on the default branch", async () => { + const h = await harness(); + + await h.run(["deploy", "--project", PROJECT.id]); + + expect(h.asked).toEqual(["main"]); + expect(h.created).toEqual([ + { projectId: "proj_1", branchId: "br_1", displayName: "web" }, + ]); + expect(deployOptions().target).toEqual({ appId: "svc_new" }); + }); + + it("deploys to the service that already has the name, and creates none", async () => { + const h = await harness({ + routes: { + "GET /v1/apps": () => ({ + data: page([{ ...CREATED, id: "svc_old" }]), + }), + }, + }); + + const result = await h.run(["deploy", "--project", PROJECT.id, "--json"]); + + expect(h.created).toEqual([]); + expect(deployOptions().target).toEqual({ appId: "svc_old" }); + expect(envelopeOf(result)).toMatchObject({ + result: { service: { id: "svc_old", name: "web", existing: true } }, + }); + }); + + it("names the service with --name", async () => { + const h = await harness(); + + await h.run(["deploy", "--project", PROJECT.id, "--name", "api"]); + + expect(h.created).toMatchObject([{ displayName: "api" }]); + }); + + it("names the service after the folder when package.json has no name", async () => { + const h = await harness(); + await writeFile(path.join(h.cwd, "package.json"), "{}"); + + await h.run(["deploy", "--project", PROJECT.id]); + + expect(h.created).toMatchObject([{ displayName: path.basename(h.cwd) }]); + }); + + it("deploys to the branch --environment names, and creates it when it is missing", async () => { + const branches: unknown[] = []; + const h = await harness({ + routes: { + "GET /v1/projects/{projectId}/branches": (init) => + init.params?.query?.gitName === "pr-12" + ? { data: page(branches) } + : { + data: page([ + { + id: "br_1", + gitName: "main", + isDefault: true, + role: "production", + }, + ]), + }, + "POST /v1/projects/{projectId}/branches": (init) => { + const branch = { + id: "br_pr", + gitName: (init.body as { gitName: string }).gitName, + isDefault: false, + role: "preview", + }; + branches.push(branch); + return { data: { data: branch } }; + }, + }, + }); + + const result = await h.run([ + "deploy", + "--project", + PROJECT.id, + "--environment", + "pr-12", + "--json", + ]); + + expect(h.created).toEqual([ + { projectId: "proj_1", branchId: "br_pr", displayName: "web" }, + ]); + expect(envelopeOf(result)).toMatchObject({ + result: { branch: { name: "pr-12", production: false } }, + }); + }); + + it("uses the project the directory is linked to", async () => { + const h = await harness(); + await mkdir(path.join(h.cwd, ".prisma")); + await writeFile( + path.join(h.cwd, ".prisma", "local.json"), + JSON.stringify({ workspaceId: WORKSPACE.id, projectId: PROJECT.id }), + ); + + const result = await h.run(["deploy", "--json"]); + + expect(envelopeOf(result)).toMatchObject({ + ok: true, + result: { project: { id: "proj_1", name: "acme-app" } }, + }); + }); + + it("fails before building when there is no linked project and no --project", async () => { + const h = await harness(); + + const result = await h.run(["deploy", "--json"]); + + expect(envelopeOf(result).ok).toBe(false); + expect(sdk.buildApp).not.toHaveBeenCalled(); + expect(h.created).toEqual([]); + }); + + it("sends the deploy-source and client headers on Management API requests", async () => { + const h = await harness(); + + await h.run(["deploy", "--project", PROJECT.id]); + expect(h.headers()).toMatchObject({ + "x-prisma-deploy-source": "cli", + "x-prisma-client-name": "prisma-cli", + "x-prisma-client-version": getCliVersion(), + }); + }); + + it("reports the source as github-action in GitHub Actions", async () => { + const h = await harness(); + + await h.run(["deploy", "--project", PROJECT.id], { + env: { GITHUB_ACTIONS: "true" }, + }); + + expect(h.headers()["x-prisma-deploy-source"]).toBe("github-action"); + }); +}); + +describe("deploy: the App config", () => { + it("passes the app section to the build, and the stated port to the deploy", async () => { + const h = await harness({ + config: { app: { build: null, start: "bun server.ts", port: 3000 } }, + }); + sdk.buildApp.mockResolvedValue({ + ...BUILT, + settings: { ...SETTINGS, port: { value: 3000, from: "config" } }, + }); + + await h.run(["deploy", "--project", PROJECT.id]); + + expect(sdk.buildApp.mock.calls[0]?.[0]).toMatchObject({ + dir: h.cwd, + config: { build: null, start: "bun server.ts", port: 3000 }, + }); + expect(deployOptions().port).toBe(3000); + }); + + it("passes no port when the App config states none", async () => { + const h = await harness(); + + await h.run(["deploy", "--project", PROJECT.id]); + + expect(deployOptions()).not.toHaveProperty("port"); + expect(deployOptions()).not.toHaveProperty("envVars"); + }); + + it.each([ + [{ port: "3000" }, "port"], + [{ port: 70000 }, "port"], + [{ start: "" }, "start"], + [{ strat: "node server.js" }, "strat"], + ])("refuses the app section %j", async (app, field) => { + const h = await harness({ config: { app } }); + + const result = await h.run(["deploy", "--project", PROJECT.id, "--json"]); + + expect(envelopeOf(result)).toMatchObject({ + ok: false, + error: { + code: "CLI.CONFIG_FIELD_INVALID", + meta: { section: "app", field }, + }, + }); + expect(sdk.buildApp).not.toHaveBeenCalled(); + }); +}); + +describe("deploy: single-app output", () => { + it("prints the target, the Build settings, each step and the URL", async () => { + const h = await harness(); + await writeFile(path.join(h.cwd, "package-lock.json"), "{}"); + await writeFile( + path.join(h.cwd, "package.json"), + JSON.stringify({ + name: "web", + scripts: { build: "tsc", start: "node dist/index.js" }, + dependencies: { koa: "3" }, + }), + ); + sdk.deployApp.mockImplementation(async (options: DeployAppOptions) => { + options.onEvent?.({ + type: "started", + deploymentId: "cpv_1", + port: 8080, + seconds: 28, + }); + options.onEvent?.({ type: "promoted", url: DEPLOYED.url }); + return Result.ok(DEPLOYED); + }); + + const result = await h.run(["deploy", "--project", PROJECT.id], { + tty: true, + }); + + expect(result.exitCode).toBe(0); + expect(result.stderr).toBe( + [ + "", + " App web", + " Project acme-app", + " Branch main (production)", + "", + " Install npm ci from the lockfile", + " Build npm run build from package.json", + " Start node dist/index.js from package.json", + " Port $PORT", + "", + "✔ Installed 4s", + "✔ Built 3s", + "✔ Uploaded 28s", + "✔ Started listening on port 8080", + "✔ Promoted", + "", + "https://web.prisma.build", + "", + "→ Read the app's logs: prisma service logs svc_new", + "", + ].join("\n"), + ); + }); + + it("writes one data line to stdout: name, kind, service id and URL", async () => { + const h = await harness(); + + const result = await h.run(["deploy", "--project", PROJECT.id]); + + expect(result.stdout).toBe( + "web\tcompute-service\tsvc_new\thttps://web.prisma.build\n", + ); + }); + + it("prints the note for a start script that runs a development server, and the start the build decided", async () => { + const h = await harness(); + await writeFile( + path.join(h.cwd, "package.json"), + JSON.stringify({ name: "docs", scripts: { start: "docusaurus start" } }), + ); + sdk.buildApp.mockResolvedValue({ + ...BUILT, + steps: [], + settings: { + ...SETTINGS, + start: null, + static: { value: "build", from: "build output" }, + }, + }); + + const result = await h.run(["deploy", "--project", PROJECT.id], { + tty: true, + }); + + expect(result.stderr).toContain( + "⚠ The start script runs a development server (docusaurus start). It is not used.", + ); + expect(result.stderr).not.toContain(" Start "); + expect(result.stderr).toContain(" Static build from build output\n"); + }); + + it("says when the app listens on another port and the deploy runs again", async () => { + const h = await harness(); + sdk.deployApp.mockImplementation(async (options: DeployAppOptions) => { + options.onEvent?.({ type: "port-changed", from: 8080, to: 4123 }); + return Result.ok({ + ...DEPLOYED, + port: 4123, + start: { state: "listening", port: 4123 }, + }); + }); + + const result = await h.run(["deploy", "--project", PROJECT.id], { + tty: true, + }); + + expect(result.stderr).toContain( + "⚠ App listens on port 4123, not 8080. Deploying again with port 4123.\n", + ); + expect(result.stderr).toContain("✔ Started listening on port 4123\n"); + }); + + it("returns the result in --json mode", async () => { + const h = await harness(); + + const result = await h.run(["deploy", "--project", PROJECT.id, "--json"]); + + expect(envelopeOf(result)).toMatchObject({ + ok: true, + commandId: "deploy", + result: { + app: "web", + project: { id: "proj_1", name: "acme-app" }, + branch: { name: "main", production: true }, + service: { id: "svc_new", name: "web", existing: false }, + settings: SETTINGS, + versionId: "cpv_1", + url: "https://web.prisma.build", + port: 8080, + start: { state: "listening", port: 8080 }, + promoted: true, + }, + }); + }); +}); + +describe("deploy: single-app failures", () => { + it("fails with no start command before anything is created or uploaded", async () => { + const h = await harness(); + sdk.buildApp.mockResolvedValue({ + ok: false, + settings: { ...SETTINGS, start: null }, + steps: BUILT.steps, + failure: { + code: "no_start", + message: + "No start command. Add a start script to package.json, or set start or static in prisma.config.ts.", + }, + }); + + const result = await h.run(["deploy", "--project", PROJECT.id], { + tty: true, + }); + + expect(result.exitCode).not.toBe(0); + expect(result.stderr).toContain( + "✘ [DEPLOY.APP_NO_START] No start command. Add a start script to package.json, or set start or static in prisma.config.ts.\n", + ); + expect(h.created).toEqual([]); + expect(sdk.deployApp).not.toHaveBeenCalled(); + }); + + it.each([ + ["install", "DEPLOY.APP_INSTALL_FAILED", "✘ Install failed 2s"], + ["build", "DEPLOY.APP_BUILD_FAILED", "✘ Build failed 2s"], + ] as const)("shows the failed %s step and the end of its output", async (name, code, line) => { + const h = await harness(); + sdk.buildApp.mockImplementation( + async (options: { log?: (text: string) => void }) => { + options.log?.("\n$ the command\n"); + options.log?.("line one\nerror: it broke\n"); + return { + ok: false, + settings: SETTINGS, + steps: [{ name, command: "the command", seconds: 2, ok: false }], + failure: { code: `${name}_failed`, message: "failed" }, + }; + }, + ); + + const result = await h.run(["deploy", "--project", PROJECT.id], { + tty: true, + }); + + expect(result.exitCode).not.toBe(0); + expect(result.stderr).toContain(`${line}\n`); + expect(result.stderr).toContain("line one\nerror: it broke\n"); + expect(result.stderr).toContain(`✘ [${code}]`); + expect(sdk.deployApp).not.toHaveBeenCalled(); + }); + + it("fails without promoting when the app exits at start, and shows the app's output", async () => { + const h = await harness(); + sdk.deployApp.mockResolvedValue( + Result.ok({ + ...DEPLOYED, + ok: false, + promoted: false, + url: "https://cpv-1.prisma.build", + start: { + state: "exited", + code: 1, + output: "Error: DATABASE_URL is not set", + }, + }), + ); + + const human = await h.run(["deploy", "--project", PROJECT.id], { + tty: true, + }); + const json = await h.run(["deploy", "--project", PROJECT.id, "--json"]); + + expect(human.exitCode).not.toBe(0); + expect(human.stderr).toContain("✘ Start failed exited with code 1\n"); + expect(human.stderr).toContain("Error: DATABASE_URL is not set\n"); + expect(human.stderr).toContain( + "✘ [DEPLOY.APP_EXITED] App exited with code 1. Not promoted.\n", + ); + expect(human.stderr).not.toContain("Promoted\n"); + expect(envelopeOf(json)).toMatchObject({ + ok: false, + error: { + code: "DEPLOY.APP_EXITED", + meta: { + serviceId: "svc_new", + versionId: "cpv_1", + start: { state: "exited", code: 1 }, + }, + }, + }); + }); + + it("fails without promoting when the app opens no port", async () => { + const h = await harness(); + sdk.deployApp.mockResolvedValue( + Result.ok({ + ...DEPLOYED, + ok: false, + promoted: false, + start: { state: "silent", output: "" }, + }), + ); + + const result = await h.run(["deploy", "--project", PROJECT.id], { + tty: true, + }); + + expect(result.exitCode).not.toBe(0); + expect(result.stderr).toContain( + "✘ [DEPLOY.APP_SILENT] App did not open a port within 60s. Not promoted.\n", + ); + }); + + it("fails when the app listens on another port than the stated one", async () => { + const h = await harness({ config: { app: { port: 3000 } } }); + sdk.deployApp.mockResolvedValue( + Result.ok({ + ...DEPLOYED, + ok: false, + promoted: false, + port: 3000, + start: { state: "listening", port: 4123 }, + }), + ); + + const result = await h.run(["deploy", "--project", PROJECT.id], { + tty: true, + }); + + expect(result.exitCode).not.toBe(0); + expect(result.stderr).toContain( + "✘ [DEPLOY.APP_PORT_MISMATCH] App listens on port 4123, not 3000. Not promoted.\n", + ); + }); + + it("fails when the upload or an API call fails", async () => { + const h = await harness(); + sdk.deployApp.mockResolvedValue(Result.err(new Error("upload refused"))); + + const result = await h.run(["deploy", "--project", PROJECT.id, "--json"]); + + expect(result.exitCode).not.toBe(0); + expect(envelopeOf(result)).toMatchObject({ + ok: false, + error: { code: "SERVICE.DEPLOY_FAILED", why: "upload refused" }, + }); + }); +}); diff --git a/packages/cli/tests/e2e-coverage.test.ts b/packages/cli/tests/e2e-coverage.test.ts index ae68625f6..f94b1be68 100644 --- a/packages/cli/tests/e2e-coverage.test.ts +++ b/packages/cli/tests/e2e-coverage.test.ts @@ -103,10 +103,8 @@ const EXCLUSIONS: Readonly> = { "Needs a GitHub App installation on the account under test, which CI cannot provision.", "git disconnect": "Needs a connected repository, which `git connect` cannot create here.", - deploy: - "Provisions real cloud infrastructure for an app entry point, through a child `alchemy deploy`. Standing that up per CI run is neither cheap nor unattended-safe.", "deploy list": - "Lists a deployed Composer app's stage, and this suite deploys none (see `deploy`). Composer's e2e deploy workflow runs it after every deploy and checks it against the platform.", + "Lists what a Composer app has deployed in an environment. This suite deploys no Composer app: `deploy` is covered here by its single-app path, and deploying a Composer app provisions cloud infrastructure through a child `alchemy deploy`, which is neither cheap nor unattended-safe per CI run. Composer's e2e deploy workflow runs `deploy list` after every deploy and checks it against the platform.", dev: "A session command: it runs until SIGINT or SIGTERM, redeploying on file change, so it has no happy path that terminates on its own.", "dev url": LOCAL_EMULATOR_REASON, "dev stop": LOCAL_EMULATOR_REASON, diff --git a/packages/cli/tests/mount-coverage.test.ts b/packages/cli/tests/mount-coverage.test.ts index cceb3de73..ff3fedb21 100644 --- a/packages/cli/tests/mount-coverage.test.ts +++ b/packages/cli/tests/mount-coverage.test.ts @@ -22,6 +22,7 @@ import { describe, expect, it } from "vitest"; import { cliGroups, composerCommandFamily, + deployCommandFamily, mountedCommands, ormCommandFamily, platformCommandFamily, @@ -171,10 +172,20 @@ const EXPECTED_MOUNT_PATHS: readonly string[] = [ const MOUNTED_FAMILIES = { platform: platformCommandFamily, composer: composerCommandFamily, + deploy: deployCommandFamily, orm: ormCommandFamily, skills: skillsCommandFamily, }; +/** + * Family commands the tree does not mount under their own definition. + * Composer's `deploy` is one: the shell's `deploy` is mounted at that + * path and runs Composer's command for a repository with a Composer config. + */ +const RUN_BY_ANOTHER_COMMAND: Readonly> = { + composer: ["deploy"], +}; + describe("prisma mount coverage", () => { it("mounts exactly the expected command paths", () => { expect(Object.keys(mountedCommands).sort()).toEqual(EXPECTED_MOUNT_PATHS); @@ -182,8 +193,10 @@ describe("prisma mount coverage", () => { it.each( Object.entries(MOUNTED_FAMILIES), - )("mounts every command in the %s family", (_name, commandFamily) => { - expect(unmountedFamilyCommands(commandFamily, mountedCommands)).toEqual([]); + )("mounts every command in the %s family", (name, commandFamily) => { + expect(unmountedFamilyCommands(commandFamily, mountedCommands)).toEqual( + RUN_BY_ANOTHER_COMMAND[name] ?? [], + ); }); it("gives every mounted command a family, except the deliberately familyless ones", () => { diff --git a/packages/cli/tests/v8-conformance.test.ts b/packages/cli/tests/v8-conformance.test.ts index a04b2854c..78673fa54 100644 --- a/packages/cli/tests/v8-conformance.test.ts +++ b/packages/cli/tests/v8-conformance.test.ts @@ -21,6 +21,7 @@ import { describe, expect, test } from "vitest"; import { SHELL_ALLOWED_UNIMPORTED } from "../scripts/shell-conformance-inputs"; import { composerCommandFamily, + deployCommandFamily, mountedCommands, ormCommandFamily, platformCommandFamily, @@ -31,8 +32,12 @@ const HERE = fileURLToPath(new URL(".", import.meta.url)); describe("conformance: validator no-throw", () => { const sections = sectionsFrom({ + // The deploy family comes before Composer's: both declare the `composer` + // section, and the deploy family's validator runs Composer's, so checking + // it checks both. families: [ platformCommandFamily, + deployCommandFamily, composerCommandFamily, ormCommandFamily, skillsCommandFamily, @@ -45,8 +50,9 @@ describe("conformance: validator no-throw", () => { * fails, which is the point: a new validator gets checked rather than * silently skipped. */ - test("the shell mounts composer's, orm's and skills' sections, and the platform family declares none", () => { + test("the shell mounts the app, composer, orm and skills sections", () => { expect(sections.map((section) => section.name)).toEqual([ + "app", "composer", "orm", "skills", diff --git a/packages/prisma/README.md b/packages/prisma/README.md index 04d6f640a..5529f12fc 100644 --- a/packages/prisma/README.md +++ b/packages/prisma/README.md @@ -74,7 +74,7 @@ npx prisma project env list --role preview | `postgres` | Create, inspect, back up, restore, and delete Prisma Postgres databases and their connections. | | `bucket` | Create, list, and delete object-store buckets and their access keys. | | `service` | Inspect services: versions, logs, domains, promote, roll back, delete. | -| `dev`, `deploy` | Run a Composer app locally; deploy it to the platform. `dev url` prints a running node's local URL and `dev stop` stops the app. | +| `dev`, `deploy` | Run a Composer app locally; deploy it to the platform. `dev url` prints a running node's local URL and `dev stop` stops the app. In a repository with no Composer config, `deploy` deploys the one app in the folder from its own install, build and start commands. | | `emulator` | List the local emulators `prisma dev` runs services, databases and buckets on. | | `contract`, `db`, `migration`, `orm init`, `lsp` | The Prisma ORM workflow. | diff --git a/packages/prisma/src/config.ts b/packages/prisma/src/config.ts index 9c1d2f455..f2e1293cd 100644 --- a/packages/prisma/src/config.ts +++ b/packages/prisma/src/config.ts @@ -3,4 +3,22 @@ * Re-exported from the engine so user repos never depend on * @prisma/cli-engine directly. */ -export { definePrismaConfig } from "@prisma/cli-engine"; +import { definePrismaConfig as defineConfig } from "@prisma/cli-engine"; +import type { AppConfig } from "@prisma/compute-sdk/app"; + +/** + * The `app` section: the App config of a single-app deploy. Every field + * is optional and replaces the Build setting that `prisma deploy` would + * take from the repository's own files. + */ +export type { AppConfig }; + +/** + * The engine's function, with the `app` section typed. The other + * sections are typed by the helper their own package exports. + */ +export const definePrismaConfig: < + T extends Record & { readonly app?: AppConfig }, +>( + config: T, +) => T & { readonly $prismaConfig: number } = defineConfig; diff --git a/scripts/list-error-codes.mjs b/scripts/list-error-codes.mjs index 8cfc7bc93..242ae82b4 100644 --- a/scripts/list-error-codes.mjs +++ b/scripts/list-error-codes.mjs @@ -31,6 +31,7 @@ const NAMESPACES = [ "BRANCH", "BUCKET", "CLI", + "DEPLOY", "FEEDBACK", "GIT", "INIT", diff --git a/skills/prisma-platform-core-concepts/SKILL.md b/skills/prisma-platform-core-concepts/SKILL.md index 226bd5efa..23c9eb5f0 100644 --- a/skills/prisma-platform-core-concepts/SKILL.md +++ b/skills/prisma-platform-core-concepts/SKILL.md @@ -79,7 +79,7 @@ this install plus `prisma skills sync`, not before. One config file, `prisma.config.ts`, configures the CLI and every product it runs. Each top-level key is a section owned by one product, and this CLI -recognises exactly three: `orm`, `composer`, and `skills`. The composed +recognises exactly four: `orm`, `composer`, `app`, and `skills`. The composed shape: ```ts @@ -103,8 +103,10 @@ export default definePrismaConfig({ }); ``` -`dev` and `deploy` read the `composer` section and nothing else; what goes -in it belongs to `prisma-composer-core-concepts`. A separate +`dev` reads the `composer` section and nothing else; what goes in it belongs +to `prisma-composer-core-concepts`. `deploy` reads the `composer` section +when a file declares one. When none does, `deploy` is a single-app deploy +and reads the `app` section (see below). A separate `prisma-composer.config.ts` is no longer read, and the old setup is refused, never silently ignored: `CONFIG.SECTION_MISSING` when no loaded `prisma.config.ts` declares a `composer` section, `CONFIG.FIELD_RETIRED` @@ -230,6 +232,33 @@ deployable app. Both paths converge the same declaration, so they are mutually idempotent: a repo can be connected to GitHub and still be deployed from the CLI. +**Single-app deploy.** In a repository with no `composer` section, +`prisma deploy` deploys the one app in the current folder as a service, +with no Composer module and no framework rules. It runs the app's own +commands, called its Build settings: Install (from the lockfile), Build (the +`build` script), and Start. Start is the first of: the `start` script unless +it runs a development server, a server file or a static site the build +wrote, an entry file such as `index.ts`. The app must listen on the port in +`PORT`. Each setting can be replaced in the `app` section: + +```ts +import { definePrismaConfig } from "prisma/config"; + +export default definePrismaConfig({ + app: { build: "npm run docs:build", static: "docs/.vitepress/dist" }, +}); +``` + +The fields are `install`, `build` (`null` skips the build), `start`, +`static` (a folder of static files to serve) and `port`. The project is the +linked one or `--project`; a single-app deploy never creates a project, so +run `prisma project create` or `prisma project link` first. `--name` names +the service (default: the `name` in `package.json`, else the folder name), +and `--environment ` deploys to that Branch. The app is started on +Prisma Cloud before it gets traffic: when it exits (`DEPLOY.APP_EXITED`) or +opens no port (`DEPLOY.APP_SILENT`), the deploy fails and the live version +stays. A missing start is `DEPLOY.APP_NO_START`. + ## Services and versions A **service** is an HTTP app inside a branch, reachable at a stable URL.