diff --git a/.github/workflows/test-npm-build.yml b/.github/workflows/test-npm-build.yml index 0c095607..f2a80c92 100644 --- a/.github/workflows/test-npm-build.yml +++ b/.github/workflows/test-npm-build.yml @@ -33,3 +33,20 @@ jobs: run: | chmod +x test-scripts/test-npm-build.sh ./test-scripts/test-npm-build.sh + + test-npm-shim: + strategy: + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + steps: + - name: Code checkout + uses: actions/checkout@v4 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: "20.x" + + - name: Run npm shim tests + run: npm test diff --git a/bin/hookdeck.js b/bin/hookdeck.js index 7c921aa0..a6a3d90f 100755 --- a/bin/hookdeck.js +++ b/bin/hookdeck.js @@ -1,5 +1,5 @@ #!/usr/bin/env node -const { execFileSync } = require('child_process'); +const { spawn } = require('child_process'); const { existsSync } = require('fs'); const path = require('path'); @@ -28,10 +28,35 @@ if (!existsSync(binaryPath)) { process.exit(1); } -try { - execFileSync(binaryPath, process.argv.slice(2), { stdio: 'inherit' }); -} catch (error) { - // execFileSync will exit with the same code as the binary - // If there's an error executing, exit with code 1 - process.exit(error.status ?? 1); -} +// Use spawn (not execFileSync) so the Node event loop stays free to receive signals and +// forward them to the CLI; otherwise `kill ` / `docker stop` would never reach it. +const child = spawn(binaryPath, process.argv.slice(2), { stdio: 'inherit' }); + +const forwardedSignals = ['SIGINT', 'SIGTERM', 'SIGHUP']; +const handlers = {}; +forwardedSignals.forEach((sig) => { + handlers[sig] = () => { + try { + child.kill(sig); + } catch (e) { + // child already gone + } + }; + process.on(sig, handlers[sig]); +}); + +child.on('error', (error) => { + console.error(`Error: failed to run ${binaryPath}: ${error.message}`); + process.exit(1); +}); + +child.on('exit', (code, signal) => { + if (signal) { + // Mirror the child's fate: re-raise the signal with default handling so the parent + // sees the same termination status. + forwardedSignals.forEach((sig) => process.removeListener(sig, handlers[sig])); + process.kill(process.pid, signal); + return; + } + process.exit(code ?? 1); +}); diff --git a/package.json b/package.json index 62a51ec4..bbb827e5 100644 --- a/package.json +++ b/package.json @@ -22,6 +22,8 @@ "bin/", "binaries/" ], - "scripts": {}, + "scripts": { + "test": "node --test test-scripts/npm-shim.test.js" + }, "dependencies": {} } \ No newline at end of file diff --git a/test-scripts/npm-shim.test.js b/test-scripts/npm-shim.test.js new file mode 100644 index 00000000..db294e16 --- /dev/null +++ b/test-scripts/npm-shim.test.js @@ -0,0 +1,66 @@ +// Tests for bin/hookdeck.js (the npm shim). No dependencies: `npm test` +const { test } = require('node:test'); +const assert = require('node:assert'); +const { spawn } = require('node:child_process'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); + +const archMap = { x64: 'amd64', arm64: 'arm64', ia32: '386' }; + +// Lay out the shim and its fixture as they would appear in the npm package. +function setup(t) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hookdeck-shim-')); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + fs.mkdirSync(path.join(dir, 'bin')); + fs.copyFileSync(path.join(__dirname, '..', 'bin', 'hookdeck.js'), path.join(dir, 'bin', 'hookdeck.js')); + const binDir = path.join(dir, 'binaries', `${process.platform}-${archMap[process.arch] || process.arch}`); + fs.mkdirSync(binDir, { recursive: true }); + const bin = path.join(binDir, process.platform === 'win32' ? 'hookdeck.exe' : 'hookdeck'); + return { bin, shim: path.join(dir, 'bin', 'hookdeck.js') }; +} + +function run(shim, args) { + const child = spawn(process.execPath, [shim, ...args], { stdio: ['ignore', 'pipe', 'pipe'] }); + let out = ''; + child.stdout.on('data', (d) => (out += d)); + return { child, done: new Promise((resolve) => child.on('close', (code, signal) => resolve({ code, signal, out }))) }; +} + +test('propagates exit code and arguments', async (t) => { + const { bin, shim } = setup(t); + // Use a native executable on each platform. Node runs the fixture passed through the shim. + fs.copyFileSync(process.execPath, bin); + const fixture = path.join(path.dirname(bin), 'fixture.js'); + fs.writeFileSync(fixture, 'console.log(JSON.stringify(process.argv.slice(2))); process.exitCode = 7;\n'); + const args = ['listen', 'with spaces', '', 'a"b']; + const { code, out } = await run(shim, [fixture, ...args]).done; + assert.strictEqual(code, 7); + assert.deepStrictEqual(JSON.parse(out), args); +}); + +for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP']) { + test(`forwards ${sig} to the CLI process`, { skip: process.platform === 'win32' }, async (t) => { + // The fake binary records the signal it receives and exits 0 on it. It also gives up + // after ~5s so it never outlives the test if the signal is not forwarded. + const { bin, shim } = setup(t); + fs.writeFileSync(bin, + `#!/bin/sh\ntrap 'echo got-${sig} > "${'$'}(dirname "${'$'}0")/got"; exit 0' ${sig.slice(3)}\n` + + `echo ready > "${'$'}(dirname "${'$'}0")/ready"\ni=0; while [ $i -lt 50 ]; do sleep 0.1; i=$((i+1)); done\n`, + { mode: 0o755 } + ); + const got = path.dirname(bin); + const child = spawn(process.execPath, [shim], { stdio: 'ignore' }); + const exited = new Promise((resolve) => child.on('exit', resolve)); + for (let i = 0; i < 100 && !fs.existsSync(path.join(got, 'ready')); i++) { + await new Promise((r) => setTimeout(r, 50)); + } + child.kill(sig); + await Promise.race([exited, new Promise((r) => setTimeout(r, 3000))]); + await new Promise((r) => setTimeout(r, 300)); + const received = fs.existsSync(path.join(got, 'got')) ? fs.readFileSync(path.join(got, 'got'), 'utf8').trim() : ''; + // let a non-forwarded fake binary time out on its own before removing its directory + child.kill('SIGKILL'); + assert.strictEqual(received, `got-${sig}`); + }); +}