diff --git a/docs/product/command-principles.md b/docs/product/command-principles.md index 427268f9e..8b9ae1781 100644 --- a/docs/product/command-principles.md +++ b/docs/product/command-principles.md @@ -37,6 +37,7 @@ The long-term command surface grows through workflow groups such as: - `db` - `app` - `git` +- `build` The preview implements only `auth`, `project`, `git`, `branch`, `database`, `bucket`, `app`, `skills`, and `init`. @@ -53,6 +54,7 @@ The CLI should keep the meaning of these nouns stable: - `service` - `version` (always qualified in prose: a service version) - `domain` +- `build` (one run that built and deployed the app from a Git commit, such as a GitHub Actions run of the deploy workflow; its id starts with `bld_`) If a noun means one thing in docs and a different thing in commands or output, the model is already drifting. @@ -128,7 +130,7 @@ The scaffolded config imports `definePrismaConfig` from `prisma/config` and spel ### `logs` -Resolve a service version and show or stream its logs. +Show the logs of one resource. `service logs` resolves a service version and shows or streams what it printed while running. `build logs` shows the CI job log of one build, the newest one when no build id is given. Build logs are a separate group because a build is not owned by one service: one build can deploy several. ### `delete` and `remove` diff --git a/docs/reference/error-reference.md b/docs/reference/error-reference.md index 0c830fe6e..acbb923ff 100644 --- a/docs/reference/error-reference.md +++ b/docs/reference/error-reference.md @@ -18,6 +18,7 @@ Namespaces: | `AUTH` | Workspace authentication and sessions (`prisma auth`, credential resolution) | | `BRANCH` | Branch listing (`prisma branch`) | | `BUCKET` | Bucket and bucket-key management (`prisma bucket`) | +| `BUILD` | Listing builds and reading a build's log (`prisma build`) | | `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`), and building the one Service of a repository with no Composer config (`prisma deploy`), whose codes start with `DEPLOY.SERVICE_` | @@ -120,6 +121,20 @@ A bucket Management API request (listing, creating, or deleting buckets or bucke A bucket subcommand was called without its required id argument: `bucket delete` and `bucket key create`/`bucket key list` need a bucket id, and `bucket key delete` needs both a bucket id and a key id. The nextActions point at `bucket list` (or `bucket key list`) to find the ids. Meta: none. +## BUILD + +### BUILD.API_ERROR + +A Management API request made by `prisma build list` or `prisma build logs` failed. The `why` carries the API's message or, failing that, the HTTP status. For `build logs` the message says what to do: a build that did not run in GitHub Actions has no log here, a GitHub rate limit says how long to wait (HTTP 503), and a missing GitHub App permission links to where to approve it. For an unknown build id (HTTP 404), the next action is `prisma build list`. Meta: `status`, `apiCode` (the API's own error code, when the response supplied one). + +### BUILD.NONE + +`prisma build logs` was run without a build id, and the project has no builds yet. A build is reported when the deploy workflow runs on a push, or when `prisma deploy` runs. Meta: none. + +### BUILD.USAGE_ERROR + +`prisma build logs` was given a `--tail` that is not a whole number from 1 to 1000. Leave `--tail` out to print every line. Meta: none. + ## CLI ### CLI.ABORTED diff --git a/packages/cli-engine/package.json b/packages/cli-engine/package.json index 6cc42b20b..34f3d3e39 100644 --- a/packages/cli-engine/package.json +++ b/packages/cli-engine/package.json @@ -58,7 +58,7 @@ "@prisma/management-api-sdk": "^1.55.0" }, "devDependencies": { - "@prisma/management-api-sdk": "1.101.0", + "@prisma/management-api-sdk": "1.110.0", "@repo/cli-conformance": "workspace:8.0.0-rc.39", "@repo/tsconfig": "workspace:8.0.0-rc.39", "@types/node": "^22.19.19", diff --git a/packages/cli/AGENTS.md b/packages/cli/AGENTS.md index 003c02e55..1ffdd01c8 100644 --- a/packages/cli/AGENTS.md +++ b/packages/cli/AGENTS.md @@ -33,7 +33,7 @@ Architecture and contributor workflow references: - Group commands by developer workflow, not product ownership. - No `orm`, `postgres`, or `compute` namespaces in the command surface. - Canonical command shape is `prisma `. -- The shipped groups are `auth`, `project`, `git`, `branch`, `postgres`, `bucket`, `service`, `skills`, the root `init` and `deploy` verbs, `dev` (a command that is also a group: `dev url`, `dev stop`), `emulator`, and the ORM family (`contract`, `db`, `migration`, `orm init`, `lsp`). +- The shipped groups are `auth`, `project`, `git`, `branch`, `postgres`, `bucket`, `service`, `build`, `skills`, the root `init` and `deploy` verbs, `dev` (a command that is also a group: `dev url`, `dev stop`), `emulator`, and the ORM family (`contract`, `db`, `migration`, `orm init`, `lsp`). - Preserve the long-term resource model: `workspace -> project -> branch -> { service, database, bucket }`. The mounted tree in `packages/cli/src/cli.ts` is the authoritative command surface. diff --git a/packages/cli/README.md b/packages/cli/README.md index da6248bc3..852d0b088 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -77,6 +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. | +| `build` | List the runs that built and deployed your app, and print one build's log from GitHub Actions. | | `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 folder as one Service, built 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/build.e2e.ts b/packages/cli/e2e/build.e2e.ts new file mode 100644 index 000000000..2b6ece0f6 --- /dev/null +++ b/packages/cli/e2e/build.e2e.ts @@ -0,0 +1,71 @@ +/** Real-API runs of the build commands, on a build this file reports. */ +import { beforeAll, expect, it } from "vitest"; + +import { apiBaseUrl, serviceToken } from "./deployed-service"; +import { useScratchProject } from "./scratch"; +import { describeCommand } from "./suite"; + +const scratch = useScratchProject("build"); + +let buildId: string; + +/** Reports a build the way `prisma deploy` does from a laptop. Only a + * GitHub Actions run can report a build that has a log, and this suite + * has none, so `build logs` is checked on the answer for this build. */ +beforeAll(async () => { + const response = await fetch(`${apiBaseUrl()}/v1/builds`, { + method: "POST", + headers: { + authorization: `Bearer ${serviceToken()}`, + "content-type": "application/json", + }, + body: JSON.stringify({ + source: "cli", + commitSha: "0123456789abcdef0123456789abcdef01234567", + branchName: "main", + projectId: scratch.project().id, + }), + }); + if (!response.ok) { + throw new Error( + `could not report a build: HTTP ${response.status} ${await response.text()}`, + ); + } + buildId = ((await response.json()) as { data: { id: string } }).data.id; +}); + +describeCommand("build list", () => { + it("lists the project's builds, including one just reported", async () => { + const run = await scratch.run(["build", "list"]); + const result = run.envelope.result as { + readonly projectId: string; + readonly builds: ReadonlyArray<{ + readonly id: string; + readonly state: string; + readonly branchName: string; + }>; + }; + + expect(run.exitCode).toBe(0); + expect(result.projectId).toBe(scratch.project().id); + expect(result.builds).toContainEqual( + expect.objectContaining({ + id: buildId, + state: "pending", + branchName: "main", + }), + ); + }); +}); + +describeCommand("build logs", () => { + it("reads the newest build, and says one that did not run in GitHub Actions has no log", async () => { + const run = await scratch.run(["build", "logs"], { expectOk: false }); + + expect(run.envelope.ok).toBe(false); + expect(run.envelope.error?.code).toBe("BUILD.API_ERROR"); + expect(run.envelope.error?.why).toContain( + "was not reported by a GitHub Actions run", + ); + }); +}); diff --git a/packages/cli/package.json b/packages/cli/package.json index 956fca77a..878c345dd 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -54,7 +54,7 @@ "@prisma/composer-cli": "0.41.2", "@prisma/composer-prisma-cloud": "0.41.2", "@prisma/compute-sdk": "0.47.0", - "@prisma/management-api-sdk": "1.101.0", + "@prisma/management-api-sdk": "1.110.0", "@prisma/orm-family-sql": "8.0.0-rc.28", "@prisma/orm-framework": "8.0.0-rc.28", "@prisma/orm-postgres": "8.0.0-rc.28", diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index 1b5d0e41a..fc7ebbafe 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -24,6 +24,8 @@ 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 { buildListCommand } from "./commands/build/list"; +import { buildLogsCommand } from "./commands/build/logs"; import { createDeployCommand } from "./commands/deploy/command"; import { deployConfigSection, @@ -118,6 +120,8 @@ export const platformCommandFamily: CommandFamily = defineCommandFamily({ bucketKeyCreate: bucketKeyCreateCommand, bucketKeyDelete: bucketKeyDeleteCommand, branchList: branchListCommand, + buildList: buildListCommand, + buildLogs: buildLogsCommand, gitConnect: gitConnectCommand, gitDisconnect: gitDisconnectCommand, serviceList: serviceListCommand, @@ -289,6 +293,22 @@ export const cliGroups: Readonly< description: "A Branch maps to a Git branch of the connected repository. Each is an isolated environment with its own services, databases, buckets, and environment variables: the production branch serves live traffic, every other branch is a preview.", }, + build: { + brief: + "Inspect the runs that build and deploy your app. List recent builds, print one build's log", + description: + "A build is one run that built and deployed your app from a Git commit: a GitHub Actions run of the deploy workflow on push, or a 'prisma deploy' from your machine. Each has an id (bld_...) and a state: pending, running, succeeded, failed, or cancelled. 'logs' reads a build's log from GitHub Actions, so it works only for builds that ran there.", + workflow: [ + { + run: "build list --state failed", + brief: "Find the builds that failed, newest first", + }, + { + run: "build logs --errors", + brief: "Print the error lines of the newest build", + }, + ], + }, git: { brief: "Manage the GitHub connection behind deploy-on-push. Connect or disconnect a repository", @@ -437,6 +457,8 @@ export const mountedCommands: Readonly> = { "bucket key create": bucketKeyCreateCommand, "bucket key delete": bucketKeyDeleteCommand, "branch list": branchListCommand, + "build list": buildListCommand, + "build logs": buildLogsCommand, "git connect": gitConnectCommand, "git disconnect": gitDisconnectCommand, "service list": serviceListCommand, diff --git a/packages/cli/src/commands/build/errors.ts b/packages/cli/src/commands/build/errors.ts new file mode 100644 index 000000000..6d18f17df --- /dev/null +++ b/packages/cli/src/commands/build/errors.ts @@ -0,0 +1,43 @@ +import { CliStructuredError } from "@prisma/cli-engine/protocol"; +import { CLI_NAME } from "../../cli-name"; +import { + type ApiErrorBody, + apiErrorDetail, +} from "../../lib/management-api-error"; + +/** The API's message is the `why`: for a build log it already says what + * to do. Its hint is not used, because it names API routes, not commands. */ +export function buildApiError( + summary: string, + response: Response | undefined, + error: ApiErrorBody | undefined, +): CliStructuredError { + const status = response?.status ?? 0; + const detail = apiErrorDetail(error); + return new CliStructuredError("BUILD.API_ERROR", summary, { + why: + detail.message ?? + `The Management API returned status ${status || "unknown"}.`, + ...(status || detail.code !== undefined + ? { + meta: { + ...(status ? { status } : {}), + ...(detail.code !== undefined ? { apiCode: detail.code } : {}), + }, + } + : {}), + nextActions: [ + status === 404 + ? { + kind: "run-command", + label: "List the project's builds", + command: `${CLI_NAME} build list`, + } + : { + kind: "user-choice", + label: + "Re-run with --log-level verbose for the underlying API response details.", + }, + ], + }); +} diff --git a/packages/cli/src/commands/build/list.ts b/packages/cli/src/commands/build/list.ts new file mode 100644 index 000000000..c9b77a039 --- /dev/null +++ b/packages/cli/src/commands/build/list.ts @@ -0,0 +1,160 @@ +import { + type Block, + defineCommand, + flag, + type Presentations, +} from "@prisma/cli-engine"; +import { ok } from "@prisma/cli-engine/protocol"; +import { CLI_NAME } from "../../cli-name"; +import { resolvePinnedProject } from "../project/context"; +import { resolveActiveWorkspace } from "../resources-shared/workspace"; +import { buildApiError } from "./errors"; + +const BUILD_STATES = [ + "pending", + "running", + "succeeded", + "failed", + "cancelled", +] as const; + +const DEFAULT_LIMIT = 20; + +export interface BuildSummary { + readonly id: string; + readonly state: (typeof BUILD_STATES)[number]; + readonly branchName: string; + readonly commitSha: string; + readonly createdAt: string; + readonly failingStep: string | null; + readonly errorMessage: string | null; +} + +export interface BuildListResult { + readonly projectId: string; + readonly projectName: string; + readonly builds: readonly BuildSummary[]; + readonly hasMore: boolean; +} + +function listPresentations(result: BuildListResult): Presentations { + const rows = result.builds.map((build) => [ + build.id, + build.state, + build.branchName, + build.commitSha.slice(0, 7), + build.createdAt, + ]); + return { + json: () => result, + next: () => + result.builds.length === 0 + ? [] + : [ + { + kind: "run-command", + label: "Read a build's log", + command: `${CLI_NAME} build logs ${result.builds[0]?.id}`, + }, + ], + human: (): Block[] => [ + { + kind: "fields", + rows: [{ label: "project", value: result.projectName }], + }, + rows.length === 0 + ? { kind: "summary", status: "info", text: "No builds found." } + : { + kind: "table", + columns: ["Id", "State", "Branch", "Commit", "Created"], + rows, + }, + ...(result.hasMore + ? [ + { + kind: "summary" as const, + status: "info" as const, + text: "More builds exist. Pass a larger --limit to list them.", + }, + ] + : []), + ], + stdout: () => + result.builds.map((build) => + [ + build.id, + build.state, + build.branchName, + build.commitSha, + build.createdAt, + ].join("\t"), + ), + }; +} + +export const buildListCommand = defineCommand({ + help: { + summary: "List a project's recent builds, newest first", + description: + "A build is one run that built and deployed your app from a Git commit, such as a GitHub Actions run of the deploy workflow or a 'prisma deploy' from this machine. Use the listed ids with 'build logs'.", + examples: ["build list", "build list --state failed"], + }, + args: { + flags: { + project: flag.string({ + brief: + "Project id or name (default: the project this directory is linked to)", + placeholder: "id-or-name", + }), + state: flag.enum({ + brief: "Only list builds in this state, such as failed", + values: BUILD_STATES, + }), + limit: flag.number({ + brief: `How many builds to list (default ${DEFAULT_LIMIT})`, + placeholder: "n", + }), + }, + }, + needs: { credentials: true }, + handler: async (args, ctx) => { + const workspace = await resolveActiveWorkspace(ctx); + const target = await resolvePinnedProject( + ctx, + workspace, + args.flags.project, + "build list", + ); + const { data, error, response } = await ctx.api.GET("/v1/builds", { + params: { + query: { + projectId: target.project.id, + limit: args.flags.limit ?? DEFAULT_LIMIT, + ...(args.flags.state !== undefined + ? { state: args.flags.state } + : {}), + }, + }, + signal: ctx.signal, + }); + if (error || !data) { + throw buildApiError("Failed to list builds", response, error); + } + + const result: BuildListResult = { + projectId: target.project.id, + projectName: target.project.name, + builds: data.data.map((build) => ({ + id: build.id, + state: build.state, + branchName: build.branchName, + commitSha: build.commitSha, + createdAt: build.createdAt, + failingStep: build.failingStep, + errorMessage: build.errorMessage, + })), + hasMore: data.pagination.hasMore, + }; + return ok(ctx.present({ data: result }, listPresentations(result))); + }, +}); diff --git a/packages/cli/src/commands/build/logs.ts b/packages/cli/src/commands/build/logs.ts new file mode 100644 index 000000000..3d6ddef9f --- /dev/null +++ b/packages/cli/src/commands/build/logs.ts @@ -0,0 +1,184 @@ +import { + type Block, + defineCommand, + flag, + type Presentations, + positional, +} from "@prisma/cli-engine"; +import { CliStructuredError, ok } from "@prisma/cli-engine/protocol"; +import { resolvePinnedProject } from "../project/context"; +import { resolveActiveWorkspace } from "../resources-shared/workspace"; +import { buildApiError } from "./errors"; + +const MAX_TAIL = 1000; + +export interface BuildLogsResult { + readonly buildId: string; + readonly job: { + readonly name: string; + readonly url: string; + readonly conclusion: string | null; + }; + /** The lines asked for: every line of the build, the last --tail + * lines, or only the error lines with --errors. */ + readonly lines: readonly string[]; + readonly truncated: boolean; + readonly errors: readonly string[]; +} + +function logsPresentations(result: BuildLogsResult): Presentations { + return { + json: () => result, + next: () => [], + human: (): Block[] => [ + { + kind: "fields", + rows: [ + { label: "build", value: result.buildId }, + { label: "job", value: result.job.name }, + { label: "result", value: result.job.conclusion ?? "running" }, + { label: "url", value: result.job.url }, + ], + }, + result.lines.length === 0 + ? { kind: "summary", status: "info", text: "No log lines." } + : { kind: "drawing", lines: result.lines }, + ...(result.truncated + ? [ + { + kind: "summary" as const, + status: "warn" as const, + text: "Earlier lines are not shown. Open the job url for the full log.", + }, + ] + : []), + ], + stdout: () => [...result.lines], + }; +} + +export const buildLogsCommand = defineCommand({ + help: { + summary: + "Print a build's log, to see why it failed (default: the newest build)", + description: + "Prints the lines of the CI job that ran the build, from the build's start to its end, without the job's setup and cleanup. Only builds that ran in GitHub Actions have a log here; a 'prisma deploy' from your machine printed its log where it ran. Without a build id, it reads the newest build of the project. Build ids come from 'build list'.", + examples: [ + "build logs --errors", + "build logs bld_123", + "build logs bld_123 --tail 50", + ], + }, + args: { + positionals: { + build: positional.optionalString({ + brief: + "Build id, from 'build list' (default: the project's newest build)", + placeholder: "build", + }), + }, + flags: { + project: flag.string({ + brief: + "Project whose newest build to read when no build id is given (default: the project this directory is linked to)", + placeholder: "id-or-name", + }), + tail: flag.number({ + brief: `Print only the last N lines, up to ${MAX_TAIL} (default: every line)`, + placeholder: "n", + }), + errors: flag.boolean({ + brief: "Print only the lines the build reported as errors", + }), + }, + }, + needs: { credentials: true }, + handler: async (args, ctx) => { + const { tail } = args.flags; + if ( + tail !== undefined && + (!Number.isInteger(tail) || tail < 1 || tail > MAX_TAIL) + ) { + throw new CliStructuredError( + "BUILD.USAGE_ERROR", + "--tail must be a whole number from 1 to 1000", + { + why: `--tail was ${tail}.`, + nextActions: [ + { + kind: "user-choice", + label: + "Pass a --tail from 1 to 1000, or leave it out to print every line.", + }, + ], + }, + ); + } + + let buildId = args.positionals.build; + if (buildId === undefined) { + const workspace = await resolveActiveWorkspace(ctx); + const target = await resolvePinnedProject( + ctx, + workspace, + args.flags.project, + "build logs", + ); + const newest = await ctx.api.GET("/v1/builds", { + params: { query: { projectId: target.project.id, limit: 1 } }, + signal: ctx.signal, + }); + if (newest.error || !newest.data) { + throw buildApiError( + "Failed to find the newest build", + newest.response, + newest.error, + ); + } + buildId = newest.data.data[0]?.id; + if (buildId === undefined) { + throw new CliStructuredError( + "BUILD.NONE", + `Project ${target.project.name} has no builds yet`, + { + why: "A build is reported when the deploy workflow runs on a push, or when 'prisma deploy' runs.", + nextActions: [ + { + kind: "user-choice", + label: "Push a commit to a connected branch, then try again.", + }, + ], + }, + ); + } + } + + const { data, error, response } = await ctx.api.GET( + "/v1/builds/{buildId}/logs", + { + params: { + path: { buildId }, + query: tail !== undefined ? { tail } : {}, + }, + signal: ctx.signal, + }, + ); + if (error || !data) { + throw buildApiError("Failed to read the build's log", response, error); + } + + const log = data.data; + const result: BuildLogsResult = { + buildId: log.buildId, + job: { + name: log.job.name, + url: log.job.url, + conclusion: log.job.conclusion, + }, + lines: args.flags.errors ? log.errors : log.lines, + truncated: log.truncated, + errors: log.errors, + }; + return ok(ctx.present({ data: result }, logsPresentations(result))); + }, +}); diff --git a/packages/cli/src/commands/service/results.ts b/packages/cli/src/commands/service/results.ts index bcb11a478..e810bfeb9 100644 --- a/packages/cli/src/commands/service/results.ts +++ b/packages/cli/src/commands/service/results.ts @@ -109,6 +109,7 @@ export type ServiceDomainStatus = "pending" | "active"; /** What the hostname is doing now. `active` means it serves the service. */ export type ServiceDomainState = + | "no_domain_ownership" | "not_verified" | "no_service" | "no_live_deployment" diff --git a/packages/cli/src/lib/app/app-provider.ts b/packages/cli/src/lib/app/app-provider.ts index 7ac182807..d25432282 100644 --- a/packages/cli/src/lib/app/app-provider.ts +++ b/packages/cli/src/lib/app/app-provider.ts @@ -77,6 +77,7 @@ export interface RemovedAppRecord { export type DomainStatus = "pending" | "active"; export type DomainState = + | "no_domain_ownership" | "not_verified" | "no_service" | "no_live_deployment" diff --git a/packages/cli/src/lib/app/domain-guidance.ts b/packages/cli/src/lib/app/domain-guidance.ts index 60b1357d1..cbf8af562 100644 --- a/packages/cli/src/lib/app/domain-guidance.ts +++ b/packages/cli/src/lib/app/domain-guidance.ts @@ -78,14 +78,18 @@ export function waitsForUserDns(domain: Pick): boolean { /** * States a wait stops at. A failed certificate is only retried when the * user asks, and a hostname whose service is deleted has to be added - * again. In the other states where the user has to act, such as + * again, and so does one that no domain ownership covers. In the other states where the user has to act, such as * publishing DNS or deploying, the hostname goes on by itself once they * have, so a wait keeps going. */ export function cannotBecomeActive( domain: Pick, ): boolean { - return domain.state === "certificate_failed" || domain.state === "no_service"; + return ( + domain.state === "certificate_failed" || + domain.state === "no_service" || + domain.state === "no_domain_ownership" + ); } /** What a hostname that is not serving yet waits on. Null once it serves. */ @@ -104,6 +108,12 @@ export function domainStateGuidance( switch (domain.state) { case "active": return null; + case "no_domain_ownership": + return { + failed: false, + waitingOn: "No domain ownership in this workspace covers the hostname.", + fix: "Delete the hostname, then add it again: adding it creates the domain ownership.", + }; case "not_verified": return { failed: false, diff --git a/packages/cli/tests/build.test.ts b/packages/cli/tests/build.test.ts new file mode 100644 index 000000000..c6922b9cf --- /dev/null +++ b/packages/cli/tests/build.test.ts @@ -0,0 +1,299 @@ +import { mkdir, mkdtemp, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import type { ManagementApiClient, StreamEvent } from "@prisma/cli-engine"; +import { createTestCli, mintTestJwt } from "@prisma/cli-engine/testing"; +import { describe, expect, it } from "vitest"; + +import { buildListCommand } from "../src/commands/build/list"; +import { buildLogsCommand } from "../src/commands/build/logs"; + +const SESSION = { + workspaceId: "ws_1", + workspaceName: "Acme Inc", + credential: { + token: mintTestJwt({ sub: "usr_1", workspace_id: "ws_1" }), + refreshToken: undefined, + expiresAt: undefined, + }, +}; + +const PROJECTS = [ + { + id: "proj_1", + name: "Billing", + workspace: { id: "wksp_ws_1", name: "Acme Inc" }, + }, +]; + +const FAILED_BUILD = { + id: "bld_2", + source: "ci", + state: "failed", + phase: "build", + commitSha: "9f8e7d6c5b4a39281706f5e4d3c2b1a098765432", + branchName: "feature-x", + gitRepoId: "repo_1", + projectId: "proj_1", + branchId: "br_2", + externalLogUrl: null, + deployedUrl: null, + applicationTopologyContentHash: null, + errorMessage: "build failed: exit code 1", + failingStep: "build", + createdAt: "2026-12-03T09:11:42.000Z", + startedAt: "2026-12-03T09:11:42.000Z", + finishedAt: "2026-12-03T09:12:10.000Z", +}; + +const LOG = { + buildId: "bld_2", + job: { + name: "deploy", + url: "https://github.com/acme/billing/actions/runs/1/job/2", + conclusion: "failure", + steps: [{ name: "Deploy", conclusion: "failure" }], + }, + lines: [ + "2026-12-03T09:11:58.3736739Z ##[group]build", + "2026-12-03T09:11:59.8093597Z > build", + "2026-12-03T09:12:01.0000000Z ##[error]build failed: exit code 1", + ], + truncated: false, + errors: ["2026-12-03T09:12:01.0000000Z ##[error]build failed: exit code 1"], +}; + +interface Call { + readonly path: string; + readonly init: { + params?: { path?: Record; query?: Record }; + }; +} + +function buildClient( + routes: Readonly unknown>> = {}, + calls: Call[] = [], +): ManagementApiClient { + return { + GET: async (apiPath: string, init: Call["init"]) => { + const call: Call = { path: apiPath, init: init ?? {} }; + calls.push(call); + const route = routes[apiPath]; + if (route) { + return route(call); + } + if (apiPath === "/v1/projects") { + return { data: { data: PROJECTS } }; + } + if (apiPath === "/v1/builds") { + return { + data: { + data: [FAILED_BUILD], + pagination: { hasMore: false, nextCursor: null }, + }, + }; + } + if (apiPath === "/v1/builds/{buildId}/logs") { + return { data: { data: LOG } }; + } + throw new Error(`unexpected GET ${apiPath}`); + }, + } as unknown as ManagementApiClient; +} + +function makeCli(client: ManagementApiClient) { + return createTestCli({ + commands: { + "build list": buildListCommand, + "build logs": buildLogsCommand, + }, + groups: { build: { brief: "Inspect builds" } }, + sessions: [SESSION], + selectedWorkspaceId: SESSION.workspaceId, + managementApi: { client }, + now: () => new Date(0), + }); +} + +async function linkedCwd() { + const cwd = await mkdtemp(path.join(os.tmpdir(), "build-test-")); + await mkdir(path.join(cwd, ".prisma"), { recursive: true }); + await writeFile( + path.join(cwd, ".prisma", "local.json"), + `${JSON.stringify({ workspaceId: "ws_1", projectId: "proj_1" })}\n`, + "utf8", + ); + return cwd; +} + +function envelope(frames: ReadonlyArray<{ kind: string }>) { + const frame = frames.at(-1); + if (frame === undefined || frame.kind !== "result") { + throw new Error("expected a terminal result frame"); + } + return (frame as Extract).envelope; +} + +describe("prisma build list", () => { + it("lists the linked project's builds, one tab-separated line each", async () => { + const calls: Call[] = []; + const result = await makeCli(buildClient({}, calls)).run( + ["build", "list", "--state", "failed"], + { cwd: await linkedCwd(), isTty: { stdout: true } }, + ); + + expect(result.exitCode).toBe(0); + expect( + calls.find((call) => call.path === "/v1/builds")?.init.params, + ).toEqual({ + query: { projectId: "proj_1", limit: 20, state: "failed" }, + }); + expect(result.presented?.presentation.stdout).toEqual([ + "bld_2\tfailed\tfeature-x\t9f8e7d6c5b4a39281706f5e4d3c2b1a098765432\t2026-12-03T09:11:42.000Z", + ]); + }); +}); + +describe("prisma build logs", () => { + it("points an unknown build id at build list, not at the API's hint", async () => { + const result = await makeCli( + buildClient({ + "/v1/builds/{buildId}/logs": () => ({ + error: { + error: { + code: "notFound", + message: "Build with id nope not found", + hint: "Use GET /v1/{resource} to list available IDs.", + }, + }, + response: new Response(null, { status: 404 }), + }), + }), + ).run(["build", "logs", "bld_nope", "--json"]); + + expect(result.exitCode).toBe(2); + expect(envelope(result.json)).toMatchObject({ + ok: false, + error: { + code: "BUILD.API_ERROR", + why: "Build with id nope not found", + meta: { status: 404, apiCode: "notFound" }, + nextActions: [ + { + kind: "run-command", + label: "List the project's builds", + command: "prisma build list", + }, + ], + }, + }); + }); + + it("prints every line of the build", async () => { + const result = await makeCli(buildClient()).run( + ["build", "logs", "bld_2"], + { isTty: { stdout: true } }, + ); + + expect(result.exitCode).toBe(0); + expect(result.presented?.presentation.stdout).toEqual(LOG.lines); + }); + + it("reads the linked project's newest build when no id is given", async () => { + const calls: Call[] = []; + const result = await makeCli(buildClient({}, calls)).run( + ["build", "logs"], + { cwd: await linkedCwd(), isTty: { stdout: true } }, + ); + + expect(result.exitCode).toBe(0); + expect( + calls.find((call) => call.path === "/v1/builds")?.init.params, + ).toEqual({ query: { projectId: "proj_1", limit: 1 } }); + expect(calls.at(-1)?.init.params?.path).toEqual({ buildId: "bld_2" }); + }); + + it("says so when the project has no builds", async () => { + const result = await makeCli( + buildClient({ + "/v1/builds": () => ({ + data: { data: [], pagination: { hasMore: false, nextCursor: null } }, + }), + }), + ).run(["build", "logs", "--json"], { cwd: await linkedCwd() }); + + expect(envelope(result.json)).toMatchObject({ + ok: false, + error: { + code: "BUILD.NONE", + summary: "Project Billing has no builds yet", + }, + }); + }); + + it("prints only the error lines with --errors", async () => { + const result = await makeCli(buildClient()).run( + ["build", "logs", "bld_2", "--errors"], + { isTty: { stdout: true } }, + ); + + expect(result.presented?.presentation.stdout).toEqual(LOG.errors); + }); + + it("asks the API for the last lines with --tail", async () => { + const calls: Call[] = []; + await makeCli(buildClient({}, calls)).run( + ["build", "logs", "bld_2", "--tail", "50"], + { isTty: { stdout: true } }, + ); + + expect(calls.at(-1)?.init.params).toEqual({ + path: { buildId: "bld_2" }, + query: { tail: 50 }, + }); + }); + + it("refuses a --tail the API would refuse, before calling it", async () => { + const calls: Call[] = []; + const result = await makeCli(buildClient({}, calls)).run([ + "build", + "logs", + "bld_2", + "--tail", + "5000", + "--json", + ]); + + expect(envelope(result.json)).toMatchObject({ + ok: false, + error: { code: "BUILD.USAGE_ERROR" }, + }); + expect(calls).toEqual([]); + }); + + it("passes on the API's reason when GitHub limits requests", async () => { + const result = await makeCli( + buildClient({ + "/v1/builds/{buildId}/logs": () => ({ + error: { + error: { + code: "upstreamUnavailable", + message: + "GitHub is limiting requests from the Prisma GitHub App on acme/billing. Try again in 30 seconds.", + }, + }, + response: new Response(null, { status: 503 }), + }), + }), + ).run(["build", "logs", "bld_2", "--json"]); + + expect(envelope(result.json)).toMatchObject({ + ok: false, + error: { + code: "BUILD.API_ERROR", + why: "GitHub is limiting requests from the Prisma GitHub App on acme/billing. Try again in 30 seconds.", + meta: { status: 503 }, + }, + }); + }); +}); diff --git a/packages/cli/tests/domain-guidance.test.ts b/packages/cli/tests/domain-guidance.test.ts index abf014ce4..b16ab8986 100644 --- a/packages/cli/tests/domain-guidance.test.ts +++ b/packages/cli/tests/domain-guidance.test.ts @@ -63,6 +63,14 @@ describe("domainStateGuidance", () => { }); }); + it("asks to add the hostname again when no domain ownership covers it", () => { + expect(guidance(input({ state: "no_domain_ownership" }))).toEqual({ + failed: false, + waitingOn: "No domain ownership in this workspace covers the hostname.", + fix: "Delete the hostname, then add it again: adding it creates the domain ownership.", + }); + }); + it("says the service is gone", () => { expect(guidance(input({ state: "no_service" }))).toEqual({ failed: false, @@ -257,6 +265,12 @@ const STATES: ReadonlyArray<{ waitsOnPlatform: boolean; stuck: boolean; }> = [ + { + state: "no_domain_ownership", + waitsForDns: false, + waitsOnPlatform: false, + stuck: true, + }, { state: "not_verified", waitsForDns: true, diff --git a/packages/cli/tests/helpers/routing-url.ts b/packages/cli/tests/helpers/routing-url.ts index 22999c294..98d553ba2 100644 --- a/packages/cli/tests/helpers/routing-url.ts +++ b/packages/cli/tests/helpers/routing-url.ts @@ -47,6 +47,7 @@ export function domainRecord(overrides: Partial = {}): RawDomain { heldBy: null, customDomain: null, customDomainSyncError: null, + certificateLimitResetsAt: null, switchboardDns: null, setupUrl: "https://console.prisma.io/ws_1/proj_1/compute/svc_1/domains?setup=shop.acme.com", diff --git a/packages/cli/tests/mount-coverage.test.ts b/packages/cli/tests/mount-coverage.test.ts index 4c059f80b..ff0b0aaaf 100644 --- a/packages/cli/tests/mount-coverage.test.ts +++ b/packages/cli/tests/mount-coverage.test.ts @@ -89,6 +89,8 @@ const EXPECTED_MOUNT_PATHS: readonly string[] = [ "bucket key delete", "bucket key list", "bucket list", + "build list", + "build logs", "contract emit", "contract format", "contract infer", diff --git a/packages/prisma/package.json b/packages/prisma/package.json index 4bc4a148d..8f07c658c 100644 --- a/packages/prisma/package.json +++ b/packages/prisma/package.json @@ -55,7 +55,7 @@ "@prisma/composer-cli": "0.41.2", "@prisma/composer-prisma-cloud": "0.41.2", "@prisma/compute-sdk": "0.47.0", - "@prisma/management-api-sdk": "1.101.0", + "@prisma/management-api-sdk": "1.110.0", "@prisma/orm-family-sql": "8.0.0-rc.28", "@prisma/orm-framework": "8.0.0-rc.28", "@prisma/orm-postgres": "8.0.0-rc.28", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 88173e223..6b43c5103 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -43,10 +43,10 @@ importers: version: 0.41.2(@prisma/cli-engine@packages+cli-engine)(@prisma/orm-framework@8.0.0-rc.28(typescript@6.0.3))(@prisma/orm-postgres@8.0.0-rc.28(3dbbfdcbfcebb8ddc677798d02eba024))(@types/pg@8.23.1)(@vercel/nft@1.10.2(rollup@4.62.2))(magicast@0.5.3)(pg@8.23.1)(redis@6.4.0)(tsx@4.22.4)(typescript@6.0.3)(unrun@0.2.39)(vite@7.3.5(@types/node@22.19.19)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.1))(ws@8.23.1) '@prisma/compute-sdk': specifier: 0.47.0 - version: 0.47.0(@prisma/management-api-sdk@1.101.0)(rollup@4.62.2) + version: 0.47.0(@prisma/management-api-sdk@1.110.0)(rollup@4.62.2) '@prisma/management-api-sdk': - specifier: 1.101.0 - version: 1.101.0 + specifier: 1.110.0 + version: 1.110.0 '@prisma/orm-family-sql': specifier: 8.0.0-rc.28 version: 8.0.0-rc.28(@prisma/orm-framework@8.0.0-rc.28(typescript@6.0.3))(@prisma/orm-toolchain@8.0.0-rc.28(@prisma/cli-engine@packages+cli-engine)(@prisma/orm-framework@8.0.0-rc.28(typescript@6.0.3))(magicast@0.5.3)(typescript@6.0.3))(typescript@6.0.3) @@ -158,8 +158,8 @@ importers: version: 8.2.2 devDependencies: '@prisma/management-api-sdk': - specifier: 1.101.0 - version: 1.101.0 + specifier: 1.110.0 + version: 1.110.0 '@repo/cli-conformance': specifier: workspace:8.0.0-rc.39 version: link:../cli-conformance @@ -241,10 +241,10 @@ importers: version: 0.41.2(@prisma/cli-engine@packages+cli-engine)(@prisma/orm-framework@8.0.0-rc.28(typescript@6.0.3))(@prisma/orm-postgres@8.0.0-rc.28(3dbbfdcbfcebb8ddc677798d02eba024))(@types/pg@8.23.1)(@vercel/nft@1.10.2(rollup@4.62.2))(magicast@0.5.3)(pg@8.23.1)(redis@6.4.0)(tsx@4.22.4)(typescript@6.0.3)(unrun@0.2.39)(vite@7.3.5(@types/node@22.19.19)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.1))(ws@8.23.1) '@prisma/compute-sdk': specifier: 0.47.0 - version: 0.47.0(@prisma/management-api-sdk@1.101.0)(rollup@4.62.2) + version: 0.47.0(@prisma/management-api-sdk@1.110.0)(rollup@4.62.2) '@prisma/management-api-sdk': - specifier: 1.101.0 - version: 1.101.0 + specifier: 1.110.0 + version: 1.110.0 '@prisma/orm-family-sql': specifier: 8.0.0-rc.28 version: 8.0.0-rc.28(@prisma/orm-framework@8.0.0-rc.28(typescript@6.0.3))(@prisma/orm-toolchain@8.0.0-rc.28(@prisma/cli-engine@packages+cli-engine)(@prisma/orm-framework@8.0.0-rc.28(typescript@6.0.3))(magicast@0.5.3)(typescript@6.0.3))(typescript@6.0.3) @@ -936,6 +936,9 @@ packages: '@prisma/management-api-sdk@1.101.0': resolution: {integrity: sha512-q06lds4gANEm78l4kZxjMxJcIXAEjj6IeC/9DzASnubaEZuaf1rgvBIpyaK5//iEx6L2gsEHbzQzY4d/p87SZw==} + '@prisma/management-api-sdk@1.110.0': + resolution: {integrity: sha512-Ub3bPtdJ/HztGpOY1debO0H6p7XneRY3Y8eCQcjaTy4T8mUcXxt8drvzhenK4hL9RfacudpszRHehTYolQ5xsA==} + '@prisma/orm-family-sql@8.0.0-rc.28': resolution: {integrity: sha512-5/bR+cREch3///KetNtFQUidkPqmHiZO9oi3H141lZzpfkJZIBX/ISm5MLOzt17ia8Rhg/YtKO6JLEshTzgxpw==} peerDependencies: @@ -3350,9 +3353,9 @@ snapshots: - vite - ws - '@prisma/compute-sdk@0.47.0(@prisma/management-api-sdk@1.101.0)(rollup@4.62.2)': + '@prisma/compute-sdk@0.47.0(@prisma/management-api-sdk@1.110.0)(rollup@4.62.2)': dependencies: - '@prisma/management-api-sdk': 1.101.0 + '@prisma/management-api-sdk': 1.110.0 '@vercel/nft': 1.10.2(rollup@4.62.2) better-result: 2.9.2 jiti: 2.7.0 @@ -3408,6 +3411,10 @@ snapshots: dependencies: openapi-fetch: 0.14.0 + '@prisma/management-api-sdk@1.110.0': + dependencies: + openapi-fetch: 0.14.0 + '@prisma/orm-family-sql@8.0.0-rc.28(@prisma/orm-framework@8.0.0-rc.28(typescript@6.0.3))(@prisma/orm-toolchain@8.0.0-rc.28(@prisma/cli-engine@packages+cli-engine)(@prisma/orm-framework@8.0.0-rc.28(typescript@6.0.3))(magicast@0.5.3)(typescript@6.0.3))(typescript@6.0.3)': dependencies: '@prisma/orm-framework': 8.0.0-rc.28(typescript@6.0.3) diff --git a/scripts/list-error-codes.mjs b/scripts/list-error-codes.mjs index 242ae82b4..232156589 100644 --- a/scripts/list-error-codes.mjs +++ b/scripts/list-error-codes.mjs @@ -30,6 +30,7 @@ const NAMESPACES = [ "AUTH", "BRANCH", "BUCKET", + "BUILD", "CLI", "DEPLOY", "FEEDBACK",