Skip to content

Commit ac46456

Browse files
Merge pull request #18 from prisma/feat/stream-deploy-output
feat: stream the deploy output while it runs
2 parents 8cef831 + 40fa6ee commit ac46456

3 files changed

Lines changed: 130 additions & 13 deletions

File tree

‎main.mjs‎

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,10 @@ import {
1313
import { resolveCredential } from "./credentials.mjs";
1414
import { deployedUrlsFromOutput } from "./deployment.mjs";
1515
import { failurePatch, guardReport, makeReporter, mapPhase } from "./report.mjs";
16+
import { runCommand } from "./run.mjs";
1617

17-
// Synchronous stdout keeps ::group:: markers ordered around child output:
18-
// spawnSync blocks the event loop, so buffered async writes would flush late.
18+
// Synchronous stdout keeps ::group:: markers ordered around child output,
19+
// which reaches fd 1 directly or through runCommand's synchronous writes.
1920
const log = (line) => writeSync(1, `${line}\n`);
2021

2122
const input = (name) => (process.env[`INPUT_${name.toUpperCase()}`] ?? "").trim();
@@ -83,16 +84,7 @@ async function runPhase(phase, command, args, capture = false) {
8384
// String commands come from the consuming repo's own workflow inputs and
8485
// run through a shell verbatim; argv arrays never touch a shell, so
8586
// event-controlled values like the stage name cannot inject.
86-
const stdio = capture ? ["inherit", "pipe", "inherit"] : "inherit";
87-
// maxBuffer raised so a large but successful deploy is not misreported as a spawn failure.
88-
const options = capture
89-
? { cwd: workdir, stdio, maxBuffer: 64 * 1024 * 1024 }
90-
: { cwd: workdir, stdio };
91-
const result = args
92-
? spawnSync(command, args, options)
93-
: spawnSync(command, { ...options, shell: true });
94-
const captured = capture && result.stdout ? result.stdout.toString() : "";
95-
if (captured) writeSync(1, captured);
87+
const result = await runCommand(command, args, { cwd: workdir, capture });
9688
log("::endgroup::");
9789
if (result.status !== 0) {
9890
const error =
@@ -102,7 +94,7 @@ async function runPhase(phase, command, args, capture = false) {
10294
: `${printable} exited with status ${result.status}`);
10395
await fail(phase, error);
10496
}
105-
return captured;
97+
return result.stdout;
10698
}
10799

108100
const mode = input("mode") || "deploy";

‎run.mjs‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { spawn } from "node:child_process";
2+
import { writeSync } from "node:fs";
3+
4+
/**
5+
* Runs a command and resolves once it has exited. An argv array never
6+
* touches a shell; a string command (args null) runs through one verbatim.
7+
*
8+
* With `capture`, stdout is piped: each chunk is written to the job log as it
9+
* arrives and also collected, so the caller can parse the full output. stdin
10+
* and stderr stay inherited, so the child writes them to the log directly.
11+
*
12+
* @returns {Promise<{ status?: number | null, signal?: string | null, error?: Error, stdout: string }>}
13+
*/
14+
export async function runCommand(command, args, { cwd, capture = false }) {
15+
const options = { cwd, stdio: capture ? ["inherit", "pipe", "inherit"] : "inherit" };
16+
const child = args ? spawn(command, args, options) : spawn(command, { ...options, shell: true });
17+
const chunks = [];
18+
child.stdout?.on("data", (chunk) => {
19+
chunks.push(chunk);
20+
writeSync(1, chunk);
21+
});
22+
// A spawn failure emits "error" and then "close"; the first event wins.
23+
const result = await new Promise((done) => {
24+
child.on("error", (error) => done({ error }));
25+
child.on("close", (status, signal) => done({ status, signal }));
26+
});
27+
const stdout = Buffer.concat(chunks).toString();
28+
// Ends a partial last line so the next log line, such as ::endgroup::, starts on its own line.
29+
if (stdout && !stdout.endsWith("\n")) writeSync(1, "\n");
30+
return { ...result, stdout };
31+
}

‎tests/run.test.mjs‎

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
import assert from "node:assert/strict";
2+
import { spawn } from "node:child_process";
3+
import { test } from "node:test";
4+
import { deployedUrlsFromOutput } from "../deployment.mjs";
5+
import { runCommand } from "../run.mjs";
6+
7+
const RUN_MODULE = new URL("../run.mjs", import.meta.url).href;
8+
9+
// Runs a fake command through runCommand in a separate Node process, so its
10+
// fd 1 writes can be observed as they happen. Resolves with every stdout chunk
11+
// the wrapper wrote, each stamped with its arrival time, and the result.
12+
function runFake(fakeScript, { capture = true } = {}) {
13+
const wrapper = `
14+
import { runCommand } from ${JSON.stringify(RUN_MODULE)};
15+
import { writeFileSync } from "node:fs";
16+
const result = await runCommand(process.execPath, ["-e", ${JSON.stringify(fakeScript)}], { cwd: process.cwd(), capture: ${capture} });
17+
writeFileSync(3, JSON.stringify({ ...result, error: result.error?.code }));
18+
`;
19+
const child = spawn(process.execPath, ["--input-type=module", "-e", wrapper], {
20+
stdio: ["ignore", "pipe", "inherit", "pipe"],
21+
});
22+
const writes = [];
23+
let resultJson = "";
24+
child.stdout.on("data", (chunk) => writes.push({ at: Date.now(), text: chunk.toString() }));
25+
child.stdio[3].on("data", (chunk) => {
26+
resultJson += chunk;
27+
});
28+
return new Promise((done) => {
29+
child.on("close", () => done({ writes, result: JSON.parse(resultJson) }));
30+
});
31+
}
32+
33+
test("writes each stdout line to the log before the command exits", async () => {
34+
const { writes, result } = await runFake(
35+
'console.log("first"); setTimeout(() => console.log("second"), 500);',
36+
);
37+
const first = writes.find((w) => w.text.includes("first"));
38+
const second = writes.find((w) => w.text.includes("second"));
39+
assert.ok(first && second);
40+
assert.ok(!first.text.includes("second"), "first and second arrived in one write");
41+
assert.ok(second.at - first.at >= 300, `second arrived ${second.at - first.at}ms after first`);
42+
assert.equal(result.stdout, "first\nsecond\n");
43+
assert.equal(result.status, 0);
44+
});
45+
46+
test("collects a result line split across writes and parses it as before", async () => {
47+
const line = JSON.stringify({
48+
kind: "result",
49+
envelope: {
50+
commandId: "deploy",
51+
result: {
52+
summary: {
53+
nodes: [{ address: "app", entities: [{ kind: "compute-service", url: "https://abc.ewr.prisma.build" }] }],
54+
},
55+
},
56+
},
57+
});
58+
const half = Math.floor(line.length / 2);
59+
const { writes, result } = await runFake(
60+
`process.stdout.write(${JSON.stringify(`deploying\n${line.slice(0, half)}`)});
61+
setTimeout(() => process.stdout.write(${JSON.stringify(line.slice(half))}), 200);`,
62+
);
63+
assert.equal(result.stdout, `deploying\n${line}`);
64+
assert.deepEqual(deployedUrlsFromOutput(result.stdout), {
65+
urls: { app: "https://abc.ewr.prisma.build" },
66+
url: "https://abc.ewr.prisma.build",
67+
});
68+
// The partial last line is ended in the log, but not in the collected stdout.
69+
assert.equal(writes.map((w) => w.text).join(""), `deploying\n${line}\n`);
70+
});
71+
72+
test("returns the exit status of a failing command", async () => {
73+
const { result } = await runFake('console.log("boom"); process.exit(3);');
74+
assert.equal(result.status, 3);
75+
assert.equal(result.stdout, "boom\n");
76+
});
77+
78+
test("returns the signal of a killed command", async () => {
79+
const { result } = await runFake('process.kill(process.pid, "SIGTERM");');
80+
assert.equal(result.status, null);
81+
assert.equal(result.signal, "SIGTERM");
82+
});
83+
84+
test("returns no stdout when output is not captured", async () => {
85+
const { writes, result } = await runFake('console.log("inherited");', { capture: false });
86+
assert.equal(result.stdout, "");
87+
assert.equal(writes.map((w) => w.text).join(""), "inherited\n");
88+
});
89+
90+
test("returns the spawn error for a missing command", async () => {
91+
const result = await runCommand("no-such-command-for-run-test", [], { cwd: process.cwd(), capture: true });
92+
assert.equal(result.error?.code, "ENOENT");
93+
assert.equal(result.stdout, "");
94+
});

0 commit comments

Comments
 (0)