From 3912aa8bb6a9b8469e0e212172255cbfad3de740 Mon Sep 17 00:00:00 2001 From: Kristof Siket Date: Sat, 5 Dec 2026 08:30:05 +0000 Subject: [PATCH] fix(cli): `prisma deploy` records a failed build of the Service on the run's build A Service deploy builds the Service first and starts Composer's deploy after it. Composer reports the deploy on the build that the deploy workflow opened, so a failed install or build reported nothing. The workflow then recorded only "prisma deploy exited with status 2". When the run has a build (--build-id, else PRISMA_BUILD_ID), the CLI now sends the failure's code and summary to it. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Kristof Siket --- docs/product/command-principles.md | 2 +- packages/cli/src/commands/deploy/service.ts | 54 ++++++++- packages/cli/tests/deploy.test.ts | 124 +++++++++++++++++++- 3 files changed, 176 insertions(+), 4 deletions(-) diff --git a/docs/product/command-principles.md b/docs/product/command-principles.md index 97a89f6f..44e033cc 100644 --- a/docs/product/command-principles.md +++ b/docs/product/command-principles.md @@ -108,7 +108,7 @@ A Service deploy works like this: - **What the build output holds.** The SDK decides it, and `output.kind` names it. A static site is the folder of static files that the build wrote. A traced server is `.prisma/output` in the Service folder: the source files and the trace, which is the files of `node_modules` that the server loads. A standalone output is `.prisma/output` with the standalone output of a framework's build, today Next.js. A whole folder is the Service folder with all of `node_modules`, when the server could not be traced. - **What the user is told.** After the build, one line gives the start: `Start command: node server.js (from package.json)` or `Static files: dist (from build output)`. For a traced server, a second line gives the file count, the size and the entrypoints that the trace started from, then the bins and the optional peer dependencies when there are some: `Build output: 312 files, 4.2 MB, traced from server.js (bins: tsx)`. For a standalone output, the second line names the framework: `Build output: the standalone output of Next.js`. For a whole folder, the SDK's note says why, and the CLI prints the note as a warning. The `step-finished` event of the build step carries the build output in `data.output`, for every kind. - **Service config.** The `service` 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. -- **Build failures.** A failed install, a failed build, a missing start and a server that imports files from outside the Service folder stop the deploy before anything is created, each with its own code: `DEPLOY.SERVICE_INSTALL_FAILED`, `DEPLOY.SERVICE_BUILD_FAILED`, `DEPLOY.SERVICE_NO_START`, `DEPLOY.SERVICE_FILES_OUTSIDE_FOLDER`. +- **Build failures.** A failed install, a failed build, a missing start and a server that imports files from outside the Service folder stop the deploy before anything is created, each with its own code: `DEPLOY.SERVICE_INSTALL_FAILED`, `DEPLOY.SERVICE_BUILD_FAILED`, `DEPLOY.SERVICE_NO_START`, `DEPLOY.SERVICE_FILES_OUTSIDE_FOLDER`. When the run has a build on Prisma Cloud (`--build-id`, else `PRISMA_BUILD_ID`, which prisma/cloud-deploy-action sets), the CLI records the failure on it: `state` `failed`, `phase` `build`, the code as `failingStep` and the summary as `errorMessage`. Composer reports a deploy on that build, but it runs only after the build. A report that fails is a warning. - **Clean copy.** The CLI copies the build output without `.git` and dotenv files (`.env`, `.env.*`), at every depth. `excludedFromBuildOutput` from the SDK names what is left out. Composer uploads the whole folder it is given, so it is given this copy. When the build output is the Service folder, the copy also leaves out `.prisma/deploy`, which holds the copy itself. - **Composer files.** The CLI writes `module.ts` and `service.ts`: a Composer app with one Compute service whose build is the clean copy. It links its own `@prisma/composer` and `@prisma/composer-prisma-cloud` packages next to them. - **Where the files go.** `.prisma/deploy/` in the Service folder holds the two files and the clean copy. The folder has its own `.gitignore` with `*`, so git ignores it and no tracked file changes. The paths are the same on every deploy of one checkout: Composer uploads the path of `service.ts` and of the copy, so a path that changed would make a new version on every deploy. Two checkouts each have their own folder. The folder lies inside the checkout so that Composer finds the commit and the branch to record the deploy under. diff --git a/packages/cli/src/commands/deploy/service.ts b/packages/cli/src/commands/deploy/service.ts index 209d5e71..877938f8 100644 --- a/packages/cli/src/commands/deploy/service.ts +++ b/packages/cli/src/commands/deploy/service.ts @@ -36,6 +36,12 @@ const COMPOSER_PACKAGES = [ "@prisma/composer-prisma-cloud", ] as const; +/** The variable in which the deploy workflow passes the build it opened for the run. Composer reads it too. */ +const BUILD_ID_VARIABLE = "PRISMA_BUILD_ID"; + +/** The Management API's limit on a build's error message. */ +const ERROR_MESSAGE_LIMIT = 5000; + 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 = /^@[^/]*\//; @@ -184,6 +190,43 @@ async function linkComposerPackages(deployDir: string): Promise { ); } +/** + * Records why the Service's build failed on the build the deploy workflow + * opened for the run. Composer reports a deploy on that build, but it runs + * only after the Service is built. A report that fails is a warning, never a + * second failure. + */ +async function reportBuildFailure( + buildId: string, + failure: CliStructuredError, + ctx: CommandContext, +): Promise { + const warn = (detail: string) => + ctx.report({ + kind: "message", + severity: "warn", + text: `Could not report the failed build to Prisma Cloud: ${detail}`, + }); + + try { + const { error, response } = await ctx.api.PATCH("/v1/builds/{buildId}", { + params: { path: { buildId } }, + body: { + phase: "build", + state: "failed", + failingStep: failure.code, + errorMessage: failure.message.slice(0, ERROR_MESSAGE_LIMIT), + }, + signal: ctx.signal, + }); + if (error) { + warn(`the API answered ${response.status}`); + } + } catch (error) { + warn(error instanceof Error ? error.message : String(error)); + } +} + /** * Deploys the folder as one Service: builds it from its own install, build * and start commands, then hands the build output to Composer's deploy as @@ -236,7 +279,16 @@ export async function deployService( ctx.report({ kind: "message", severity: "warn", text: note }); } if (built.isErr()) { - return notOk(serviceBuildError(built.error)); + const failure = serviceBuildError(built.error); + // An empty value is how a shell writes "unset". The flag wins, as it does in Composer. + const buildId = [args.flags.buildId, ctx.env[BUILD_ID_VARIABLE]].find( + (id): id is string => typeof id === "string" && id !== "", + ); + if (buildId !== undefined) { + await reportBuildFailure(buildId, failure, ctx); + } + + return notOk(failure); } const { output, start } = built.value; diff --git a/packages/cli/tests/deploy.test.ts b/packages/cli/tests/deploy.test.ts index 4b8ec3ca..eba98990 100644 --- a/packages/cli/tests/deploy.test.ts +++ b/packages/cli/tests/deploy.test.ts @@ -10,7 +10,10 @@ import { } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; -import { defineCommandFamily } from "@prisma/cli-engine"; +import { + defineCommandFamily, + type ManagementApiClient, +} from "@prisma/cli-engine"; import { ok } from "@prisma/cli-engine/protocol"; import { createTestCli, mintTestJwt } from "@prisma/cli-engine/testing"; import { defineConfig as composer } from "@prisma/composer/config"; @@ -157,7 +160,10 @@ interface Harness { } async function harness( - options: { config?: Record } = {}, + options: { + config?: Record; + client?: ManagementApiClient; + } = {}, ): Promise { const cwd = await makeTempCwd("deploy-"); await writeFile( @@ -181,6 +187,9 @@ async function harness( commands: { deploy }, groups: { deploy: cliGroups.deploy }, config: options.config, + ...(options.client === undefined + ? {} + : { managementApi: { client: options.client } }), sessions: [ { workspaceId: WORKSPACE.id, @@ -452,6 +461,117 @@ describe("deploy: a build that produces no build output", () => { }); }); +describe("deploy: a failed build of the Service, in a run that has a build on Prisma Cloud", () => { + const BUILD_FAILED = new ServiceBuildError({ + code: "build_failed", + message: "Step failed: npm run build", + settings: SETTINGS, + steps: [{ name: "build", command: "npm run build", seconds: 5, ok: false }], + commandOutput: "error TS2304", + }); + + /** A client that records each PATCH and answers it with `answer`. */ + function patchClient(answer: () => unknown = () => ({ data: {} })) { + const patches: { path: string; init: unknown }[] = []; + const client = { + PATCH: async (apiPath: string, init: unknown) => { + patches.push({ path: apiPath, init }); + return answer(); + }, + } as unknown as ManagementApiClient; + return { client, patches }; + } + + it("records the failure on the build that PRISMA_BUILD_ID names", async () => { + const { client, patches } = patchClient(); + const h = await harness({ client }); + sdk.buildService.mockResolvedValue(Result.err(BUILD_FAILED)); + + const result = await h.run(["deploy", "--json"], { + PRISMA_BUILD_ID: "bld_fromworkflow", + }); + + expect(envelopeOf(result)).toMatchObject({ + ok: false, + error: { code: "DEPLOY.SERVICE_BUILD_FAILED" }, + }); + expect(patches).toEqual([ + { + path: "/v1/builds/{buildId}", + init: expect.objectContaining({ + params: { path: { buildId: "bld_fromworkflow" } }, + body: { + phase: "build", + state: "failed", + failingStep: "DEPLOY.SERVICE_BUILD_FAILED", + errorMessage: "Step failed: npm run build", + }, + }), + }, + ]); + }); + + it("uses --build-id when both it and PRISMA_BUILD_ID are set", async () => { + const { client, patches } = patchClient(); + const h = await harness({ client }); + sdk.buildService.mockResolvedValue(Result.err(BUILD_FAILED)); + + await h.run(["deploy", "--json", "--build-id", "bld_fromflag"], { + PRISMA_BUILD_ID: "bld_fromworkflow", + }); + + expect(patches).toHaveLength(1); + expect(patches[0]?.init).toMatchObject({ + params: { path: { buildId: "bld_fromflag" } }, + }); + }); + + it("records nothing when the run has no build", async () => { + const { client, patches } = patchClient(); + const h = await harness({ client }); + sdk.buildService.mockResolvedValue(Result.err(BUILD_FAILED)); + + await h.run(["deploy", "--json"], { PRISMA_BUILD_ID: "" }); + + expect(patches).toEqual([]); + }); + + it.each([ + [ + "the API refuses the report", + () => ({ error: { message: "not found" }, response: { status: 404 } }), + "the API answered 404", + ], + [ + "the request fails", + () => { + throw new Error("fetch failed"); + }, + "fetch failed", + ], + ] as const)("keeps the build's own error and warns when %s", async (_case, answer, detail) => { + const { client } = patchClient(answer); + const h = await harness({ client }); + sdk.buildService.mockResolvedValue(Result.err(BUILD_FAILED)); + + const result = await h.run(["deploy", "--json"], { + PRISMA_BUILD_ID: "bld_fromworkflow", + }); + + expect(envelopeOf(result)).toMatchObject({ + ok: false, + error: { code: "DEPLOY.SERVICE_BUILD_FAILED" }, + }); + expect(result.events).toContainEqual( + expect.objectContaining({ + kind: "message", + severity: "warn", + text: `Could not report the failed build to Prisma Cloud: ${detail}`, + }), + ); + }); +}); + describe("deploy: a server that imports files from outside the Service folder", () => { it("stops with DEPLOY.SERVICE_FILES_OUTSIDE_FOLDER and says that a workspace member cannot be deployed", async () => { const h = await harness();