diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dbbeb933..92ff6941 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,3 +25,45 @@ jobs: run: | python3 -m unittest discover -s quality -p 'test_*.py' python3 -m unittest discover -s adapters/opencode -p 'test_*.py' + + worker-image: + name: Worker image — Node 24 and fnm + runs-on: ubuntu-latest + timeout-minutes: 45 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - name: Extract embedded Dockerfile + run: | + python3 - <<'PY' + from pathlib import Path + source = Path("src/sh.rs").read_text(encoding="utf-8") + prefix = 'pub const DF: &str = r#"' + assert source.count(prefix) == 1, "expected one worker Dockerfile" + dockerfile = source.split(prefix, 1)[1].split('"#;', 1)[0] + Path("worker.Dockerfile").write_text(dockerfile, encoding="utf-8") + prefix = 'pub const PRE: &str = "' + assert source.count(prefix) == 1, "expected one shell prelude" + pre = source.split(prefix, 1)[1].split('";\n', 1)[0] + Path("pre.sh").write_text(pre.encode().decode("unicode_escape"), encoding="utf-8") + PY + - name: Build actual worker image + run: docker build --pull -t apollo-office-worker-smoke -f worker.Dockerfile . + - name: Verify image Node and cross-repository fnm defaults + run: | + docker run --rm -v "$PWD/pre.sh:/pre.sh:ro" apollo-office-worker-smoke bash -euc ' + node --version | grep -Eq "^v24\\." + fnm --version + mkdir -p /work/uses-node-20/sub /work/uses-node-22 /work/no-node-version + printf "20\\n" > /work/uses-node-20/.nvmrc + printf "22\\n" > /work/uses-node-22/.nvmrc + . /pre.sh + for d in /work/uses-node-20 /work/uses-node-22; do (cd "$d" && fnm use --install-if-missing); done + cd /work/uses-node-20/sub + node --version | grep -Eq "^v20\\." + cd /work/uses-node-22 + node --version | grep -Eq "^v22\\." + cd /work/no-node-version + node --version + node --version | grep -Eq "^v24\\." + bash -c ". /pre.sh; node --version" | grep -Eq "^v24\\." + ' diff --git a/src/pipe.rs b/src/pipe.rs index ac577966..da88c6ce 100644 --- a/src/pipe.rs +++ b/src/pipe.rs @@ -10,6 +10,26 @@ use std::collections::BTreeSet; pub const RND: u64 = 2; const CIT: u64 = 150 * 60; +const NODE_VERSION_SELECTION: &str = r#"if [ "${APOLLO_OFFICE_FNM:-}" != 1 ] || ! command -v fnm >/dev/null 2>&1; then exit 0; fi +if [ -f .nvmrc ] || [ -f .node-version ] || { [ -f package.json ] && python3 -c 'import json,sys; e=json.load(open("package.json", encoding="utf-8")).get("engines", {}); sys.exit(0 if isinstance(e, dict) and isinstance(e.get("node"), str) and e["node"].strip() else 1)' >/dev/null 2>&1; }; then + fnm use --install-if-missing --resolve-engines +fi"#; +const NODE_VERSION_DIAGNOSTIC: &str = r#"source= +required= +if [ -f .nvmrc ]; then + source=.nvmrc + required=$(sed 's/#.*//' .nvmrc | sed -n '/[^[:space:]]/{s/^[[:space:]]*//;s/[[:space:]]*$//;p;q;}') +elif [ -f .node-version ]; then + source=.node-version + required=$(sed 's/#.*//' .node-version | sed -n '/[^[:space:]]/{s/^[[:space:]]*//;s/[[:space:]]*$//;p;q;}') +elif [ -f package.json ] && command -v python3 >/dev/null 2>&1; then + source=package.json + required=$(python3 -c 'import json; e=json.load(open("package.json", encoding="utf-8")).get("engines", {}); print(e.get("node", "") if isinstance(e, dict) else "")' 2>/dev/null) || required= +fi +if [ -n "$required" ]; then + have=$(node --version 2>/dev/null) || have=unavailable + printf 'Node hint: %s requests %s; the environment reports %s. Check version selection and setup tooling.\n' "$source" "$required" "$have" +fi"#; pub fn gitb() -> String { std::env::var("APOLLO_OFFICE_REMOTE").unwrap_or_else(|_| "https://github.com/".into()) @@ -260,12 +280,34 @@ async fn prep(a: &Ax, j: &mut Job) -> R<()> { ok(a, j, &format!("git checkout -q -B {} refs/ao/head", q(&br)), 1800).await?; j.d["old"] = json!(ok(a, j, "git rev-parse HEAD", 60).await?); } + // Best-effort Node provisioning only in the managed build image. Do not + // reject a repository here: its setup may install or select Node itself. + let node_selection = x(a, j, &format!("bash -c {} 2>&1", q(NODE_VERSION_SELECTION)), 360).await; + if node_selection.c != 0 { + a.say( + "repro", + &format!( + "[{}] optional Node selection failed (setup will continue): {}", + j.h(), + crate::sh::last(node_selection.all().trim(), 240) + ), + Some(j.id), + ); + } let su = rp(a, &j.repo)["setup"].as_str().unwrap_or("").trim().to_string(); if !su.is_empty() { a.say("repro", &format!("[{}] setup: {}", j.h(), crate::sh::head(&su, 80)), Some(j.id)); let r = x(a, j, &format!("to 1800 bash -c {} 2>&1 | tail -c 3000; exit ${{PIPESTATUS[0]}}", q(&su)), 1900).await; if r.c != 0 { - return drop(format!("setup command failed (exit {}): {}", r.c, crate::sh::last(r.o.trim(), 300))); + let mut reason = format!("setup command failed (exit {}): {}", r.c, crate::sh::last(r.o.trim(), 300)); + // Diagnostic only: the original setup error remains authoritative. + // In particular, a repository may install Node through its own setup. + let hint = x(a, j, &format!("bash -c {} 2>&1", q(NODE_VERSION_DIAGNOSTIC)), 60).await; + if hint.c == 0 && !hint.o.trim().is_empty() { + reason.push('\n'); + reason.push_str(&crate::sh::last(hint.o.trim(), 500)); + } + return drop(reason); } ok(a, j, "git checkout -q -- . 2>/dev/null; true", 60).await?; } @@ -562,7 +604,7 @@ async fn ci0(a: &Ax, j: &mut Job) -> R { if let Some(k) = t.1.filter(|_| !it) { it = true; a.say("ci", &format!("[{}] {c} needs {k}, installing it", j.h()), Some(j.id)); - let r = hx(a, &j.h(), &format!("{}cargo install {} --locked 2>&1 | tail -3", crate::sh::PRE, q(&k)), 2400).await; + let r = hx(a, &j.h(), &format!("cargo install {} --locked 2>&1 | tail -3", q(&k)), 2400).await; if r.c == 0 { continue; } @@ -1866,6 +1908,93 @@ pub async fn guard(a: Ax) { mod t { use super::*; + #[cfg(unix)] + fn run_node_script(script: &str, nvmrc: Option<&str>, node_version: Option<&str>, package: Option<&str>, enable_fnm: bool) -> std::process::Output { + use std::os::unix::fs::PermissionsExt; + + let root = std::env::temp_dir().join(format!( + "apollo-node-env-{}-{}", + std::process::id(), + hex::encode(rand::random::<[u8; 8]>()) + )); + let bin = root.join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + for (file, body) in [(".nvmrc", nvmrc), (".node-version", node_version), ("package.json", package)] { + if let Some(body) = body { + std::fs::write(root.join(file), body).unwrap(); + } + } + let fnm = bin.join("fnm"); + std::fs::write(&fnm, "#!/bin/sh\nprintf 'fnm-called: %s\\n' \"$*\"\n").unwrap(); + let mut permissions = std::fs::metadata(&fnm).unwrap().permissions(); + permissions.set_mode(0o700); + std::fs::set_permissions(&fnm, permissions).unwrap(); + let output = std::process::Command::new("/bin/bash") + .arg("-c") + .arg(script) + .current_dir(&root) + .env("PATH", format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default())) + .env("APOLLO_OFFICE_FNM", if enable_fnm { "1" } else { "0" }) + .output() + .unwrap(); + let _ = std::fs::remove_dir_all(root); + output + } + + #[cfg(unix)] + #[test] + fn node_selection_is_optional_and_supports_version_sources() { + let none = run_node_script(NODE_VERSION_SELECTION, None, None, None, true); + assert!(none.status.success()); + assert!(none.stdout.is_empty()); + + let pinned = run_node_script(NODE_VERSION_SELECTION, Some("v24.1.0\n"), None, None, true); + assert!(pinned.status.success()); + assert!(String::from_utf8_lossy(&pinned.stdout).contains("fnm-called: use --install-if-missing --resolve-engines")); + + let alias = run_node_script(NODE_VERSION_SELECTION, Some("lts/iron\n"), None, None, true); + assert!(alias.status.success()); + assert!(String::from_utf8_lossy(&alias.stdout).contains("fnm-called: use")); + + let node_version = run_node_script(NODE_VERSION_SELECTION, None, Some("22\n"), None, true); + assert!(node_version.status.success()); + assert!(String::from_utf8_lossy(&node_version.stdout).contains("fnm-called: use")); + + let engine = run_node_script(NODE_VERSION_SELECTION, None, None, Some(r#"{"engines":{"node":">=22 <25"}}"#), true); + assert!(engine.status.success()); + assert!(String::from_utf8_lossy(&engine.stdout).contains("fnm-called: use")); + + let no_engine = run_node_script(NODE_VERSION_SELECTION, None, None, Some(r#"{"name":"no-node-requirement"}"#), true); + assert!(no_engine.status.success()); + assert!(no_engine.stdout.is_empty()); + + let host = run_node_script(NODE_VERSION_SELECTION, Some("24\n"), None, None, false); + assert!(host.status.success()); + assert!(host.stdout.is_empty()); + } + + #[cfg(unix)] + #[test] + fn node_diagnostic_only_reports_existing_requirements() { + let none = run_node_script(NODE_VERSION_DIAGNOSTIC, None, None, None, false); + assert!(none.status.success()); + assert!(none.stdout.is_empty()); + + let pinned = run_node_script(NODE_VERSION_DIAGNOSTIC, Some("24 # pinned major\n"), None, None, false); + let message = String::from_utf8_lossy(&pinned.stdout); + assert!(pinned.status.success()); + assert!(message.contains(".nvmrc requests 24;"), "{message}"); + + let node_version = run_node_script(NODE_VERSION_DIAGNOSTIC, None, Some("22\n"), None, false); + assert!(String::from_utf8_lossy(&node_version.stdout).contains(".node-version requests 22;")); + + let engine = run_node_script(NODE_VERSION_DIAGNOSTIC, None, None, Some(r#"{"engines":{"node":">=20 <25"}}"#), false); + assert!(String::from_utf8_lossy(&engine.stdout).contains("package.json requests >=20 <25;")); + + let ignored = run_node_script(NODE_VERSION_DIAGNOSTIC, None, None, Some(r#"{"name":"no-engines"}"#), false); + assert!(ignored.stdout.is_empty()); + } + #[cfg(unix)] #[tokio::test] async fn cancelled_ci_releases_build_capacity() { diff --git a/src/sh.rs b/src/sh.rs index 5b2dc4db..4e1d80ae 100644 --- a/src/sh.rs +++ b/src/sh.rs @@ -341,7 +341,7 @@ pub fn hbid(a: &App, h: &str) -> String { ho(a, h).map(|x| hb(a, &x)).unwrap_or_else(|| "/work".into()) } -pub const PRE: &str = "ulimit -n 10240 2>/dev/null; export PATH=\"$HOME/.cargo/bin:$HOME/.local/bin:$HOME/go/bin:/usr/local/go/bin:/opt/homebrew/bin:/usr/local/bin:$PATH\" CARGO_TERM_COLOR=never NO_COLOR=1 CI=1 GIT_TERMINAL_PROMPT=0 CARGO_PROFILE_DEV_DEBUG=line-tables-only CARGO_PROFILE_TEST_DEBUG=line-tables-only CARGO_PROFILE_RELEASE_LTO=off CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16 CARGO_PROFILE_BENCH_LTO=off; to() { s=$1; shift; if command -v timeout >/dev/null 2>&1 && timeout --version 2>/dev/null | head -n 1 | grep -q 'coreutils'; then timeout -k 10 \"$s\" \"$@\"; else \"$@\"; fi; }\n"; +pub const PRE: &str = "ulimit -n 10240 2>/dev/null; export PATH=\"$HOME/.cargo/bin:$HOME/.local/bin:$HOME/go/bin:/usr/local/go/bin:/opt/homebrew/bin:/usr/local/bin:$PATH\" CARGO_TERM_COLOR=never NO_COLOR=1 CI=1 GIT_TERMINAL_PROMPT=0 CARGO_PROFILE_DEV_DEBUG=line-tables-only CARGO_PROFILE_TEST_DEBUG=line-tables-only CARGO_PROFILE_RELEASE_LTO=off CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16 CARGO_PROFILE_BENCH_LTO=off; to() { s=$1; shift; if command -v timeout >/dev/null 2>&1 && timeout --version 2>/dev/null | head -n 1 | grep -q 'coreutils'; then timeout -k 10 \"$s\" \"$@\"; else \"$@\"; fi; }\nif [ \"${APOLLO_OFFICE_FNM:-}\" = 1 ] && command -v fnm >/dev/null 2>&1; then _ao_fnm_env=$(fnm env --shell bash --resolve-engines --version-file-strategy recursive) && { eval \"$_ao_fnm_env\"; _ao_fnm_link=${FNM_MULTISHELL_PATH:-}; trap 'if [ -L \"$_ao_fnm_link\" ]; then rm -f -- \"$_ao_fnm_link\"; fi' EXIT; _ao_node() { local d=$PWD; while :; do if [ -f \"$d/.nvmrc\" ] || [ -f \"$d/.node-version\" ]; then fnm use --silent-if-unchanged >/dev/null 2>&1; break; fi; if [ \"$d\" = / ]; then fnm use --silent-if-unchanged system >/dev/null 2>&1; break; fi; d=${d%/*}; d=${d:-/}; done; hash -r; }; cd() { builtin cd \"$@\" || return $?; _ao_node || true; }; _ao_node || true; }; fi\n"; fn sshv(h: &Ho) -> Vec { let mut v: Vec = vec!["-o".into(), "ConnectTimeout=15".into(), "-o".into(), "ServerAliveInterval=15".into(), "-o".into(), "ServerAliveCountMax=4".into(), "-o".into(), "BatchMode=yes".into()]; @@ -389,7 +389,9 @@ async fn hxo(a: &App, id: &str, s: &str, t: u64, ln: Option<&(dyn Fn(&str) + Sen // active everywhere, including Windows/macOS without GNU coreutils timeout. let boundary=format!("APOLLO_JOB_{}",hex::encode(rand::random::<[u8;16]>())); let body=format!("if command -v timeout >/dev/null 2>&1 && timeout --version 2>/dev/null | head -n 1 | grep -q 'coreutils'; then exec timeout -k 5 {t}s bash -s; else exec bash -s; fi <<'{boundary}'\n{PRE}{s}\n{boundary}\n"); - let i = format!("{PRE}{}{body}", jobs(a, &h)); + // Only the inner Bash session initializes fnm; its exit trap removes + // its own multishell symlink after the command has completed. + let i = format!("{}{body}", jobs(a, &h)); let mut command: Vec = if h.dk { vec!["docker".into(), "exec".into(), "-i".into(), CT.into()] } else { vec![] }; command.extend(["bash".into(), "-s".into()]); let (p, v) = if h.ssh.is_empty() { @@ -411,15 +413,40 @@ pub async fn hx(a: &App, id: &str, s: &str, t: u64) -> Out { hxl(a, id, s, t, None).await } -pub const DF: &str = r#"FROM rust:1-trixie +pub const DF: &str = r#"FROM node:24-trixie-slim AS node24 +FROM rust:1-trixie RUN apt-get update && apt-get install -y --no-install-recommends \ pkg-config libssl-dev clang cmake git curl ca-certificates procps xz-utils unzip libxdo-dev mesa-vulkan-drivers \ - python3 python3-pip python3-venv python3-dev nodejs npm golang-go \ + python3 python3-pip python3-venv python3-dev golang-go \ libasound2-dev libfontconfig1-dev libfreetype-dev libgl1-mesa-dev libgtk-3-dev libwayland-dev \ libx11-dev libxcursor-dev libxi-dev libxkbcommon-dev libxrandr-dev libudev-dev xvfb \ && rm -rf /var/lib/apt/lists/* +# Use the official Node 24 LTS distribution rather than Debian's older nodejs. +COPY --from=node24 /usr/local/bin/node /usr/local/bin/node +COPY --from=node24 /usr/local/lib/node_modules /usr/local/lib/node_modules +COPY --from=node24 /usr/local/include/node /usr/local/include/node +RUN ln -sf ../lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm \ + && ln -sf ../lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx \ + && npm --version >/dev/null +# Install an immutable, checksum-verified fnm v1.39.0 release archive. +RUN set -eu; \ + case "$(dpkg --print-architecture)" in \ + amd64) asset=fnm-linux.zip; checksum=7807664f39d39fc518da1c35ba0181e4b3267603c4b1dedeb4b5fc6ae440a224 ;; \ + arm64) asset=fnm-arm64.zip; checksum=4eaff58b2c5bf30d0934027572dd0b5bbb60d2a1af309230b53662d4b1d45599 ;; \ + *) echo "Unsupported architecture for fnm release" >&2; exit 1 ;; \ + esac; \ + curl --fail --location --retry 3 --silent --show-error "https://github.com/Schniz/fnm/releases/download/v1.39.0/$asset" -o /tmp/fnm.zip; \ + echo "$checksum /tmp/fnm.zip" | sha256sum --check --status; \ + unzip -j /tmp/fnm.zip fnm -d /usr/local/bin; \ + chmod 755 /usr/local/bin/fnm; \ + rm /tmp/fnm.zip; \ + fnm --version; \ + node --version | grep -Eq '^v24\.' +# Prevent installing a project-specific version from changing the image default. +ENV FNM_DIR=/opt/apollo-fnm +RUN fnm alias system default RUN rustup component add rustfmt clippy && rustup target add wasm32-unknown-unknown && npm install -g pnpm yarn && pip3 install --break-system-packages pytest -ENV CARGO_TERM_COLOR=never CARGO_INCREMENTAL=0 PIP_BREAK_SYSTEM_PACKAGES=1 +ENV CARGO_TERM_COLOR=never CARGO_INCREMENTAL=0 PIP_BREAK_SYSTEM_PACKAGES=1 APOLLO_OFFICE_FNM=1 WORKDIR /work "#; @@ -559,6 +586,54 @@ mod tests { assert_eq!(super::clip("short", 6000), "short"); } + + #[cfg(unix)] + #[test] + fn fnm_activation_does_not_turn_successful_cd_into_a_failure() { + use std::os::unix::fs::{symlink, PermissionsExt}; + + let root = std::env::temp_dir().join(format!( + "apollo-fnm-cd-{}-{}", + std::process::id(), + hex::encode(rand::random::<[u8; 8]>()) + )); + let bin = root.join(".local").join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + let target = root.join("node-24"); + std::fs::create_dir_all(&target).unwrap(); + let multishell = root.join("fnm-multishell"); + symlink(&target, &multishell).unwrap(); + let fnm = bin.join("fnm"); + // Simulate a valid fnm shell environment, but an unavailable Node pin. + std::fs::write( + &fnm, + "#!/bin/sh\nif [ \"$1\" = env ]; then printf 'export FNM_MULTISHELL_PATH=%s\\n' \"$APOLLO_TEST_MULTISHELL\"; exit 0; fi\nexit 9\n", + ).unwrap(); + let mut permissions = std::fs::metadata(&fnm).unwrap().permissions(); + permissions.set_mode(0o700); + std::fs::set_permissions(&fnm, permissions).unwrap(); + + let script = format!( + "{}cd {} && printf 'entered\n'; cd /this-directory-must-not-exist-ao-fnm-test >/dev/null 2>&1 && echo invalid || echo denied", + super::PRE, + super::q(&root.display().to_string()) + ); + let output = std::process::Command::new("/bin/bash") + .arg("-c") + .arg(script) + .env("APOLLO_OFFICE_FNM", "1") + .env("APOLLO_TEST_MULTISHELL", &multishell) + .env("HOME", &root) + .env("PATH", format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default())) + .output() + .unwrap(); + let cleaned = std::fs::symlink_metadata(&multishell).is_err(); + let _ = std::fs::remove_dir_all(root); + assert!(cleaned, "fnm multishell symlink leaked after the Bash command"); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); + assert_eq!(String::from_utf8_lossy(&output.stdout), "entered\ndenied\n"); + } + #[cfg(unix)] #[tokio::test] async fn timeout_kills_child_processes() {