Repository navigation
Expand file tree
/
Copy pathmain.mjs
More file actions
418 lines (387 loc) · 18.3 KB
/
Copy pathmain.mjs
File metadata and controls
418 lines (387 loc) · 18.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
// prisma/cloud-deploy-action: install, build, and deploy (or destroy) a
// Prisma Composer app, or deploy a repository with no Composer module
// (single-app mode), reporting the attempt to the Builds API when a
// credential is available. Interface and behaviors are frozen by ./README.md.
import { spawnSync } from "node:child_process";
import { appendFileSync, existsSync, readFileSync, writeSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { selectBuildCommand } from "./build.mjs";
import {
MINIMUM_BUN_VERSION,
composerArguments,
deploysWithoutComposerModule,
findLocalPrismaCli,
isSupportedBunVersion,
nearestDirectoryWith,
selectPrismaCliCommand,
singleAppCliCommand,
} from "./cli.mjs";
import { resolveCredential } from "./credentials.mjs";
import { deployedUrlsFromOutput, deployedUrlsFromReport } from "./deployment.mjs";
import { readRunReport, renderJobSummary } from "./summary.mjs";
import { failurePatch, guardReport, makeReporter, mapPhase, reportEarlyFailure } from "./report.mjs";
import { runCommand } from "./run.mjs";
// Synchronous stdout keeps ::group:: markers ordered around child output,
// which reaches fd 1 directly or through runCommand's synchronous writes.
const log = (line) => writeSync(1, `${line}\n`);
const input = (name) => (process.env[`INPUT_${name.toUpperCase()}`] ?? "").trim();
const setOutput = (name, value) => appendFileSync(process.env.GITHUB_OUTPUT, `${name}=${value}\n`);
const saveState = (name, value) => appendFileSync(process.env.GITHUB_STATE, `${name}=${value}\n`);
const STUB_BUILD_ID = `build_stub_${process.env.GITHUB_RUN_ID}`;
const startedAt = Date.now();
let reportWarningLogged = false;
const warnAboutReport = (message) => {
if (!reportWarningLogged) log(`::warning::${message}`);
reportWarningLogged = true;
};
let reporter = null;
let buildId = null;
let firstPhaseReported = false;
// Called once on every exit path. A job summary error is logged, never fatal.
function finish(outcome, { cause, urls } = {}) {
setOutput("outcome", outcome);
saveState("finalOutcome", outcome);
try {
const report = readRunReport(reportPath, startedAt, warnAboutReport);
if (report) setOutput("report-path", reportPath);
if (process.env.GITHUB_STEP_SUMMARY) {
const summary = renderJobSummary({
outcome,
mode,
environment,
sha: process.env.GITHUB_SHA,
ref: branch,
buildId,
report,
reportPath,
urls,
cause,
});
appendFileSync(process.env.GITHUB_STEP_SUMMARY, summary);
}
} catch (error) {
log(`::warning::could not write the job summary: ${error.message}`);
}
}
async function reportUpdate(patch, label) {
// guardReport returns null on failure (it already logged a warning).
// update() returns void on success, so a non-null result means succeeded.
const result = await guardReport(() => reporter.update(buildId, patch), label, log);
if (result !== null) log(`report: ${label}`);
}
// Fails after a build report has been created: sends a failure state update,
// records the outcome, then exits non-zero. On the deploy/destroy phase the
// Prisma CLI reports its own, more precise failure first; failurePatch keeps it.
async function fail(failingStep, errorText) {
if (reporter && buildId) {
const existing =
failingStep === mode
? await guardReport(() => reporter.get(buildId), "read before failed", log)
: null;
const result = await guardReport(
() => reporter.update(buildId, failurePatch(existing, failingStep, errorText)),
"failed",
log,
);
if (result !== null) log("report: failed");
}
finish("failed", { cause: `${failingStep} failed: ${errorText}` });
log(`::error::${failingStep} failed: ${errorText}`);
process.exit(1);
}
// Fails before the action has created its build report. The platform holds
// a queued build for this run, and without a report it would only say the
// run "finished without reporting", so the cause is reported to it first.
async function failEarly(failingStep, errorText) {
const reportedId = await reportEarlyFailure({
env: process.env,
apiUrl,
createPayload: buildReport,
failingStep,
errorText,
log,
});
if (reportedId) {
buildId = reportedId;
setOutput("build-id", reportedId);
}
finish("failed", { cause: `${failingStep} failed: ${errorText}` });
log(`::error::${failingStep} failed: ${errorText}`);
process.exit(1);
}
async function runPhase(phase, command, args, capture = false, cwd = workdir) {
const serverPhase = mapPhase(phase);
log(`::group::${phase}`);
if (reporter && buildId) {
const patch = firstPhaseReported
? { phase: serverPhase }
: { phase: serverPhase, state: "running" };
firstPhaseReported = true;
await reportUpdate(patch, `phase ${serverPhase}`);
}
const printable = args ? [command, ...args].join(" ") : command;
log(`$ ${printable}`);
// String commands come from the consuming repo's own workflow inputs and
// run through a shell verbatim; argv arrays never touch a shell, so
// event-controlled values like the environment name cannot inject.
const result = await runCommand(command, args, { cwd, capture });
log("::endgroup::");
if (result.status !== 0) {
const error =
result.error?.message ??
(result.signal
? `${printable} was terminated by ${result.signal}`
: `${printable} exited with status ${result.status}`);
await fail(phase, error);
}
return result.stdout;
}
const mode = input("mode") || "deploy";
const modulePath = input("module") || "module.ts";
const prismaVersion = input("prisma-version");
const workdir = resolve(process.env.GITHUB_WORKSPACE ?? ".", input("working-directory") || ".");
// Single-app mode: the repository has no Composer module. The Prisma CLI works
// out how to build and start the Service, builds it, and deploys it.
const singleApp = !input("module") && !existsSync(join(workdir, modulePath));
const repository = process.env.GITHUB_REPOSITORY ?? "";
const branch = process.env.GITHUB_HEAD_REF || process.env.GITHUB_REF_NAME || "";
const runUrl = `${process.env.GITHUB_SERVER_URL ?? "https://github.com"}/${repository}/actions/runs/${process.env.GITHUB_RUN_ID}`;
const apiUrl = input("api-url") || "https://api.prisma.io";
// The run identity lets this report converge on the build the platform
// already queued for the run, instead of creating a second one.
const buildReport = {
source: "ci",
commitSha: process.env.GITHUB_SHA ?? "",
branchName: branch,
runIdentity: {
provider: "github",
repositoryId: process.env.GITHUB_REPOSITORY_ID ?? "",
runId: process.env.GITHUB_RUN_ID ?? "",
runAttempt: parseInt(process.env.GITHUB_RUN_ATTEMPT ?? "1", 10),
},
externalLogUrl: runUrl,
};
// The deploy writes its run report here; a path the workflow already set is kept.
process.env.PRISMA_COMPOSER_REPORT_FILE ||= join(process.env.RUNNER_TEMP || tmpdir(), "prisma-deploy-report.json");
// The CLI resolves a relative path against its cwd, which is workdir.
const reportPath = resolve(workdir, process.env.PRISMA_COMPOSER_REPORT_FILE);
log(
singleApp
? `prisma-deploy: mode=${mode} single-app mode (no Composer module) working-directory=${workdir}`
: `prisma-deploy: mode=${mode} module=${modulePath} working-directory=${workdir}`,
);
// Every exit path leaves valid JSON for fromJSON(); a deploy overwrites it (last write wins).
setOutput("urls", "{}");
const defaultBranch = (() => {
try {
const event = JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH, "utf8"));
return event.repository?.default_branch ?? "";
} catch {
return "";
}
})();
// `stage` is the input's name from before the CLI renamed stages to environments.
const explicitEnvironment = input("environment") || input("stage");
// The default branch deploys to production; every other branch deploys to an
// environment named after it.
const environment = explicitEnvironment || (branch === defaultBranch ? "" : branch);
if (input("environment") && input("stage") && input("environment") !== input("stage")) {
await failEarly(
"config",
`the environment input ("${input("environment")}") and its older name, the stage input ("${input("stage")}"), disagree; set only environment`,
);
}
if (mode !== "deploy" && mode !== "destroy") {
await failEarly("config", `unknown mode "${mode}" (expected "deploy" or "destroy")`);
}
if (!explicitEnvironment && !branch) {
await failEarly("config", "cannot derive an environment: the event context has no branch; set the environment input");
}
if (mode === "destroy" && !environment) {
await failEarly(
"config",
"destroy refuses to run without a resolved environment; the default branch derives to production, so pass the environment input explicitly",
);
}
log(environment ? `${mode} target: environment ${environment}` : `${mode} target: production (default branch)`);
if (singleApp && mode === "destroy") {
await failEarly(
"config",
"destroy is not supported for a repository without a Composer module; delete the branch or the Service in the Prisma Console",
);
}
// Bun is required: composer runs under Bun, not Node. The generated Prisma
// deploy workflow adds `oven-sh/setup-bun@v2` for every project.
// Single-app mode runs the CLI under Node.js, so it does not check for Bun.
const bunVersionCheck = singleApp ? null : spawnSync("bun", ["--version"], { stdio: "pipe" });
if (bunVersionCheck?.error?.code === "ENOENT") {
await failEarly(
"config",
"bun not found on PATH: add `- uses: oven-sh/setup-bun@v2` before this action step; the generated Prisma deploy workflow includes this automatically",
);
}
// Version guard: Bun <= 1.3.9 omits Content-Length on the CLI's artifact
// upload, failing every deploy with an opaque HTTP 411 — name the cause
// here instead. An unreadable version is only a warning; the guard must
// never break a working deploy over output formatting.
const bunVersion = ((bunVersionCheck?.stdout ?? "").toString().match(/\d+\.\d+\.\d+/) ?? [null])[0];
if (singleApp) {
// No Bun version to check.
} else if (bunVersion === null) {
log("::warning::could not determine the bun version; continuing without the compatibility check");
} else if (!isSupportedBunVersion(bunVersion)) {
await failEarly(
"config",
`bun ${bunVersion} is too old: bun <= 1.3.9 omits Content-Length on the deploy's artifact upload, so it fails with HTTP 411. Use bun >= ${MINIMUM_BUN_VERSION} — setup-bun installs the latest by default, so look for an old pin in package.json's \`packageManager\`, a .bun-version file, or the setup step's bun-version input.`,
);
}
if (!singleApp && input("name")) {
log("::warning::the name input is only used in single-app mode; a Composer module states its own name");
}
const repositoryRoot = resolve(process.env.GITHUB_WORKSPACE ?? ".");
// The CLI reads prisma.config.ts before it runs a command, and the file imports
// the repository's own packages. So single-app mode installs first when there is one.
const singleAppWithConfig =
singleApp && nearestDirectoryWith(["prisma.config.ts"], workdir, repositoryRoot) !== null;
// The CLI also reads a config file above the working directory, which imports the packages of the folder with the lockfile.
const lockfileDir = singleAppWithConfig
? (nearestDirectoryWith(["bun.lock", "bun.lockb", "package-lock.json", "pnpm-lock.yaml", "yarn.lock"], workdir, repositoryRoot) ?? workdir)
: workdir;
const installCommand = (() => {
const explicit = input("install-command");
if (explicit) return explicit;
if (existsSync(join(lockfileDir, "bun.lock")) || existsSync(join(lockfileDir, "bun.lockb"))) {
return "bun install --frozen-lockfile";
}
if (existsSync(join(lockfileDir, "package-lock.json"))) return "npm ci";
// Composer mode runs the CLI under Bun and does not support these two.
if (singleAppWithConfig && existsSync(join(lockfileDir, "pnpm-lock.yaml"))) return "pnpm install --frozen-lockfile";
if (singleAppWithConfig && existsSync(join(lockfileDir, "yarn.lock"))) return "yarn install --frozen-lockfile";
return null;
})();
if (!singleApp && !installCommand) {
await failEarly(
"install",
`install-auto-detect-failed: no bun.lock, bun.lockb, or package-lock.json in ${workdir} (pnpm/yarn are out of scope); set the install-command input`,
);
}
// Credential guard: resolved before any reporting and before deploy. Runs
// with no credential path skip reporting entirely and exit successfully without
// deploying. A transient exchange failure (outage) fails the run instead of
// skipping it.
const credential = await (async () => {
try {
return await resolveCredential(process.env, apiUrl);
} catch (error) {
finish("failed", { cause: `credential failed: ${error.message}` });
log(`::error::credential failed: ${error.message}`);
process.exit(1);
}
})();
if (credential.source === "none" || credential.denied) {
const remedy = credential.denied
? "This repository is not connected to a Prisma workspace. Connect it in the Prisma Console, or set PRISMA_SERVICE_TOKEN as an Actions secret."
: "Connect the repository in the Prisma Console and grant this job `permissions: id-token: write`, or set PRISMA_SERVICE_TOKEN as an Actions secret.";
log(`::notice title=${mode} skipped, no credential::The action cannot ${mode} without a credential. ${remedy}`);
setOutput("build-id", STUB_BUILD_ID);
finish("skipped-no-credential");
process.exit(0);
}
if (credential.source === "oidc") {
log(`::add-mask::${credential.token}`);
process.env.PRISMA_SERVICE_TOKEN = credential.token;
process.env.PRISMA_WORKSPACE_ID = credential.workspaceId;
log("credential: short-lived workspace token via GitHub OIDC");
}
reporter = makeReporter({ apiUrl, token: credential.token });
// Create the build report. A failure here is a warning, not a deploy blocker.
buildId = await guardReport(() => reporter.create(buildReport), "create", log);
if (buildId) {
log(`report: created ${buildId}`);
setOutput("build-id", buildId);
saveState("buildId", buildId);
// The Prisma CLI reads this and reports into this build instead of creating its own.
process.env.PRISMA_BUILD_ID = buildId;
} else {
setOutput("build-id", STUB_BUILD_ID);
}
let cliCommand;
if (singleApp) {
// The CLI installs and builds the repository, so the action runs neither, except the install a config file needs.
if (input("install-command") && !singleAppWithConfig) {
log("::warning::the install-command input is not used in single-app mode without a prisma.config.ts; the Prisma CLI installs and builds the Service");
}
// action.yml gives build-command the default "npm run build", so only another value shows that the user set it.
if (input("build-command") && input("build-command") !== "npm run build") {
log("::warning::the build-command input is not used in single-app mode; the Prisma CLI builds the Service");
}
let localVersion = null;
if (singleAppWithConfig && installCommand) {
// The install-command input runs in the working directory, as it does for a Composer module.
await runPhase("install", installCommand, undefined, false, input("install-command") ? workdir : lockfileDir);
const localCli = prismaVersion ? null : findLocalPrismaCli(workdir, repositoryRoot);
if (localCli && deploysWithoutComposerModule(localCli.version)) localVersion = localCli.version;
} else if (singleAppWithConfig) {
log(`::warning::found a prisma.config.ts but no lockfile from ${workdir} up to the repository root, so the repository's packages are not installed and the Prisma CLI may fail to read the file; set the install-command input`);
}
// Without the repository's own CLI, no lockfile pins the version, so an unpinned run takes whatever release is newest that day.
if (localVersion === null && !prismaVersion) {
log("::warning::running prisma@latest: set the prisma-version input to an exact version, so that a new CLI release cannot change a deploy unseen");
}
cliCommand = singleAppCliCommand(prismaVersion, environment, input("name"), localVersion);
} else {
await runPhase("install", installCommand);
const localCli = findLocalPrismaCli(workdir, repositoryRoot);
const hasLocalBin = localCli !== null;
if (!hasLocalBin && !prismaVersion) {
await fail(
"config",
`no prisma CLI in node_modules from ${workdir} up to the repository root: add prisma as a devDependency at the version that matches your app's @prisma/composer (the CLI and the app must be on the same Composer version), or set the prisma-version input`,
);
}
// Destroy builds too, by composer's own requirement: "destroy evaluates the
// same stack program as deploy, which packages the built artifacts — so the
// app must be built first" (its error text on 0.6.0). We wanted destroy to
// skip the build so teardown never depends on the default branch's build
// health; composer does not allow that today. `build-command: none` is
// different: the app has no build step at all, so both modes skip the phase.
const buildCommand = selectBuildCommand(input("build-command"));
if (buildCommand === null) {
// Install already reported the server-side "build" phase (mapPhase sends
// install as "build"), so the skip needs no report update of its own.
log("build: skipped (build-command: none)");
} else {
await runPhase("build", buildCommand);
}
// The environment name reaches the argv array straight from the event; it is
// never interpolated into a shell string.
const composerArgs = composerArguments(
mode,
modulePath,
environment,
localCli ? localCli.version : prismaVersion,
);
cliCommand = selectPrismaCliCommand(prismaVersion, hasLocalBin, composerArgs);
}
const [cliCmd, cliArgs, cliLabel] = cliCommand;
log(cliLabel);
const deployOutput = await runPhase(mode, cliCmd, cliArgs, mode === "deploy");
const fromReport = deployedUrlsFromReport(readRunReport(reportPath, startedAt, warnAboutReport));
const { urls, url: deployedUrl } =
mode !== "deploy"
? { urls: {}, url: null }
: Object.keys(fromReport.urls).length > 0
? fromReport
: deployedUrlsFromOutput(deployOutput);
if (mode === "deploy") {
setOutput("url", deployedUrl ?? "");
setOutput("urls", JSON.stringify(urls));
}
if (reporter && buildId) {
await reportUpdate(
deployedUrl ? { state: "succeeded", deployedUrl } : { state: "succeeded" },
"succeeded",
);
}
finish("succeeded", { urls });