diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..f28cb69 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,78 @@ +name: ci + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +env: + # Immutable SDK commit (Perfscale/sdk-libraries, feat/wasm-step-sdk): + # defineSteps + --kind steps build + settings delivery. + SDK_COMMIT: 522cfdd590062652c04337e6dfdcfc1c2c79389e + +jobs: + build-test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + path: repo + # The SDK is a file: sibling dependency (../sdk-step-authoring/ts); + # pin it to an exact public commit. + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + repository: Perfscale/sdk-libraries + ref: feat/wasm-step-sdk + path: sdk-step-authoring + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: 24 + - name: Verify the pinned SDK commit + working-directory: sdk-step-authoring + run: test "$(git rev-parse HEAD)" = "$SDK_COMMIT" + - name: Install and build SDK (dist + type declarations) + working-directory: sdk-step-authoring/ts + run: | + npm ci + npm run build + - name: Install, typecheck, unit-test + working-directory: repo + run: | + npm install + npm run typecheck + npm test + - name: Build the WASM component + working-directory: repo + run: npm run build + - name: Inspect component imports/exports + working-directory: repo + run: ../sdk-step-authoring/ts/node_modules/.bin/jco wit nodejs.wasm + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: nodejs-wasm + path: repo/nodejs.wasm + retention-days: 7 + + integration: + needs: build-test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: nodejs-wasm + path: . + - uses: dtolnay/rust-toolchain@stable + - name: Build Perfscale v0.30.0 from source + run: | + git clone --depth 1 --branch v0.30.0 https://github.com/Perfscale/perfscale.git /tmp/perfscale-src + cargo build --release -p perfscale-cli --manifest-path /tmp/perfscale-src/Cargo.toml + cp /tmp/perfscale-src/target/release/perfscale "$GITHUB_WORKSPACE/perfscale" + "$GITHUB_WORKSPACE/perfscale" --version + - name: Run the example through the engine (settings-driven install + exec) + run: | + "$GITHUB_WORKSPACE/perfscale" run -f examples/node.test.yaml -c examples/node.config.yaml | tee run.log + grep -q 'hello from node v24.16.0' run.log diff --git a/README.md b/README.md index f7ea373..4d61516 100644 --- a/README.md +++ b/README.md @@ -30,8 +30,9 @@ scripts can do on the host, they do with the perfscale process's privileges. or override, string values only). - `install` never uses sudo and never mutates global state: everything lands under `install-dir` (default `/tmp/perfscale-toolcache/nodejs`). - It is idempotent — if `/node-v-linux-/bin/node - --version` succeeds, nothing is re-downloaded or re-installed, ever. On a + It is idempotent — if `/node-v-linux-/bin/node` + exists (`test -x`; the host import hard-errors on spawn-ENOENT) and + answers `--version`, nothing is re-downloaded or re-installed, ever. On a checksum mismatch only the downloaded archive is deleted; install trees are never `rm`'d. - `exec` path/`node-path` values are passed verbatim — this is a trusted @@ -129,7 +130,7 @@ steps: use: lib/nodejs/install-exec with: node-version: 24.16.0 - install-dir: .perfscale-tools/nodejs + install-dir: /tmp/perfscale-toolcache/nodejs # absolute — exec requires an absolute node-path script: console.log("ok") outputs: combo ``` @@ -137,6 +138,43 @@ steps: Output merges install and exec results: `{ "path", "node-path", "version", "exit_code", "stdout", "stderr" }`. +## Run settings (RFC 009) + +Every step knob may be set once for the whole run instead of repeated per +step. Precedence (highest first): + +1. the step's explicit `with:` params +2. the `nodejs:` config extension block (claimed via the component's config + schema — unknown keys fail the run) +3. the `variables.nodejs` map +4. the library entry's `with:` block +5. the built-in defaults + +`env` maps merge in that same order (a step's `env` wins per key). Accepted +settings keys: `node-version` (alias `version`), `install-dir`, `node-path` +(alias `executable`), `working-directory` / `cwd`, `timeout_ms` / +`timeoutMs`, `env`. Invalid blocks (unknown key, wrong type, relative +`node-path`, bad version) are hard errors — at instantiation for the +library `with:`, at step resolution for the rest. + +```yaml +# perfscale.config.yaml +nodejs: # config extension, validated against the schema + node-version: "24" + install-dir: /tmp/perfscale-toolcache/nodejs # absolute — exec requires an absolute node-path +variables: + nodejs: { timeout_ms: 30000 } +libraries: + - use: ./nodejs.wasm + capabilities: [process] + with: { env: { NODE_ENV: test } } # lowest-precedence defaults +steps: + - name: smoke + use: lib/nodejs/install-exec + with: + script: console.log(process.version) # version/dir come from settings +``` + ## Orchestration, not hot path Each step invocation is **real host process spawns** (and `install` may @@ -150,7 +188,7 @@ before: use: lib/nodejs/install with: node-version: 24.16.0 - install-dir: .perfscale-tools/nodejs + install-dir: /tmp/perfscale-toolcache/nodejs # absolute — exec requires an absolute node-path outputs: setup # → ${{ config.setup.node-path }} in test steps ``` @@ -165,10 +203,11 @@ $ npm run build # → nodejs.wasm (needs the SDK bin, see below) $ perfscale run -f examples/node.test.yaml -c examples/node.config.yaml ``` -Run `perfscale` from the **repository root** — `install-dir: -.perfscale-tools/nodejs` (gitignored) is resolved against the process cwd. -The first run downloads Node.js 24.16.0 from nodejs.org; later runs reuse -the cache. +The first run downloads Node.js 24.16.0 from nodejs.org into the default +toolcache (`/tmp/perfscale-toolcache/nodejs`); later runs reuse the cache. +`install-dir` may be relative, but then the installed `node-path` is +relative too and `exec` (which requires an absolute path) will refuse it — +prefer absolute install dirs. ## Development diff --git a/SECURITY.md b/SECURITY.md index bbc4693..ab5e8f0 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -14,14 +14,16 @@ its contract, for example: skipping the SHA-256 verification against the official `SHASUMS256.txt` before extraction. - Spawning anything other than the documented `/usr/bin/uname`, - `/usr/bin/mkdir`, `/usr/bin/curl`, `/usr/bin/sha256sum`, `/usr/bin/tar`, - `/usr/bin/rm` (the downloaded archive only), or the selected node binary. + `/usr/bin/test` (cache probe), `/usr/bin/mkdir`, `/usr/bin/curl`, + `/usr/bin/sha256sum`, `/usr/bin/tar`, `/usr/bin/rm` (the downloaded + archive only), or the selected node binary. - Leaking host environment variables into a child (the host import already guarantees a replacement environment; a bug that bypasses it matters). - The cache-idempotency or bad-archive cleanup deleting anything other than the downloaded `.tar.xz` archive. -- Validation gaps that let crafted `with:` params alter the spawned argv in - undocumented ways. +- Validation gaps that let crafted `with:` params or settings blocks + (extension / variables / library `with:`) alter the spawned argv or + environment in undocumented ways. ## What is out of scope diff --git a/examples/node.config.yaml b/examples/node.config.yaml index 7adc9c3..0ba55cb 100644 --- a/examples/node.config.yaml +++ b/examples/node.config.yaml @@ -8,16 +8,25 @@ seed: 42 # side, the engine refuses to load the component (fail-closed, like `net`). allow_library_capabilities: true allow_process_actions: true +# Run-level settings (RFC 009): the `nodejs` extension block is claimed by +# the component's config schema; a step's explicit `with:` still wins over +# it, `variables.nodejs` sits one level below it, and the library entry's +# `with:` provides defaults below both. install-dir stays at its (absolute) +# built-in default — exec requires an absolute node-path. +nodejs: + timeout_ms: 60000 +variables: + nodejs: { timeout_ms: 30000 } libraries: - use: ../nodejs.wasm capabilities: [process] before: # Pinned exact version, checksum-verified against the official - # nodejs.org SHASUMS256.txt. Installs into a repo-local toolcache - # (gitignored); subsequent runs reuse it — nothing is re-downloaded. + # nodejs.org SHASUMS256.txt. Installs into the default toolcache + # (/tmp/perfscale-toolcache/nodejs); subsequent runs reuse it — nothing is + # re-downloaded. - name: node use: lib/nodejs/install with: node-version: 24.16.0 - install-dir: .perfscale-tools/nodejs outputs: setup # → ${{ config.setup.node-path }} in test steps diff --git a/examples/node.test.yaml b/examples/node.test.yaml index 4507a41..bb71c0f 100644 --- a/examples/node.test.yaml +++ b/examples/node.test.yaml @@ -5,8 +5,6 @@ # npm run build # → ../nodejs.wasm relative to this file's examples dir # # perfscale run -f examples/node.test.yaml -c examples/node.config.yaml -# (run from the repository root — `install-dir: .perfscale-tools/nodejs` -# is resolved against the process cwd) # # NOTE: process steps are orchestration (setup, fixtures, one-off checks), # not a high-RPS hot path — each invocation is a real host spawn. @@ -24,8 +22,7 @@ steps: - name: install-exec-one-shot use: lib/nodejs/install-exec with: - node-version: 24.16.0 - install-dir: .perfscale-tools/nodejs # cache hit — no re-download + node-version: 24.16.0 # cache hit — no re-download script: console.log(JSON.stringify(process.argv.slice(2))) args: ["perfscale"] outputs: combo diff --git a/src/nodejs.ts b/src/nodejs.ts index d2cddab..700d751 100644 --- a/src/nodejs.ts +++ b/src/nodejs.ts @@ -25,6 +25,12 @@ import { * AND `allow_process_actions: true` + `allow_library_capabilities: true` in * the config. * + * Settings (RFC 009): every step knob may also come from the run — + * `extensions[nodejs]` > `variables[nodejs]` > the library entry's `with:` + * > built-in defaults; a step's explicit `with:` param beats them all, and + * `env` maps merge in that order. The component claims the `nodejs` config + * extension key via its config schema (unknown keys fail the run). + * * Build: node ../sdk-step-authoring/ts/bin/perfscale-library-build.mjs \ * --kind steps --process src/nodejs.ts -o nodejs.wasm */ @@ -40,6 +46,153 @@ const DIST_BASE = "https://nodejs.org/dist"; const TARBALL_TIMEOUT_MS = 600_000; const SMALL_TIMEOUT_MS = 60_000; +// --------------------------------------------------------------------------- +// Settings (RFC 009): library `with:` defaults + run settings +// --------------------------------------------------------------------------- +// +// Every knob a step accepts may also be set once for the whole run. +// Precedence (highest first): +// +// 1. the step's explicit `with:` params +// 2. the run's `extensions[nodejs]` block (claimed via configSchema) +// 3. the run's `variables[nodejs]` map +// 4. the library entry's `with:` block (delivered to `init`) +// 5. the built-in defaults below +// +// `env` maps merge in that same order (a step's `env` wins over the same +// key set anywhere else); scalar keys take the highest-precedence value. +// Invalid settings are hard errors at resolution time — never silently +// ignored. + +/** The accepted keys of any settings block (step `with:` adds more). */ +const SETTINGS_KEYS = [ + "node-version", "version", "install-dir", "node-path", "executable", + "working-directory", "cwd", "timeout_ms", "timeoutMs", "env", +]; + +/** Normalized per-run defaults collected from the settings sources. */ +interface NodejsSettings { + nodeVersion?: string | undefined; + installDir?: string | undefined; + nodePath?: string | undefined; + cwd?: string | undefined; + timeoutMs?: number | undefined; + env?: Record | undefined; +} + +/** JSON Schema for the claimed `nodejs` config extension key. */ +const NODEJS_CONFIG_SCHEMA = { + type: "object", + additionalProperties: false, + properties: { + "node-version": { type: "string", minLength: 1 }, + version: { type: "string", minLength: 1 }, + "install-dir": { type: "string", minLength: 1 }, + "node-path": { type: "string", minLength: 1 }, + executable: { type: "string", minLength: 1 }, + "working-directory": { type: "string", minLength: 1 }, + cwd: { type: "string", minLength: 1 }, + timeout_ms: { type: ["number", "string"] }, + timeoutMs: { type: ["number", "string"] }, + env: { + type: "object", + additionalProperties: { type: "string" }, + }, + }, +} as const; + +function parseSettingsBlock(source: string, raw: unknown): NodejsSettings { + if (raw === undefined || raw === null) return {}; + if (typeof raw !== "object" || Array.isArray(raw)) { + throw new StepError(`nodejs settings (${source}): must be an object`); + } + const block = raw as Record; + for (const k of Object.keys(block)) { + if (!SETTINGS_KEYS.includes(k)) { + throw new StepError(`nodejs settings (${source}): unknown key '${k}'`); + } + } + const s: NodejsSettings = {}; + const str = (key: string): string | undefined => { + const v = block[key]; + if (v === undefined) return undefined; + if (typeof v !== "string" || v === "") { + throw new StepError(`nodejs settings (${source}): '${key}' must be a non-empty string`); + } + return v; + }; + const version = str("node-version") ?? str("version"); + if (version !== undefined) { + if (!EXACT_VERSION.test(version) && !MAJOR_VERSION.test(version)) { + throw new StepError( + `nodejs settings (${source}): 'node-version' must be an exact semver (e.g. 24.16.0) or a major / major.x (e.g. 24 or 24.x)`, + ); + } + s.nodeVersion = version; + } + s.installDir = str("install-dir"); + s.nodePath = str("node-path") ?? str("executable"); + if (s.nodePath !== undefined && !s.nodePath.startsWith("/")) { + throw new StepError(`nodejs settings (${source}): 'node-path' must be an absolute path`); + } + const wd = str("working-directory"); + const cwd = str("cwd"); + if (wd !== undefined && cwd !== undefined && wd !== cwd) { + throw new StepError(`nodejs settings (${source}): 'working-directory' and 'cwd' disagree`); + } + s.cwd = wd ?? cwd; + const t = block["timeout_ms"] ?? block["timeoutMs"]; + if (t !== undefined) { + const n = typeof t === "number" ? t : typeof t === "string" ? Number(t) : NaN; + if (!Number.isFinite(n) || n <= 0) { + throw new StepError(`nodejs settings (${source}): timeout must be a positive number of milliseconds`); + } + s.timeoutMs = n; + } + const env = block["env"]; + if (env !== undefined) { + if (typeof env !== "object" || env === null || Array.isArray(env)) { + throw new StepError(`nodejs settings (${source}): 'env' must be a map of string to string`); + } + s.env = {}; + for (const [k, val] of Object.entries(env as Record)) { + if (typeof val !== "string") { + throw new StepError(`nodejs settings (${source}): env['${k}'] must be a string`); + } + s.env[k] = val; + } + } + return s; +} + +/** Library-level `with:` defaults, captured by `init` at instantiation. */ +let libraryDefaults: NodejsSettings = {}; + +/** + * Resolve the effective settings for one step invocation: + * run extension > run variables > library `with:` (the step's own `with:` + * params are applied by the caller on top). Invalid blocks fail the step. + */ +function resolveSettings(ctx: StepCtx): NodejsSettings { + const ext = parseSettingsBlock( + "extensions[nodejs]", + ctx.settings.extensions?.["nodejs"], + ); + const vars = parseSettingsBlock( + "variables[nodejs]", + ctx.settings.variables?.["nodejs"], + ); + const lib = libraryDefaults; + return { + nodeVersion: ext.nodeVersion ?? vars.nodeVersion ?? lib.nodeVersion, + installDir: ext.installDir ?? vars.installDir ?? lib.installDir, + nodePath: ext.nodePath ?? vars.nodePath ?? lib.nodePath, + cwd: ext.cwd ?? vars.cwd ?? lib.cwd, + timeoutMs: ext.timeoutMs ?? vars.timeoutMs ?? lib.timeoutMs, + env: { ...lib.env, ...vars.env, ...ext.env }, + }; +} + type Log = { tag: "out" | "err" | "sys"; line: string }; type Out = Record; @@ -58,14 +211,6 @@ function strictKeys(step: string, params: Record, allowed: stri } } -function reqString(step: string, params: Record, key: string): string { - const v = params[key]; - if (typeof v !== "string" || v === "") { - throw new StepError(`nodejs/${step}: '${key}' is required and must be a non-empty string`); - } - return v; -} - function optString(step: string, params: Record, key: string): string | undefined { const v = params[key]; if (v === undefined) return undefined; @@ -90,9 +235,13 @@ function optCwd(step: string, params: Record): string | undefin return (wd ?? cwd) as string | undefined; } -/** User env merges over the minimal PATH; every value must be a string. */ -function optEnv(step: string, params: Record): Record { - const env: Record = { PATH: DEFAULT_PATH }; +/** User env merges over the minimal PATH and any settings-level env. */ +function optEnv( + step: string, + params: Record, + base: Record = {}, +): Record { + const env: Record = { PATH: DEFAULT_PATH, ...base }; const v = params["env"]; if (v === undefined) return env; if (typeof v !== "object" || v === null || Array.isArray(v)) { @@ -172,14 +321,23 @@ interface InstallParsed { installDir: string; } -function parseInstallParams(step: string, params: Record): InstallParsed { - const nodeVersion = reqString(step, params, "node-version"); +function parseInstallParams( + step: string, + params: Record, + settings: NodejsSettings, +): InstallParsed { + const explicit = optString(step, params, "node-version"); + const nodeVersion = explicit ?? settings.nodeVersion; + if (nodeVersion === undefined) { + throw new StepError(`nodejs/${step}: 'node-version' is required and must be a non-empty string`); + } if (!EXACT_VERSION.test(nodeVersion) && !MAJOR_VERSION.test(nodeVersion)) { throw new StepError( `nodejs/${step}: 'node-version' must be an exact semver (e.g. 24.16.0) or a major / major.x (e.g. 24 or 24.x)`, ); } - const installDir = optString(step, params, "install-dir") ?? DEFAULT_INSTALL_DIR; + const installDir = + optString(step, params, "install-dir") ?? settings.installDir ?? DEFAULT_INSTALL_DIR; return { version: nodeVersion, installDir }; } @@ -254,7 +412,7 @@ function resolveVersion( function runInstall(step: string, params: Record, ctx: StepCtx): StepOutcome { const logs: Log[] = []; - const { version: requested, installDir } = parseInstallParams(step, params); + const { version: requested, installDir } = parseInstallParams(step, params, resolveSettings(ctx)); const arch = hostArch(ctx); const resolved = resolveVersion(ctx, requested, arch, logs); @@ -265,26 +423,35 @@ function runInstall(step: string, params: Record, ctx: StepCtx) const path = `${installDir}/${artifact}`; const nodePath = `${path}/bin/node`; - // Idempotent: a working cached node is reused, never re-downloaded. - const cached = runHost(ctx, { - executable: nodePath, - argv: ["--version"], + // Idempotent: a working cached node is reused, never re-downloaded. The + // host import hard-errors on spawn-ENOENT, so probe with /usr/bin/test + // first and only run `node --version` when the binary exists. + const probe = runHost(ctx, { + executable: "/usr/bin/test", + argv: ["-x", nodePath], timeoutMs: SMALL_TIMEOUT_MS, }); - if (cached.exitCode === 0) { - logs.push({ tag: "sys", line: `nodejs: ${artifact} already installed at ${path} (${cached.stdout.trim()})` }); - return { - success: true, - output: { - path, - "node-path": nodePath, - version, - stdout: cached.stdout, - stderr: cached.stderr, - exit_code: 0, - }, - logs, - }; + if (probe.exitCode === 0) { + const cached = runHost(ctx, { + executable: nodePath, + argv: ["--version"], + timeoutMs: SMALL_TIMEOUT_MS, + }); + if (cached.exitCode === 0) { + logs.push({ tag: "sys", line: `nodejs: ${artifact} already installed at ${path} (${cached.stdout.trim()})` }); + return { + success: true, + output: { + path, + "node-path": nodePath, + version, + stdout: cached.stdout, + stderr: cached.stderr, + exit_code: 0, + }, + logs, + }; + } } const tarballUrl = `${DIST_BASE}/v${version}/${artifact}.tar.xz`; @@ -387,19 +554,21 @@ function runExec( ctx: StepCtx, installedNodePath?: string, ): StepOutcome { + const settings = resolveSettings(ctx); const script = optString(step, params, "script"); const file = optString(step, params, "file"); if ((script === undefined) === (file === undefined)) { throw new StepError(`nodejs/${step}: exactly one of 'script' or 'file' is required`); } - const nodePath = installedNodePath ?? optString(step, params, "node-path") ?? DEFAULT_NODE_PATH; + const nodePath = + installedNodePath ?? optString(step, params, "node-path") ?? settings.nodePath ?? DEFAULT_NODE_PATH; if (!nodePath.startsWith("/")) { throw new StepError(`nodejs/${step}: 'node-path' must be an absolute path to the node executable`); } const args = optArgs(step, params); - const cwd = optCwd(step, params); - const env = optEnv(step, params); - const timeoutMs = optTimeoutMs(step, params); + const cwd = optCwd(step, params) ?? settings.cwd; + const env = optEnv(step, params, settings.env); + const timeoutMs = optTimeoutMs(step, params) ?? settings.timeoutMs; const argv = script !== undefined ? ["-e", script, ...args] : [file!, ...args]; const res = ctx.exec({ @@ -426,6 +595,12 @@ function runExec( export default defineSteps({ name: "nodejs", version: "0.1.0", + configSchema: { key: "nodejs", schema: NODEJS_CONFIG_SCHEMA }, + init(config) { + // Library-level `with:` defaults — validated once at instantiation; + // invalid defaults are fatal to the run, never silently ignored. + libraryDefaults = parseSettingsBlock("library with", config); + }, steps: { install: { description: diff --git a/test/nodejs.test.ts b/test/nodejs.test.ts index d17b92a..a00c1cc 100644 --- a/test/nodejs.test.ts +++ b/test/nodejs.test.ts @@ -59,16 +59,18 @@ function installHost(opts: { const arch = opts.arch ?? "x86_64"; const version = opts.version ?? "24.16.0"; const nodeArch = arch === "x86_64" ? "x64" : "arm64"; - let nodeCalls = 0; return fakeExec((req) => { const argv = req.argv ?? []; if (req.executable === "/usr/bin/uname") { return ok(argv[0] === "-s" ? `${opts.os ?? "Linux"}\n` : `${arch}\n`); } + // The cache probe: ENOENT at spawn is a host error, so the component + // checks existence with test(1) before running the cached binary. + if (req.executable === "/usr/bin/test") { + return opts.cached ? ok() : { exitCode: 1, stdout: "", stderr: "" }; + } if (req.executable.endsWith("/bin/node")) { - nodeCalls += 1; - if (opts.cached || nodeCalls > 1) return ok(`v${version}\n`); - return { exitCode: 1, stdout: "", stderr: "no such file" }; + return ok(`v${version}\n`); } if (req.executable === "/usr/bin/curl") { if (argv.includes("-o")) { @@ -277,6 +279,7 @@ describe("nodejs/install-exec", () => { const { calls, exec } = fakeExec((req) => { const argv = req.argv ?? []; if (req.executable === "/usr/bin/uname") return ok(argv[0] === "-s" ? "Linux\n" : "x86_64\n"); + if (req.executable === "/usr/bin/test") return ok(); if (req.executable.endsWith("/bin/node")) { return argv[0] === "--version" ? ok("v24.16.0\n") : ok("ran\n"); } @@ -315,6 +318,7 @@ describe("nodejs/install-exec", () => { const { exec } = fakeExec((req) => { const argv = req.argv ?? []; if (req.executable === "/usr/bin/uname") return ok(argv[0] === "-s" ? "Linux\n" : "x86_64\n"); + if (req.executable === "/usr/bin/test") return ok(); if (req.executable.endsWith("/bin/node")) { return argv[0] === "--version" ? ok("v24.16.0\n") @@ -342,3 +346,166 @@ describe("nodejs/install-exec", () => { } }); }); + +// --------------------------------------------------------------------------- +// Settings (RFC 009): extensions[nodejs] > variables[nodejs] > library with +// > built-in defaults; explicit step `with:` wins over everything. +// --------------------------------------------------------------------------- + +function settingsCtx( + exec: HostExec | undefined, + settings: { extensions?: Record; variables?: Record }, +): StepCtx { + const c = ctx(exec); + c.settings = { + vus: null, + duration_ms: null, + seed: null, + stages: null, + arrival: null, + variables: settings.variables ?? {}, + extensions: settings.extensions ?? {}, + }; + return c; +} + +/** Reset library-level `with:` defaults so module state never leaks between tests. */ +function resetLibraryWith() { + def.init?.(null); +} + +describe("nodejs settings", () => { + it("install takes node-version and install-dir from extensions[nodejs]", () => { + resetLibraryWith(); + const { calls, exec } = installHost(); + const res = testStep( + def, + settingsCtx(exec, { extensions: { nodejs: { "node-version": "24.16.0", "install-dir": "/opt/ext" } } }), + "install", + {}, + ); + assert.equal(res.success, true); + assert.equal( + (res.output as Record)["node-path"], + "/opt/ext/node-v24.16.0-linux-x64/bin/node", + ); + assert.ok(calls.some((c) => c.argv?.includes("/opt/ext/.node-v24.16.0-linux-x64.tar.xz"))); + }); + + it("explicit step params beat the run extension", () => { + resetLibraryWith(); + const { exec } = installHost(); + const res = testStep( + def, + settingsCtx(exec, { extensions: { nodejs: { "install-dir": "/opt/ext" } } }), + "install", + { "node-version": "24.16.0", "install-dir": "/opt/step" }, + ); + assert.equal(res.success, true); + assert.equal( + (res.output as Record)["node-path"], + "/opt/step/node-v24.16.0-linux-x64/bin/node", + ); + }); + + it("variables[nodejs] apply when no extension, library with applies below variables", () => { + def.init?.({ "install-dir": "/opt/lib", "node-version": "24.16.0" }); + try { + const { exec } = installHost(); + const res = testStep( + def, + settingsCtx(exec, { variables: { nodejs: { "install-dir": "/opt/vars" } } }), + "install", + {}, + ); + assert.equal(res.success, true); + assert.equal( + (res.output as Record)["node-path"], + "/opt/vars/node-v24.16.0-linux-x64/bin/node", + ); + } finally { + resetLibraryWith(); + } + }); + + it("library with defaults apply when run settings are silent", () => { + def.init?.({ "install-dir": "/opt/lib", "node-version": "24.16.0" }); + try { + const { exec } = installHost(); + const res = testStep(def, settingsCtx(exec, {}), "install", {}); + assert.equal(res.success, true); + assert.equal( + (res.output as Record)["node-path"], + "/opt/lib/node-v24.16.0-linux-x64/bin/node", + ); + } finally { + resetLibraryWith(); + } + }); + + it("exec merges env in precedence order: step > extension > variables > library with", () => { + def.init?.({ env: { A: "lib", B: "lib", C: "lib", D: "lib" } }); + try { + const { calls, exec } = fakeExec(() => ok()); + const res = testStep( + def, + settingsCtx(exec, { + variables: { nodejs: { env: { B: "vars", C: "vars", D: "vars" } } }, + extensions: { nodejs: { env: { C: "ext", D: "ext" }, cwd: "/ext/cwd", timeout_ms: 5000 } }, + }), + "exec", + { script: "1", env: { D: "step" } }, + ); + assert.equal(res.success, true); + const run = calls.find((c) => c.executable.endsWith("/node"))!; + assert.equal(run.env?.A, "lib"); + assert.equal(run.env?.B, "vars"); + assert.equal(run.env?.C, "ext"); + assert.equal(run.env?.D, "step"); + assert.equal(run.env?.PATH, "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"); + assert.equal(run.cwd, "/ext/cwd"); + assert.equal(run.timeoutMs, 5000); + } finally { + resetLibraryWith(); + } + }); + + it("exec takes node-path from settings when the step omits it", () => { + resetLibraryWith(); + const { calls, exec } = fakeExec(() => ok()); + const res = testStep( + def, + settingsCtx(exec, { extensions: { nodejs: { "node-path": "/opt/node/bin/node" } } }), + "exec", + { script: "1" }, + ); + assert.equal(res.success, true); + assert.equal(calls[0]!.executable, "/opt/node/bin/node"); + }); + + it("rejects invalid settings blocks", () => { + resetLibraryWith(); + const { exec } = fakeExec(() => ok()); + for (const settings of [ + { extensions: { nodejs: { bogus: 1 } } }, + { extensions: { nodejs: { env: { A: 1 } } } }, + { extensions: { nodejs: { "node-path": "relative/node" } } }, + { extensions: { nodejs: { "node-version": "nope" } } }, + { extensions: { nodejs: { timeout_ms: -5 } } }, + { variables: { nodejs: "not-an-object" } }, + { variables: { nodejs: { cwd: "/a", "working-directory": "/b" } } }, + ]) { + assert.throws( + () => testStep(def, settingsCtx(exec, settings), "exec", { script: "1" }), + StepError, + JSON.stringify(settings), + ); + } + }); + + it("rejects an invalid library with block at init", () => { + assert.throws(() => def.init?.({ "install-dir": 42 }), StepError); + assert.throws(() => def.init?.({ unknown: true }), StepError); + resetLibraryWith(); + }); +});