diff --git a/packages/void/package.json b/packages/void/package.json index a4733bf90..9c975a898 100644 --- a/packages/void/package.json +++ b/packages/void/package.json @@ -37,6 +37,7 @@ "#self/remote": "./dist/runtime/remote/index.mjs", "#self/remote/binding-handler": "./dist/runtime/remote/binding-handler.mjs", "#self/sandbox": "./dist/runtime/sandbox/index.mjs", + "#self/sandbox.Dockerfile": "./sandbox.Dockerfile", "#self/runtime/live-server": "./dist/runtime/live/server.mjs", "#self/runtime/fetch": "./dist/runtime/client/fetch.mjs", "#self/runtime/fetch-server": "./dist/runtime/client/fetch-server.mjs", diff --git a/packages/void/src/cli/container-image.ts b/packages/void/src/cli/container-image.ts index 174307edc..ae77c0950 100644 --- a/packages/void/src/cli/container-image.ts +++ b/packages/void/src/cli/container-image.ts @@ -2,29 +2,67 @@ import { spawn } from 'node:child_process'; import { randomUUID } from 'node:crypto'; import { dirname } from 'pathslash'; -function docker(args: Array, quiet = false): Promise { - return new Promise((resolve, reject) => { +/** A daemon that does not answer must not keep back the report of a failed build. */ +const DAEMON_TIMEOUT_MS = 5000; + +/** The exit code, the signal that stopped the command, or the error that kept it from starting. */ +type DockerResult = number | NodeJS.Signals | Error; + +/** + * Run a Docker command. With `timeoutMs`, a CLI that is still running by then is killed. That is + * enough for `docker info`, the one command with a deadline: it starts plugins only to read their + * metadata, before it asks the daemon, so it has no child process while it waits. + */ +function docker( + args: Array, + options: { quiet?: boolean; timeoutMs?: number } = {}, +): Promise { + return new Promise((resolve) => { const child = spawn(process.env.WRANGLER_DOCKER_BIN ?? 'docker', args, { - stdio: quiet ? 'ignore' : 'inherit', + stdio: options.quiet ? 'ignore' : 'inherit', + }); + const deadline = + options.timeoutMs === undefined + ? undefined + : setTimeout(() => { + child.kill('SIGKILL'); + }, options.timeoutMs); + const settle = (result: DockerResult) => { + clearTimeout(deadline); + resolve(result); + }; + child.once('error', settle); + child.once('exit', (code, signal) => { + // Node reports exactly one of the two. + settle(code ?? signal ?? 1); }); - child.once('error', reject); - child.once('exit', (code) => - code === 0 - ? resolve() - : reject( - new Error('Sandbox image preparation failed. Start Docker and retry the deployment.'), - ), - ); }); } +/** Say why `docker build` produced no image. */ +async function describeBuildFailure(build: DockerResult, dockerfile: string): Promise { + if (build instanceof Error) { + return `Sandbox image preparation failed: the Docker CLI could not be started (${build.message}). Check that Docker is installed and retry the deployment.`; + } + if (typeof build === 'string') { + return `Sandbox image preparation failed: \`docker build\` was stopped by ${build} for ${dockerfile}.`; + } + // Docker has printed why the build failed. Starting Docker helps only when its daemon is known + // not to answer: a probe that times out or cannot run leaves the build failure as the report. + const daemon = await docker(['info'], { quiet: true, timeoutMs: DAEMON_TIMEOUT_MS }); + if (typeof daemon === 'number' && daemon !== 0) { + return 'Sandbox image preparation failed. Start Docker and retry the deployment.'; + } + return `Sandbox image preparation failed: \`docker build\` exited with code ${build} for ${dockerfile}. See the Docker output above.`; +} + /** Build locally; the pinned cf uploader pushes this tag to the managed registry. */ export async function buildContainerImage( dockerfile: string, buildContext: string = dirname(dockerfile), ): Promise<{ localReference: string; dispose(): Promise }> { const localReference = `void-sandbox-build:${randomUUID()}`; - await docker([ + const build = await docker([ 'build', '--platform', 'linux/amd64', @@ -34,8 +72,13 @@ export async function buildContainerImage( localReference, buildContext, ]); + if (build !== 0) { + throw new Error(await describeBuildFailure(build, dockerfile)); + } return { localReference, - dispose: () => docker(['image', 'rm', localReference], true).catch(() => {}), + dispose: async () => { + await docker(['image', 'rm', localReference], { quiet: true }); + }, }; } diff --git a/packages/void/src/sandbox/config.ts b/packages/void/src/sandbox/config.ts index 00fdf39c1..6c80ef211 100644 --- a/packages/void/src/sandbox/config.ts +++ b/packages/void/src/sandbox/config.ts @@ -42,7 +42,9 @@ export function isSandboxEnabled(config: VoidConfig): boolean { } function getDefaultSandboxImage(): string { - return fileURLToPath(new URL('../../sandbox.Dockerfile', import.meta.resolve('void/sandbox'))); + // Docker reads this file from the installed package. The private import names it in + // package.json, so the path does not depend on where a built module sits in dist. + return fileURLToPath(import.meta.resolve('#self/sandbox.Dockerfile')); } function getDefaultSandboxPlatformImage(): string { diff --git a/packages/void/test/integration/kitchen-sink-build.test.ts b/packages/void/test/integration/kitchen-sink-build.test.ts index e91f96380..afd258979 100644 --- a/packages/void/test/integration/kitchen-sink-build.test.ts +++ b/packages/void/test/integration/kitchen-sink-build.test.ts @@ -1,5 +1,5 @@ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; -import { join } from 'node:path'; +import { join, resolve } from 'node:path'; import spawn from 'cross-spawn'; import { toSlash } from 'pathslash'; import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test'; @@ -141,6 +141,10 @@ describe('playground/kitchen-sink build', () => { class_name: 'SandboxV1', }), ]); + // The playground sets no `sandbox.image`. Docker builds the default image from this path. + const dockerfile: unknown = wranglerConfig.containers[0].images.default.dockerfile; + expect(dockerfile).toMatch(/sandbox\.Dockerfile$/); + expect(existsSync(resolve(dist, 'ssr', String(dockerfile)))).toBe(true); expect(wranglerConfig.migrations).toContainEqual({ tag: 'void-sandbox-v2', new_sqlite_classes: ['SandboxV1'], diff --git a/packages/void/test/unit/config.test.ts b/packages/void/test/unit/config.test.ts index 2829f8e03..c6d7edae6 100644 --- a/packages/void/test/unit/config.test.ts +++ b/packages/void/test/unit/config.test.ts @@ -513,6 +513,11 @@ describe('readConfig', () => { const config = resolveSandboxConfig({ sandbox: true }, tmpDir); expect(config.image).toMatch(/sandbox\.Dockerfile$/); + // Docker reads this path during `vp dev` and native deploys, so it must name the file the + // package publishes at its root. + expect(readFileSync(config.image, 'utf8')).toBe( + readFileSync(join(import.meta.dirname, '..', '..', 'sandbox.Dockerfile'), 'utf8'), + ); expect(config.platformImage).toBe('cloudflare/debian-trixie'); }); diff --git a/packages/void/test/unit/container-image.test.ts b/packages/void/test/unit/container-image.test.ts new file mode 100644 index 000000000..2e6e9ad6b --- /dev/null +++ b/packages/void/test/unit/container-image.test.ts @@ -0,0 +1,166 @@ +import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; +import { buildContainerImage } from '../../src/cli/container-image.ts'; + +const START_DOCKER = 'Sandbox image preparation failed. Start Docker and retry the deployment.'; + +// The wait for a real process also runs in the test that replaces `setTimeout`. +const realSetTimeout = setTimeout; + +/** What the stand-in does for a command: exit with a code, stop itself with a signal, or hang. */ +type Outcome = number | NodeJS.Signals | 'hang'; + +type DockerStub = { + root: string; + dockerfile: string; + calls: () => Array; + /** The process id of a command that hangs, once it runs. */ + hungPid: () => number | undefined; +}; + +const roots: Array = []; +afterEach(() => { + vi.useRealTimers(); + vi.unstubAllEnvs(); + for (const root of roots.splice(0)) { + rmSync(root, { recursive: true, force: true }); + } +}); + +/** Install a Docker CLI stand-in that records its arguments and ends each command as given. */ +function stubDocker(outcomes: { build: Outcome; info?: Outcome }): DockerStub { + const root = mkdtempSync(join(tmpdir(), 'void-container-image-')); + roots.push(root); + const log = join(root, 'docker.log'); + const pidFile = join(root, 'docker.pid'); + const binary = join(root, 'docker-stub'); + writeFileSync(log, ''); + writeFileSync(pidFile, ''); + writeFileSync( + binary, + '#!/usr/bin/env node\n' + + 'const { appendFileSync } = require("node:fs");\n' + + 'const args = process.argv.slice(2);\n' + + `appendFileSync(${JSON.stringify(log)}, JSON.stringify(args) + "\\n");\n` + + `const outcome = ${JSON.stringify(outcomes)}[args[0]] ?? 0;\n` + + 'if (typeof outcome === "number") process.exit(outcome);\n' + + `if (outcome === "hang") appendFileSync(${JSON.stringify(pidFile)}, process.pid + "\\n");\n` + + 'else process.kill(process.pid, outcome);\n' + + '// Stay until a signal ends the process. A failed test leaves it no longer than this.\n' + + 'setTimeout(() => {}, 30000);\n', + ); + chmodSync(binary, 0o755); + vi.stubEnv('WRANGLER_DOCKER_BIN', binary); + return { + root, + dockerfile: join(root, 'Dockerfile'), + calls: () => + readFileSync(log, 'utf8') + .split('\n') + .filter(Boolean) + .map((line): unknown => JSON.parse(line)), + hungPid: () => { + const text = readFileSync(pidFile, 'utf8'); + // The line ends once the whole id is written. + return text.endsWith('\n') ? Number(text) : undefined; + }, + }; +} + +function buildArgs(dockerfile: string, context: string): Array { + return [ + 'build', + '--platform', + 'linux/amd64', + '--file', + dockerfile, + '--tag', + expect.stringMatching(/^void-sandbox-build:/), + context, + ]; +} + +/** Wait until the command that hangs runs, and return its process id. */ +async function hung(docker: DockerStub): Promise { + for (let tries = 0; tries < 400; tries += 1) { + const pid = docker.hungPid(); + if (pid !== undefined) { + return pid; + } + await new Promise((resolve) => { + realSetTimeout(resolve, 10); + }); + } + throw new Error('The Docker stand-in did not start in time'); +} + +// The stand-in is an executable script, which Windows does not launch by path. +describe.skipIf(process.platform === 'win32')('buildContainerImage', () => { + it('builds without checking the Docker daemon and removes the local tag on dispose', async () => { + const docker = stubDocker({ build: 0, info: 0 }); + + const image = await buildContainerImage(docker.dockerfile); + expect(docker.calls()).toEqual([buildArgs(docker.dockerfile, docker.root)]); + + await image.dispose(); + expect(docker.calls()).toEqual([ + buildArgs(docker.dockerfile, docker.root), + ['image', 'rm', image.localReference], + ]); + }); + + it('reports a failed build as a build failure while Docker is running', async () => { + const docker = stubDocker({ build: 1, info: 0 }); + + await expect(buildContainerImage(docker.dockerfile)).rejects.toThrow( + `Sandbox image preparation failed: \`docker build\` exited with code 1 for ${docker.dockerfile}. See the Docker output above.`, + ); + expect(docker.calls()).toEqual([buildArgs(docker.dockerfile, docker.root), ['info']]); + }); + + it('asks to start Docker when the daemon does not answer', async () => { + const docker = stubDocker({ build: 1, info: 1 }); + + await expect(buildContainerImage(docker.dockerfile)).rejects.toThrow(START_DOCKER); + expect(docker.calls()).toEqual([buildArgs(docker.dockerfile, docker.root), ['info']]); + }); + + it('reports the failed build when `docker info` does not finish in time', async () => { + const docker = stubDocker({ build: 1, info: 'hang' }); + // The deadline is a `setTimeout` in container-image.ts. Reach it without the real wait. + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + + const failure = expect(buildContainerImage(docker.dockerfile)).rejects.toThrow( + `Sandbox image preparation failed: \`docker build\` exited with code 1 for ${docker.dockerfile}. See the Docker output above.`, + ); + const pid = await hung(docker); + vi.runOnlyPendingTimers(); + await failure; + + expect(docker.calls()).toEqual([buildArgs(docker.dockerfile, docker.root), ['info']]); + // The deadline stopped the command: signal 0 only asks whether the process exists. + expect(() => process.kill(pid, 0)).toThrow(); + }); + + it('names the signal that stopped the build, without asking the daemon', async () => { + const docker = stubDocker({ build: 'SIGTERM' }); + + await expect(buildContainerImage(docker.dockerfile)).rejects.toThrow( + `Sandbox image preparation failed: \`docker build\` was stopped by SIGTERM for ${docker.dockerfile}.`, + ); + expect(docker.calls()).toEqual([buildArgs(docker.dockerfile, docker.root)]); + }); + + it('names the cause when the Docker CLI is missing', async () => { + const docker = stubDocker({ build: 0 }); + const missing = join(docker.root, 'missing-docker'); + vi.stubEnv('WRANGLER_DOCKER_BIN', missing); + + await expect(buildContainerImage(docker.dockerfile)).rejects.toThrow( + `Sandbox image preparation failed: the Docker CLI could not be started (spawn ${missing} ENOENT). Check that Docker is installed and retry the deployment.`, + ); + expect(docker.calls()).toEqual([]); + }); +});