|
| 1 | +/** |
| 2 | + * Transactional npm self-update: stage -> verify -> swap -> rollback (#1942 / #1849). |
| 3 | + * |
| 4 | + * The legacy path ran `npm install -g` straight into the live global tree, so a |
| 5 | + * failure after npm removed the old files left a file-less package skeleton with no |
| 6 | + * recovery. This module stages the new version into a SIBLING directory of the live |
| 7 | + * package (same volume, so directory renames are atomic-ish and never cross devices), |
| 8 | + * verifies the staged tree with a manifest before anything live is touched, then swaps |
| 9 | + * live -> backup -> stage-into-live with a reverse-rename rollback on failure and a |
| 10 | + * recovery marker on double fault. |
| 11 | + * |
| 12 | + * Layout (siblings, never children — a child would travel WITH the live rename and the |
| 13 | + * live dir cannot move into its own subtree): |
| 14 | + * <scopeDir>/opencodex live package |
| 15 | + * <scopeDir>/.ocx-staging-<ts>/ npm --prefix root (contains node_modules/...) |
| 16 | + * <scopeDir>/.ocx-backup-<ts>/opencodex previous live tree during/after the swap |
| 17 | + * <scopeDir>/.ocx-recovery.json double-fault marker with a one-line restore |
| 18 | + */ |
| 19 | +import { spawnSync } from "node:child_process"; |
| 20 | +import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"; |
| 21 | +import { dirname, join } from "node:path"; |
| 22 | + |
| 23 | +/** Verification manifest for a staged (or live) package tree. */ |
| 24 | +export function verifyInstallTree(packageDir, expectedVersion) { |
| 25 | + const failures = []; |
| 26 | + let pkg; |
| 27 | + try { |
| 28 | + pkg = JSON.parse(readFileSync(join(packageDir, "package.json"), "utf8")); |
| 29 | + } catch (error) { |
| 30 | + return { ok: false, failures: ["package.json unreadable: " + (error?.message ?? String(error))] }; |
| 31 | + } |
| 32 | + if (expectedVersion && pkg.version !== expectedVersion) { |
| 33 | + failures.push("package.json version " + pkg.version + " != expected " + expectedVersion); |
| 34 | + } |
| 35 | + const launcher = join(packageDir, "bin", "ocx.mjs"); |
| 36 | + try { |
| 37 | + const st = statSync(launcher); |
| 38 | + if (!st.isFile() || st.size < 1024) failures.push("bin/ocx.mjs missing or truncated"); |
| 39 | + } catch { |
| 40 | + failures.push("bin/ocx.mjs absent"); |
| 41 | + } |
| 42 | + // Sentinel direct deps: each must have an intact package.json. The bundled Bun dep is |
| 43 | + // the load-bearing one — without it the launcher cannot start the proxy at all. |
| 44 | + const deps = Object.keys(pkg.dependencies ?? {}); |
| 45 | + const sentinels = deps.filter(name => name === "bun" || name === "zod").length > 0 |
| 46 | + ? deps.filter(name => name === "bun" || name === "zod") |
| 47 | + : deps.slice(0, 2); |
| 48 | + for (const name of sentinels) { |
| 49 | + const depPkg = join(packageDir, "node_modules", ...name.split("/"), "package.json"); |
| 50 | + if (!existsSync(depPkg)) failures.push("sentinel dependency missing: " + name); |
| 51 | + } |
| 52 | + return failures.length === 0 ? { ok: true, failures: [] } : { ok: false, failures }; |
| 53 | +} |
| 54 | + |
| 55 | +function stampedName(prefix) { |
| 56 | + return prefix + "-" + new Date().toISOString().replace(/[:.]/g, "-"); |
| 57 | +} |
| 58 | + |
| 59 | +function recoveryMarkerPath(scopeDir) { |
| 60 | + return join(scopeDir, ".ocx-recovery.json"); |
| 61 | +} |
| 62 | + |
| 63 | +/** Startup probe: restore a backup when the live tree is broken (D4 power-loss rows). */ |
| 64 | +export function bootRestoreProbe(packageDir, deps = {}) { |
| 65 | + const rename = deps.rename ?? renameSync; |
| 66 | + const scopeDir = dirname(packageDir); |
| 67 | + let backups = []; |
| 68 | + try { |
| 69 | + backups = readdirSync(scopeDir).filter(name => name.startsWith(".ocx-backup-")).sort(); |
| 70 | + } catch { |
| 71 | + return { action: "none" }; |
| 72 | + } |
| 73 | + if (backups.length === 0) return { action: "none" }; |
| 74 | + const liveOk = existsSync(join(packageDir, "package.json")) |
| 75 | + && verifyInstallTree(packageDir).ok; |
| 76 | + const newestBackup = join(scopeDir, backups[backups.length - 1], "opencodex"); |
| 77 | + if (liveOk) { |
| 78 | + // Live is healthy: the backups are leftovers from a completed swap. Reap them. |
| 79 | + for (const name of backups) { |
| 80 | + try { rmSync(join(scopeDir, name), { recursive: true, force: true }); } catch { /* keep */ } |
| 81 | + } |
| 82 | + try { rmSync(recoveryMarkerPath(scopeDir), { force: true }); } catch { /* keep */ } |
| 83 | + return { action: "reaped", count: backups.length }; |
| 84 | + } |
| 85 | + if (!existsSync(join(newestBackup, "package.json"))) return { action: "none" }; |
| 86 | + try { |
| 87 | + try { rmSync(packageDir, { recursive: true, force: true }); } catch { /* may not exist */ } |
| 88 | + rename(newestBackup, packageDir); |
| 89 | + return { action: "restored", from: newestBackup }; |
| 90 | + } catch (error) { |
| 91 | + return { action: "failed", error: error?.message ?? String(error) }; |
| 92 | + } |
| 93 | +} |
| 94 | + |
| 95 | +/** |
| 96 | + * Run the transactional update. `runNpm(args, opts)` is injected so the caller keeps |
| 97 | + * its hardened npm resolution (npm-invocation.mjs) and logging. |
| 98 | + */ |
| 99 | +export function transactionalNpmUpdate({ |
| 100 | + packageDir, |
| 101 | + pkgName, |
| 102 | + targetVersion, |
| 103 | + tag, |
| 104 | + runNpm, |
| 105 | + log = () => {}, |
| 106 | + deps = {}, |
| 107 | +}) { |
| 108 | + const rename = deps.rename ?? renameSync; |
| 109 | + const scopeDir = dirname(packageDir); |
| 110 | + const stageRoot = join(scopeDir, stampedName(".ocx-staging")); |
| 111 | + const stagedPackage = join(stageRoot, "node_modules", ...pkgName.split("/")); |
| 112 | + |
| 113 | + // D1: stage to the side. --prefix keeps npm entirely inside stageRoot; the live tree |
| 114 | + // and the npm bin shims are untouched until the swap. |
| 115 | + mkdirSync(stageRoot, { recursive: true }); |
| 116 | + const spec = pkgName + "@" + (targetVersion || tag); |
| 117 | + log("Staging " + spec + " into " + stageRoot); |
| 118 | + const install = runNpm(["install", "--prefix", stageRoot, "--no-audit", "--no-fund", spec]); |
| 119 | + if (install.status !== 0) { |
| 120 | + try { rmSync(stageRoot, { recursive: true, force: true }); } catch { /* best effort */ } |
| 121 | + return { ok: false, phase: "stage", error: "npm staging install failed (" + (install.status ?? "?") + ")" }; |
| 122 | + } |
| 123 | + |
| 124 | + // D2: verify INSIDE the stage. Live is still untouched on any failure here. |
| 125 | + const staged = verifyInstallTree(stagedPackage, targetVersion || undefined); |
| 126 | + if (!staged.ok) { |
| 127 | + try { rmSync(stageRoot, { recursive: true, force: true }); } catch { /* best effort */ } |
| 128 | + return { ok: false, phase: "verify", error: "staged tree failed verification: " + staged.failures.join("; ") }; |
| 129 | + } |
| 130 | + |
| 131 | + // D3: swap. live -> backup, stage -> live, re-verify live, rollback on failure. |
| 132 | + const backupRoot = join(scopeDir, stampedName(".ocx-backup")); |
| 133 | + const backupPackage = join(backupRoot, "opencodex"); |
| 134 | + mkdirSync(backupRoot, { recursive: true }); |
| 135 | + try { |
| 136 | + rename(packageDir, backupPackage); |
| 137 | + } catch (error) { |
| 138 | + try { rmSync(stageRoot, { recursive: true, force: true }); } catch { /* best effort */ } |
| 139 | + try { rmSync(backupRoot, { recursive: true, force: true }); } catch { /* best effort */ } |
| 140 | + return { ok: false, phase: "swap-backup", error: "could not move live tree aside: " + (error?.message ?? String(error)) }; |
| 141 | + } |
| 142 | + try { |
| 143 | + rename(stagedPackage, packageDir); |
| 144 | + } catch (error) { |
| 145 | + // Rollback: reverse the first rename. Double fault leaves the recovery marker. |
| 146 | + try { |
| 147 | + rename(backupPackage, packageDir); |
| 148 | + try { rmSync(stageRoot, { recursive: true, force: true }); } catch { /* best effort */ } |
| 149 | + try { rmSync(backupRoot, { recursive: true, force: true }); } catch { /* best effort */ } |
| 150 | + return { ok: false, phase: "swap-live", rolledBack: true, error: "could not place staged tree: " + (error?.message ?? String(error)) }; |
| 151 | + } catch (rollbackError) { |
| 152 | + writeFileSync(recoveryMarkerPath(scopeDir), JSON.stringify({ |
| 153 | + at: new Date().toISOString(), |
| 154 | + backup: backupPackage, |
| 155 | + live: packageDir, |
| 156 | + restore: 'move "' + backupPackage + '" back to "' + packageDir + '"', |
| 157 | + error: String(error?.message ?? error), |
| 158 | + rollbackError: String(rollbackError?.message ?? rollbackError), |
| 159 | + }, null, 2)); |
| 160 | + return { ok: false, phase: "double-fault", rolledBack: false, error: "swap and rollback both failed; recovery marker written at " + recoveryMarkerPath(scopeDir) }; |
| 161 | + } |
| 162 | + } |
| 163 | + const liveCheck = verifyInstallTree(packageDir, targetVersion || undefined); |
| 164 | + if (!liveCheck.ok) { |
| 165 | + try { |
| 166 | + rmSync(packageDir, { recursive: true, force: true }); |
| 167 | + rename(backupPackage, packageDir); |
| 168 | + try { rmSync(stageRoot, { recursive: true, force: true }); } catch { /* best effort */ } |
| 169 | + try { rmSync(backupRoot, { recursive: true, force: true }); } catch { /* best effort */ } |
| 170 | + return { ok: false, phase: "post-verify", rolledBack: true, error: "live tree failed post-swap verification: " + liveCheck.failures.join("; ") }; |
| 171 | + } catch (rollbackError) { |
| 172 | + writeFileSync(recoveryMarkerPath(scopeDir), JSON.stringify({ |
| 173 | + at: new Date().toISOString(), |
| 174 | + backup: backupPackage, |
| 175 | + live: packageDir, |
| 176 | + restore: 'move "' + backupPackage + '" back to "' + packageDir + '"', |
| 177 | + error: "post-swap verification failed: " + liveCheck.failures.join("; "), |
| 178 | + rollbackError: String(rollbackError?.message ?? rollbackError), |
| 179 | + }, null, 2)); |
| 180 | + return { ok: false, phase: "double-fault", rolledBack: false, error: "post-verify rollback failed; recovery marker written" }; |
| 181 | + } |
| 182 | + } |
| 183 | + // Success: stage scaffolding is disposable now; the backup stays until the next |
| 184 | + // healthy boot reaps it (bootRestoreProbe) — the process that spawned this update may |
| 185 | + // still hold the old cwd. |
| 186 | + try { rmSync(stageRoot, { recursive: true, force: true }); } catch { /* best effort */ } |
| 187 | + return { ok: true, phase: "done", backup: backupPackage }; |
| 188 | +} |
| 189 | + |
0 commit comments