From 6648d9e1e8458e187af113e0455e813ed3ca0d26 Mon Sep 17 00:00:00 2001 From: Doug Horner Date: Fri, 4 Dec 2026 04:15:59 -0500 Subject: [PATCH] Add mieweb exec for one-shot commands in running guests --- .changeset/manager-guest-exec.md | 7 ++ README.md | 7 +- packages/cli/README.md | 32 ++++++++ packages/cli/package.json | 2 +- packages/cli/src/exec.mjs | 100 +++++++++++++++++++++++ packages/cli/src/index.mjs | 11 ++- packages/cli/test/exec.test.mjs | 112 ++++++++++++++++++++++++++ packages/deploy-contract/src/index.ts | 24 ++++++ pnpm-lock.yaml | 10 +-- 9 files changed, 297 insertions(+), 8 deletions(-) create mode 100644 .changeset/manager-guest-exec.md create mode 100644 packages/cli/src/exec.mjs create mode 100644 packages/cli/test/exec.test.mjs diff --git a/.changeset/manager-guest-exec.md b/.changeset/manager-guest-exec.md new file mode 100644 index 0000000..9b364bd --- /dev/null +++ b/.changeset/manager-guest-exec.md @@ -0,0 +1,7 @@ +--- +"@mieweb/cli": minor +"@mieweb/deploy-contract": minor +"mieweb": minor +--- + +Add `mieweb exec --site --container -- [arg ...]` for running a one-shot command in an existing guest through a provider with the optional `exec` capability. Preserve argument boundaries, output bytes, and the guest process exit status. diff --git a/README.md b/README.md index aabb8c1..12d32bd 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,12 @@ mieweb whoami mieweb deploy ``` -Commands that use a target print its name to standard error. For commands +Run a one-off command in a running guest with +`mieweb exec --site --container -- node --version`. This requires a +Manager and OS provider with exec support. It preserves guest stdout, stderr, +and exit status for scripts. [Guest exec details](packages/cli/README.md#run-a-command-in-a-manager-guest) + +Other commands that use a target print its name to standard error. For commands that contact an opensource-server Manager, the same line includes its URL. Deploy, tail and destroy also show the site ID when one is configured. Wrangler commands show the named environment selected with `--env` or diff --git a/packages/cli/README.md b/packages/cli/README.md index c35ef55..886aa95 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -25,6 +25,38 @@ Select `--target cloudflare` to use Wrangler. The CLI uses in that order. Any target can override its deploy provider with `targets..provider` in `mieweb.jsonc`. +## Run a command in a Manager guest + +Sign in with `mieweb login`, or set `MIEWEB_OS_TOKEN` in CI. Use the numeric site +ID and Manager container ID of a running guest you have permission to execute in. +The guest can have just an HTTP route. + +```sh +mieweb exec --site 2 --container 41 -- node --version +mieweb exec --site 2 --container 41 -- node -e 'process.exit(17)' +``` + +The first argument after `--` is the program. Each remaining argument goes to it +literally, including empty strings and flags such as `--target`. Shell expansion +by your local shell still applies. The command runs once, with no terminal or +stdin. The CLI sends guest output to the matching local streams and exits with +the guest status. If the Manager caps a stream, the CLI reports which one on +stderr. + +CLI, Manager, and transport failures exit with status 125 and a +`[mieweb exec] Request failed:` diagnostic. A guest that exits 125 gets a final +`[mieweb exec] Guest exited with status 125.` line on stderr. If the connection +breaks after submission, the command may already have run. Check its effect +before issuing another request. + +Exec requires an updated Manager and an exec-capable +`@mieweb/os-cloud-provider`. The CLI prefers the provider installed in the +current project. For a pull request preview, install the provider tarball from +the OS provider preview workflow's job summary in that project. For a local +build, point `targets.mieweb.provider` at the provider's +built entry point and configure `targets.mieweb.instanceUrl` for the test +Manager. The built-in Cloudflare provider does not implement this command. + ## Images (Cloudflare Containers) Build container images once, distribute them with **skopeo** diff --git a/packages/cli/package.json b/packages/cli/package.json index 1d222c8..48d3222 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -33,7 +33,7 @@ "@mieweb/cloud-adapters": "workspace:*", "@mieweb/deploy-contract": "workspace:*", "@mieweb/deploy-wrangler": "workspace:*", - "@mieweb/os-cloud-provider": "~2026.10.4", + "@mieweb/os-cloud-provider": "~2026.12.1", "import-meta-resolve": "^4.2.0", "jsonc-parser": "^3.3.1" }, diff --git a/packages/cli/src/exec.mjs b/packages/cli/src/exec.mjs new file mode 100644 index 0000000..8133ab8 --- /dev/null +++ b/packages/cli/src/exec.mjs @@ -0,0 +1,100 @@ +// @ts-check +import { parseArgs } from 'node:util'; +import { loadConfig } from './config.mjs'; +import { buildContext, resolveProvider, usesOpensourceServer } from './provider.mjs'; + +const usage = 'Usage: mieweb exec --site --container -- [arg ...]'; +const cliFailure = 125; + +/** @param {string[] | undefined} values @param {string} option */ +function requiredId(values, option) { + const value = values?.[0]; + const id = Number(value); + if (values?.length !== 1 || !value || !/^\d+$/.test(value) || !Number.isSafeInteger(id) || id < 1) { + throw new Error(`Supply exactly one positive integer for --${option}.\n${usage}`); + } + return id; +} + +/** @param {string[]} args @returns {import('@mieweb/deploy-contract').ContainerExecRequest} */ +function parseRequest(args) { + const end = args.indexOf('--'); + if (end < 0 || !args[end + 1]) throw new Error(usage); + const { values } = parseArgs({ + args: args.slice(0, end), + options: { + site: { type: 'string', multiple: true }, + container: { type: 'string', multiple: true }, + }, + }); + return { + siteId: requiredId(values.site, 'site'), + containerId: requiredId(values.container, 'container'), + argv: args.slice(end + 1), + }; +} + +/** @param {NodeJS.WriteStream} stream @param {Uint8Array} bytes */ +async function writeBytes(stream, bytes) { + if (!bytes.length) return; + // The CLI exits explicitly. Wait for redirected streams to drain before returning. + await new Promise((resolve, reject) => { + stream.once('error', reject); + stream.write(bytes, error => { + if (error) return reject(error); + stream.removeListener('error', reject); + resolve(undefined); + }); + }); +} + +/** @param {string[]} args @param {string | null} overrideTarget */ +export async function runExec(args, overrideTarget) { + if (args.length === 1 && (args[0] === '--help' || args[0] === '-h')) { + console.log(usage); + return 0; + } + + try { + const request = parseRequest(args); + const config = loadConfig({ overrideTarget }); + const provider = await resolveProvider(config); + if (!provider?.exec) { + const hint = usesOpensourceServer(config) + ? ' Install an exec-capable version of @mieweb/os-cloud-provider in your project.' + : ''; + throw new Error(`The provider for target "${config.target}" does not implement exec.${hint}`); + } + // The executable and guest args belong exclusively to request.argv. + const { context, dispose } = buildContext(config, []); + try { + const result = await provider.exec(context, request); + if (!(result?.stdout instanceof Uint8Array) || !(result.stderr instanceof Uint8Array) || + !Number.isInteger(result.exitCode) || result.exitCode < 0 || result.exitCode > 255 || + typeof result.stdoutTruncated !== 'boolean' || typeof result.stderrTruncated !== 'boolean') { + throw new Error('Invalid provider result. The command may have run. Check the guest before retrying.'); + } + const notices = []; + if (result.stdoutTruncated) notices.push('[mieweb exec] Guest stdout was truncated.'); + if (result.stderrTruncated) notices.push('[mieweb exec] Guest stderr was truncated.'); + // A shell has just 256 statuses. Label the collision with a CLI failure. + if (result.exitCode === cliFailure) notices.push('[mieweb exec] Guest exited with status 125.'); + try { + await writeBytes(process.stdout, result.stdout); + await writeBytes(process.stderr, result.stderr); + if (notices.length) { + const newline = result.stderr.length && result.stderr.at(-1) !== 10 ? '\n' : ''; + await writeBytes(process.stderr, Buffer.from(newline + notices.join('\n') + '\n')); + } + } catch { + throw new Error(`Guest exited with status ${result.exitCode}, but the CLI could not write its output.`); + } + return result.exitCode; + } finally { + dispose(); + } + } catch (error) { + console.error(`[mieweb exec] Request failed: ${error instanceof Error ? error.message : String(error)}`); + return cliFailure; + } +} diff --git a/packages/cli/src/index.mjs b/packages/cli/src/index.mjs index 497bcb8..3d58fa4 100755 --- a/packages/cli/src/index.mjs +++ b/packages/cli/src/index.mjs @@ -22,6 +22,7 @@ import { readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { loadConfig } from './config.mjs'; +import { runExec } from './exec.mjs'; import { delegateToWrangler } from './cloudflare.mjs'; import { runHostTarget } from './local.mjs'; import { runInit } from './init.mjs'; @@ -45,9 +46,13 @@ async function main(argv) { // it reaches wrangler (which wouldn't understand it). let overrideTarget = null; /** @type {string[]} */ - const args = []; + let args = []; for (let i = 0; i < argv.length; i += 1) { const a = argv[i]; + if (a === '--') { + args = args.concat(argv.slice(i)); + break; + } if (a === '--target' || a === '-t') { overrideTarget = argv[i + 1] ?? null; i += 1; @@ -77,6 +82,8 @@ async function main(argv) { return runInit(args.slice(1)); } + if (args[0] === 'exec') return runExec(args.slice(1), overrideTarget); + const config = loadConfig({ overrideTarget }); process.stderr.write(`[mieweb] Target: ${formatEnvironment(config, args)}\n`); @@ -158,6 +165,8 @@ function printHelp() { " mieweb login Authenticate the active target's provider.", " mieweb logout Clear the provider's stored session.", " mieweb whoami Show the provider's auth status.", + ' mieweb exec --site --container -- [arg ...]', + ' Run a one-shot command in a running guest.', ' mieweb dev Start a dev server for the active target.', " mieweb deploy Deploy via the active target's provider.", ' mieweb tail Stream logs from the deployed worker.', diff --git a/packages/cli/test/exec.test.mjs b/packages/cli/test/exec.test.mjs new file mode 100644 index 0000000..221fdc7 --- /dev/null +++ b/packages/cli/test/exec.test.mjs @@ -0,0 +1,112 @@ +import assert from 'node:assert/strict'; +import { execFile } from 'node:child_process'; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { test } from 'node:test'; +import { fileURLToPath } from 'node:url'; +import { promisify } from 'node:util'; + +const execFileAsync = promisify(execFile); +const cli = fileURLToPath(new URL('../src/index.mjs', import.meta.url)); +const select = ['--site', '2', '--container', '41', '--']; + +function project(t, result = "throw new Error('Unexpected provider call.');") { + const cwd = mkdtempSync(join(tmpdir(), 'mieweb-exec-')); + t.after(() => rmSync(cwd, { recursive: true, force: true })); + writeFileSync(join(cwd, 'mieweb.jsonc'), JSON.stringify({ + target: 'mieweb', targets: { mieweb: { provider: './fixture.mjs' } }, + })); + writeFileSync(join(cwd, 'fixture.mjs'), ` + import { appendFileSync } from 'node:fs'; + export default { + name: 'fixture', supports: target => target === 'mieweb', deploy() {}, + async exec(context, request) { + appendFileSync('requests', JSON.stringify(request) + '\\n'); + ${result} + } + }; + `); + const env = { ...process.env, MIEWEB_TARGET: '' }; + const run = (...args) => execFileAsync(process.execPath, [cli, 'exec', ...args], { cwd, env, encoding: 'buffer' }); + return { run, cwd }; +} + +test('passes the executable and literal guest arguments, and drains raw streams', async t => { + const { run, cwd } = project(t, ` + return { stdout: Buffer.alloc(131072, 0xff), stderr: Buffer.from([0, 13, 255]), + exitCode: 0, stdoutTruncated: false, stderrTruncated: false }; + `); + const guest = ['tool', 'space here', '', '--target', 'local', '-t', '$HOME', '--', '--help']; + const { stdout, stderr } = await run('--target', 'mieweb', ...select, ...guest); + assert.deepEqual(stdout, Buffer.alloc(131072, 0xff)); + assert.deepEqual(stderr, Buffer.from([0, 13, 255])); + assert.deepEqual(JSON.parse(readFileSync(join(cwd, 'requests'), 'utf8')), { siteId: 2, containerId: 41, argv: guest }); +}); + +test('returns a guest failure including its unmodified stderr', async t => { + const { run } = project(t, ` + return { stdout: Buffer.from('out'), stderr: Buffer.from('guest error'), + exitCode: 17, stdoutTruncated: false, stderrTruncated: false }; + `); + await assert.rejects(run(...select, 'guest'), err => { + assert.equal(err.code, 17); + assert.equal(err.stdout.toString(), 'out'); + assert.equal(err.stderr.toString(), 'guest error'); + return true; + }); +}); + +test('identifies truncation and distinguishes guest exit 125 from a request failure', async t => { + const { run } = project(t, ` + return { stdout: Buffer.from('out'), stderr: Buffer.from('err'), + exitCode: 125, stdoutTruncated: false, stderrTruncated: true }; + `); + await assert.rejects(run(...select, 'guest'), err => { + assert.equal(err.code, 125); + assert.equal(err.stdout.toString(), 'out'); + assert.equal(err.stderr.toString(), 'err\n[mieweb exec] Guest stderr was truncated.\n[mieweb exec] Guest exited with status 125.\n'); + return true; + }); +}); + +test('rejects bad results and reports provider failures without retrying the exec', async t => { + for (const [body, detail] of [ + ["throw new Error('Manager denied this guest.');", /Manager denied this guest/], + ["throw new Error('Connection lost. Check the guest before retrying.');", /Check the guest/], + ['return { stdout: new Uint8Array(), stderr: new Uint8Array(), exitCode: -1 };', /command may have run/], + ]) { + const { run, cwd } = project(t, body); + await assert.rejects(run(...select, 'guest'), err => { + assert.equal(err.code, 125); + assert.equal(err.stdout.length, 0); + assert.match(err.stderr.toString(), /^\[mieweb exec\] Request failed:/); + assert.match(err.stderr.toString(), detail); + assert.equal(readFileSync(join(cwd, 'requests'), 'utf8').trim().split('\n').length, 1); + return true; + }); + } +}); + +test('validates ambiguous selectors, requires the delimiter and executable, and offers local help', async t => { + const { run } = project(t); + for (const args of [ + ['--site', '2', '--', 'guest'], ['--site', '2', '--container', '0', '--', 'guest'], + ['--site', '2', '--site', '3', '--container', '41', '--', 'guest'], select, + ['--site', '2', '--container', '41', 'guest'], + ]) { + await assert.rejects(run(...args), err => { + assert.equal(err.code, 125); + assert.match(err.stderr.toString(), /Usage: mieweb exec/); + return true; + }); + } + const help = await run('--help'); + assert.match(help.stdout.toString(), /Usage: mieweb exec/); + assert.equal(help.stderr.length, 0); + await assert.rejects(run('--target', 'local', ...select, 'guest'), err => { + assert.equal(err.code, 125); + assert.match(err.stderr.toString(), /target "local" does not implement exec/); + return true; + }); +}); diff --git a/packages/deploy-contract/src/index.ts b/packages/deploy-contract/src/index.ts index ecb12b2..495b2fd 100644 --- a/packages/deploy-contract/src/index.ts +++ b/packages/deploy-contract/src/index.ts @@ -201,6 +201,22 @@ export interface DeployHandle { stop(): void | Promise; } +/** Identifies one running guest and the executable and literal arguments to run in it. */ +export interface ContainerExecRequest { + readonly siteId: number; + readonly containerId: number; + readonly argv: readonly string[]; +} + +/** A completed command, including a nonzero guest exit. Both streams contain raw bytes. */ +export interface ContainerExecResult { + readonly stdout: Uint8Array; + readonly stderr: Uint8Array; + readonly exitCode: number; + readonly stdoutTruncated: boolean; + readonly stderrTruncated: boolean; +} + /** * The result of an authentication-status check ({@link DeployProvider.whoami}). * @@ -274,6 +290,14 @@ export interface DeployProvider { /** Stream logs from the deployed worker. Absent ⇒ CLI reports unsupported. */ tail?(context: DeployContext): Promise; + /** + * Run a non-interactive command once in an existing guest. Preserve argv boundaries, + * bound execution time and output, and return the guest's exit status (0–255). + * Reject failures to obtain a guest result. A lost response can follow execution, + * so providers must not retry automatically. + */ + exec?(context: DeployContext, request: ContainerExecRequest): Promise; + /** Tear down what {@link deploy} created. Absent ⇒ CLI reports unsupported. */ destroy?(context: DeployContext): Promise; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 31d03c1..8d22201 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -36,8 +36,8 @@ importers: specifier: workspace:* version: link:../deploy-wrangler '@mieweb/os-cloud-provider': - specifier: ~2026.10.4 - version: 2026.10.4(bare-buffer@3.7.3) + specifier: ~2026.12.1 + version: 2026.12.1(bare-buffer@3.7.3) import-meta-resolve: specifier: ^4.2.0 version: 4.2.0 @@ -356,8 +356,8 @@ packages: '@mieweb/deploy-contract@0.3.1': resolution: {integrity: sha512-0H5je3UrZwHFMksJPeoGHe8OtS5UENjDne2/hZxI+3ZhLmdgoZK7fI3Pqtf/ub5xf+0Kjrp1PyswAIqDPr3LEg==} - '@mieweb/os-cloud-provider@2026.10.4': - resolution: {integrity: sha512-yO8pXDyqMLadSvrJuQdrnHm//YHjJVhqUAbfKRJ4/ifdTuiEXme4fubghsvmHbSZWa+gyAMU4JSqafBD1uFVrw==} + '@mieweb/os-cloud-provider@2026.12.1': + resolution: {integrity: sha512-XE8hk68G+wMepr5Mkqujs94i52Vs9Wj24VByZ4I97HeqYZaurtQM2c5j+z8Hd+lN8q8KuJsVq+deSqCybtew3g==} engines: {node: '>=22.18'} '@neon-rs/load@0.0.4': @@ -1514,7 +1514,7 @@ snapshots: '@mieweb/deploy-contract@0.3.1': {} - '@mieweb/os-cloud-provider@2026.10.4(bare-buffer@3.7.3)': + '@mieweb/os-cloud-provider@2026.12.1(bare-buffer@3.7.3)': dependencies: '@mieweb/deploy-contract': 0.3.1 ignore: 7.0.17