From 7e3e5e7c7f36f07fe2f6c989c92a0cfb887217a4 Mon Sep 17 00:00:00 2001 From: Arthurvroum Date: Wed, 25 Nov 2026 03:44:43 +0100 Subject: [PATCH] fix: keep the working CLI when a release update fails The updater deleted and replaced bin, lib, config and libexec one at a time, then looked for the new CLI in the live folder. An archive without a CLI displaced a working one, and a failed rename could pair new binaries with old libraries. - The staged release is checked before anything is touched: without a CLI, the installed version stays as it is. - The installed folders are moved aside, the staged ones moved in, and on any failure the new ones are removed and the old ones put back. The old copy is deleted only once the new layout is complete. - At startup, an update interrupted in between is rolled back, or its leftover copy deleted when the new release is complete. - The stored version is only updated after a successful install, as before. Fixes #38 --- src/ctrace/BinaryUpdater.ts | 143 +++++++++++++++++++++++++-------- src/test/binaryUpdater.test.ts | 98 +++++++++++++++++++++- 2 files changed, 208 insertions(+), 33 deletions(-) diff --git a/src/ctrace/BinaryUpdater.ts b/src/ctrace/BinaryUpdater.ts index 6b3b60c..4ed50d0 100755 --- a/src/ctrace/BinaryUpdater.ts +++ b/src/ctrace/BinaryUpdater.ts @@ -48,6 +48,7 @@ async function doEnsureBinary(context: vscode.ExtensionContext, output: vscode.O const binDir = path.join(globalStorage, 'bin'); await fs.promises.mkdir(binDir, { recursive: true }); + await recoverInterruptedUpdate(binDir); const downloadedBinaryPath = await getExtractedBinaryPath(binDir); const lastCheck = context.globalState.get('coretrace-last-update-check') || 0; @@ -257,8 +258,6 @@ export async function downloadAndExtract(url: string, assetName: string, destDir const tmpDir = path.join(destDir, `tmp-${timestamp}`); await fs.promises.mkdir(tmpDir, { recursive: true }); - const candidates = ['ctrace', 'coretrace', 'ctrace.exe', 'coretrace.exe']; - try { if (assetName.toLowerCase().endsWith('.dmg')) { // hdiutil cannot read from a stream: save the image, then mount it. @@ -281,45 +280,125 @@ export async function downloadAndExtract(url: string, assetName: string, destDir if (progressListener) { progressListener("Finishing..."); } + await installStagedRelease(tmpDir, destDir); + } finally { + clearTimeout(timeoutId); + try { + await fs.promises.rm(tmpDir, { recursive: true, force: true }); + } catch (e) { + // Ignore removal errors + } + } +} + +const BINARY_NAMES = ['ctrace', 'coretrace', 'ctrace.exe', 'coretrace.exe']; +const PREVIOUS_PREFIX = 'previous-'; + +type RenameFn = (from: string, to: string) => Promise; + +/** + * Replaces the installed release in `destDir` with the one extracted in + * `stagedDir`, without ever leaving a broken installation: + * 1. the staged release is checked first: without a CLI, nothing is touched; + * 2. the installed folders are moved aside, then the staged ones moved in; + * 3. on any failure the new folders are removed and the old ones put back, + * so the previous CLI keeps running with its own libraries. + * The moved-aside copy is deleted only once the new layout is complete, and + * recoverInterruptedUpdate() restores it if the process dies in between. + * + * @param rename Replaceable in tests, to fail partway through. + */ +export async function installStagedRelease( + stagedDir: string, + destDir: string, + rename: RenameFn = (from, to) => fs.promises.rename(from, to) +): Promise { + // A release can ship its CLI at the root instead of in bin/. + for (const name of BINARY_NAMES) { + const loose = path.join(stagedDir, name); + if (fs.existsSync(loose)) { + await fs.promises.mkdir(path.join(stagedDir, 'bin'), { recursive: true }); + await fs.promises.rename(loose, path.join(stagedDir, 'bin', name)); + } + } + + const stagedBinary = BINARY_NAMES.map(name => path.join(stagedDir, 'bin', name)).find(isNonEmptyFile); + if (!stagedBinary) { + throw new Error('Could not find the ctrace binary inside the downloaded archive. The installed version was kept.'); + } + if (process.platform !== 'win32') { + await fs.promises.chmod(stagedBinary, 0o755); + } + + const backupDir = path.join(destDir, `${PREVIOUS_PREFIX}${Date.now()}`); + await fs.promises.mkdir(backupDir, { recursive: true }); + const movedAside: string[] = []; + const installed: string[] = []; + try { + for (const folder of INSTALL_FOLDERS) { + if (fs.existsSync(path.join(destDir, folder))) { + await rename(path.join(destDir, folder), path.join(backupDir, folder)); + movedAside.push(folder); + } + } // Move the extracted layout (bin, lib, config, libexec) into destDir so ctrace can resolve its shared // libraries via INSTALL_RPATH "$ORIGIN/../lib" (Linux) or "@loader_path/../lib" (macOS) for (const folder of INSTALL_FOLDERS) { - const src = path.join(tmpDir, folder); - const dst = path.join(destDir, folder); - if (fs.existsSync(src)) { - await fs.promises.rm(dst, { recursive: true, force: true }).catch(() => {}); - await fs.promises.rename(src, dst); + if (fs.existsSync(path.join(stagedDir, folder))) { + await rename(path.join(stagedDir, folder), path.join(destDir, folder)); + installed.push(folder); } } - - // Also check if any standalone binary was extracted at root of tmpDir - for (const name of candidates) { - const srcFile = path.join(tmpDir, name); - if (fs.existsSync(srcFile)) { - const dstBinDir = path.join(destDir, 'bin'); - await fs.promises.mkdir(dstBinDir, { recursive: true }); - const dstFile = path.join(dstBinDir, name); - await fs.promises.unlink(dstFile).catch(() => {}); - await fs.promises.rename(srcFile, dstFile); - } + } catch (error) { + for (const folder of installed) { + await fs.promises.rm(path.join(destDir, folder), { recursive: true, force: true }).catch(() => { /* best effort */ }); } - - const finalBinPath = await getExtractedBinaryPath(destDir); - if (!finalBinPath) { - throw new Error("Could not find ctrace/coretrace binary inside the downloaded archive."); + for (const folder of movedAside) { + await fs.promises.rm(path.join(destDir, folder), { recursive: true, force: true }).catch(() => { /* best effort */ }); + await fs.promises.rename(path.join(backupDir, folder), path.join(destDir, folder)); } + await fs.promises.rm(backupDir, { recursive: true, force: true }).catch(() => { /* best effort */ }); + throw new Error(`Could not install the new CoreTrace release (${(error as Error).message}). The installed version was kept.`); + } - // Make it executable if on linux/mac - if (process.platform !== 'win32') { - await fs.promises.chmod(finalBinPath, 0o755); - } - } finally { - clearTimeout(timeoutId); - try { - await fs.promises.rm(tmpDir, { recursive: true, force: true }); - } catch (e) { - // Ignore removal errors + await fs.promises.rm(backupDir, { recursive: true, force: true }).catch(() => { /* deleted at the next start */ }); + return path.join(destDir, 'bin', path.basename(stagedBinary)); +} + +/** + * Finishes an update interrupted between moving the old release aside and + * deleting it: the old one is restored if the new one is not complete. + */ +export async function recoverInterruptedUpdate(destDir: string): Promise { + let entries: string[]; + try { + entries = (await fs.promises.readdir(destDir)).filter(name => name.startsWith(PREVIOUS_PREFIX)).sort(); + } catch { + return; + } + if (entries.length === 0) { return; } + const current = BINARY_NAMES.some(name => isNonEmptyFile(path.join(destDir, 'bin', name))); + for (const entry of entries) { + const backupDir = path.join(destDir, entry); + const latest = entry === entries[entries.length - 1]; + if (!current && latest) { + for (const folder of INSTALL_FOLDERS) { + if (fs.existsSync(path.join(backupDir, folder))) { + await fs.promises.rm(path.join(destDir, folder), { recursive: true, force: true }); + await fs.promises.rename(path.join(backupDir, folder), path.join(destDir, folder)); + } + } } + await fs.promises.rm(backupDir, { recursive: true, force: true }).catch(() => { /* retried at the next start */ }); + } +} + +function isNonEmptyFile(file: string): boolean { + try { + const stat = fs.statSync(file); + return stat.isFile() && stat.size > 0; + } catch { + return false; } } diff --git a/src/test/binaryUpdater.test.ts b/src/test/binaryUpdater.test.ts index 0b5de4b..6644681 100644 --- a/src/test/binaryUpdater.test.ts +++ b/src/test/binaryUpdater.test.ts @@ -2,7 +2,8 @@ import * as assert from 'assert'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; -import { dmgContentRoot, getAssetForPlatform, INSTALL_FOLDERS } from '../ctrace/BinaryUpdater'; +import * as cp from 'child_process'; +import { dmgContentRoot, getAssetForPlatform, installStagedRelease, INSTALL_FOLDERS, recoverInterruptedUpdate } from '../ctrace/BinaryUpdater'; // File names of the v0.85.0 release. const RELEASE = [ @@ -76,3 +77,98 @@ suite('BinaryUpdater release asset Test Suite', () => { } }); }); + +suite('BinaryUpdater release install Test Suite', () => { + let work = ''; + setup(() => { work = fs.mkdtempSync(path.join(os.tmpdir(), 'ctrace-install-')); }); + teardown(() => fs.rmSync(work, { recursive: true, force: true })); + + /** A release layout whose CLI prints `label` and reads its library. */ + function layout(dir: string, label: string, folders = ['bin', 'lib', 'libexec']): void { + for (const folder of folders) { fs.mkdirSync(path.join(dir, folder), { recursive: true }); } + if (folders.includes('lib')) { fs.writeFileSync(path.join(dir, 'lib', 'libcore.txt'), label); } + if (folders.includes('libexec')) { fs.writeFileSync(path.join(dir, 'libexec', 'tool'), label); } + if (folders.includes('bin')) { + fs.writeFileSync(path.join(dir, 'bin', 'ctrace'), + `#!/bin/sh\nprintf '%s+' '${label}'; cat "$(dirname "$0")/../lib/libcore.txt"\n`, { mode: 0o755 }); + } + } + + const posix = process.platform !== 'win32'; + const run = (dest: string) => cp.execFileSync(path.join(dest, 'bin', 'ctrace'), { encoding: 'utf8' }); + const leftovers = (dest: string) => fs.readdirSync(dest).filter(name => name.startsWith('previous-')); + + test('a release without a CLI leaves the installed one untouched', async () => { + const dest = path.join(work, 'install'); + const staged = path.join(work, 'staged'); + layout(dest, 'old'); + layout(staged, 'new', ['bin', 'lib']); + fs.unlinkSync(path.join(staged, 'bin', 'ctrace')); + + await assert.rejects(installStagedRelease(staged, dest), /installed version was kept/); + assert.strictEqual(fs.readFileSync(path.join(dest, 'lib', 'libcore.txt'), 'utf8'), 'old'); + if (posix) { assert.strictEqual(run(dest), 'old+old'); } + assert.deepStrictEqual(leftovers(dest), []); + }); + + test('a failure partway through puts the previous release back', async () => { + const dest = path.join(work, 'install'); + const staged = path.join(work, 'staged'); + layout(dest, 'old'); + layout(staged, 'new'); + // The new bin/ goes in, then moving the new lib/ fails. + const failingRename = async (from: string, to: string) => { + if (from === path.join(staged, 'lib')) { throw new Error('disk full'); } + await fs.promises.rename(from, to); + }; + + await assert.rejects(installStagedRelease(staged, dest, failingRename), /disk full.*kept/); + assert.strictEqual(fs.readFileSync(path.join(dest, 'lib', 'libcore.txt'), 'utf8'), 'old'); + assert.strictEqual(fs.readFileSync(path.join(dest, 'libexec', 'tool'), 'utf8'), 'old'); + if (posix) { assert.strictEqual(run(dest), 'old+old', 'the old CLI must run with its own libraries'); } + assert.deepStrictEqual(leftovers(dest), []); + }); + + test('a successful install replaces every folder, including ones the new release drops', async () => { + const dest = path.join(work, 'install'); + const staged = path.join(work, 'staged'); + layout(dest, 'old'); + layout(staged, 'new', ['bin', 'lib']); + + const binary = await installStagedRelease(staged, dest); + assert.strictEqual(binary, path.join(dest, 'bin', 'ctrace')); + if (posix) { assert.strictEqual(run(dest), 'new+new'); } + assert.ok(!fs.existsSync(path.join(dest, 'libexec')), 'no folder of the old release may stay behind'); + assert.deepStrictEqual(leftovers(dest), []); + }); + + test('a CLI shipped at the root of the archive is installed in bin/', async () => { + const dest = path.join(work, 'install'); + const staged = path.join(work, 'staged'); + fs.mkdirSync(staged, { recursive: true }); + fs.writeFileSync(path.join(staged, 'ctrace'), '#!/bin/sh\n', { mode: 0o755 }); + assert.strictEqual(await installStagedRelease(staged, dest), path.join(dest, 'bin', 'ctrace')); + }); + + test('an update interrupted after moving the old release aside is rolled back at the next start', async () => { + const dest = path.join(work, 'install'); + layout(path.join(dest, 'previous-1'), 'old'); + // Killed after the new lib/ went in, before the new bin/. + fs.mkdirSync(path.join(dest, 'lib'), { recursive: true }); + fs.writeFileSync(path.join(dest, 'lib', 'libcore.txt'), 'new'); + + await recoverInterruptedUpdate(dest); + assert.strictEqual(fs.readFileSync(path.join(dest, 'lib', 'libcore.txt'), 'utf8'), 'old'); + if (posix) { assert.strictEqual(run(dest), 'old+old'); } + assert.deepStrictEqual(leftovers(dest), []); + }); + + test('a moved-aside release is only deleted when the current one is complete', async () => { + const dest = path.join(work, 'install'); + layout(dest, 'new'); + layout(path.join(dest, 'previous-1'), 'old'); + await recoverInterruptedUpdate(dest); + if (posix) { assert.strictEqual(run(dest), 'new+new'); } + assert.deepStrictEqual(leftovers(dest), []); + }); +});