From acafc2ef52372b531e1ea2bbd396ad1839516d4e Mon Sep 17 00:00:00 2001 From: Arthurvroum Date: Wed, 25 Nov 2026 03:46:21 +0100 Subject: [PATCH] fix: explain why a fresh install has no CLI and let the user retry When the latest-release lookup failed (an intermittent HTTP 403 on Apple Silicon) and no CLI was cached or on PATH, the user only got the generic "binary could not be found" message. - The updater keeps why its last attempt failed: the release lookup, a release without a file for this platform, or the download. - A failed lookup reports GitHub's status and message, and when its rate limit resets; GITHUB_TOKEN is now also sent to the API to raise it. - The error offers Retry, which checks GitHub again right away instead of waiting for the failure backoff, and Show Output. - Cached and PATH binaries are still used as before. - The HTTP client can be replaced in tests: a simulated 403 followed by a successful release and download is covered without the live API. Fixes #37 --- src/ctrace/BinaryUpdater.ts | 101 +++++++++++++++-- src/extension.ts | 25 ++++- src/test/binaryUpdater.freshInstall.test.ts | 117 ++++++++++++++++++++ 3 files changed, 229 insertions(+), 14 deletions(-) create mode 100644 src/test/binaryUpdater.freshInstall.test.ts diff --git a/src/ctrace/BinaryUpdater.ts b/src/ctrace/BinaryUpdater.ts index 6b3b60c..80d8b81 100755 --- a/src/ctrace/BinaryUpdater.ts +++ b/src/ctrace/BinaryUpdater.ts @@ -14,6 +14,27 @@ const REPO_LATEST_RELEASE_URL = 'https://api.github.com/repos/CoreTrace/coretrac let updatePromise: Promise | null = null; +/** Why the last attempt to get a CLI failed, for a fresh install that has none. */ +export interface BinaryProblem { + kind: 'release-lookup' | 'no-asset' | 'download'; + message: string; +} + +let lastProblem: BinaryProblem | undefined; + +export function getLastBinaryProblem(): BinaryProblem | undefined { + return lastProblem; +} + +let fetchImpl: typeof fetch = (input, init) => fetch(input, init); + +/** Replaces the HTTP client, so tests can answer like GitHub without the network. */ +export function setFetchForTesting(fake: typeof fetch | undefined): void { + fetchImpl = fake ?? ((input, init) => fetch(input, init)); +} + +class ReleaseLookupError extends Error {} + export function isUpdatingBinary(): boolean { return updatePromise !== null; } @@ -24,11 +45,19 @@ export function setBinaryUpdateListener(listener: (msg: string) => void) { progressListener = listener; } -export async function ensureBinary(context: vscode.ExtensionContext, output: vscode.OutputChannel): Promise { +/** + * @param options.force Check GitHub now, even within the backoff after a failed + * check (the user asked to retry). + */ +export async function ensureBinary( + context: vscode.ExtensionContext, + output: vscode.OutputChannel, + options: { force?: boolean } = {} +): Promise { if (updatePromise) { return updatePromise; } - updatePromise = doEnsureBinary(context, output).finally(() => { + updatePromise = doEnsureBinary(context, output, options.force === true).finally(() => { updatePromise = null; if (progressListener) { progressListener('__done__'); @@ -37,7 +66,7 @@ export async function ensureBinary(context: vscode.ExtensionContext, output: vsc return updatePromise; } -async function doEnsureBinary(context: vscode.ExtensionContext, output: vscode.OutputChannel): Promise { +async function doEnsureBinary(context: vscode.ExtensionContext, output: vscode.OutputChannel, force: boolean): Promise { // 1. If binary is bundled with the extension (e.g. Target-Platform Marketplace package) const bundledBinary = await locateBinary(context.extensionUri.fsPath); if (bundledBinary) { @@ -65,18 +94,26 @@ async function doEnsureBinary(context: vscode.ExtensionContext, output: vscode.O // When there is no cached binary, keep retrying with a short backoff. // This avoids a 12-hour lockout if the very first download fails. - if (!downloadedBinaryPath && now - lastFailedCheck < FAILURE_BACKOFF) { + // The reason of that failure, in lastProblem, stays valid meanwhile. + if (!force && !downloadedBinaryPath && now - lastFailedCheck < FAILURE_BACKOFF) { output.appendLine('Skipping update check due to recent failure backoff.'); return await locateBinaryOnPath(); } + lastProblem = undefined; + let stage: BinaryProblem['kind'] = 'release-lookup'; try { - const response = await fetch(REPO_LATEST_RELEASE_URL, { - headers: { 'User-Agent': 'vscode-coretrace' }, - signal: AbortSignal.timeout(5000) - }); + let response: Response; + try { + response = await fetchImpl(REPO_LATEST_RELEASE_URL, { + headers: githubHeaders(), + signal: AbortSignal.timeout(5000) + }); + } catch (error) { + throw new ReleaseLookupError(`GitHub could not be reached (${(error as Error).message}).`); + } if (!response.ok) { - throw new Error(`Failed to check releases: HTTP ${response.status}`); + throw new ReleaseLookupError(await describeGitHubFailure(response)); } const release = await response.json() as { tag_name: string; assets: any[] }; const latestVersion = release.tag_name; @@ -87,6 +124,7 @@ async function doEnsureBinary(context: vscode.ExtensionContext, output: vscode.O if (latestVersion !== currentVersion || !cachedBinaryPath) { const assetInfo = getAssetForPlatform(release.assets); if (assetInfo) { + stage = 'download'; output.appendLine(`Selected release asset: ${assetInfo.name}`); if (progressListener) { progressListener("0%"); } await vscode.window.withProgress({ @@ -104,6 +142,10 @@ async function doEnsureBinary(context: vscode.ExtensionContext, output: vscode.O }); } else { output.appendLine(`No GitHub release asset found for platform ${process.platform} arch ${process.arch}`); + lastProblem = { + kind: 'no-asset', + message: `CoreTrace ${latestVersion} has no prebuilt binary for ${process.platform} ${process.arch}.`, + }; } } @@ -115,6 +157,10 @@ async function doEnsureBinary(context: vscode.ExtensionContext, output: vscode.O } catch (err: any) { output.appendLine(`Failed to check for CoreTrace updates: ${err.message}`); + lastProblem = { + kind: err instanceof ReleaseLookupError ? 'release-lookup' : stage, + message: err.message, + }; await context.globalState.update('coretrace-last-failed-update-check', now); // Keep old behaviour only when we already have a working cached binary. @@ -131,6 +177,41 @@ async function doEnsureBinary(context: vscode.ExtensionContext, output: vscode.O return await locateBinaryOnPath(); } +function githubHeaders(): Record { + const headers: Record = { 'User-Agent': 'vscode-coretrace' }; + // An authenticated request gets a much higher rate limit. + if (process.env.GITHUB_TOKEN) { headers.Authorization = `token ${process.env.GITHUB_TOKEN}`; } + return headers; +} + +/** + * Turns a failed GitHub API answer into something a user can act on: the + * status, GitHub's own message, and when the rate limit lets them retry. + */ +export async function describeGitHubFailure(response: Response): Promise { + let detail = ''; + try { + const body = await response.text(); + try { + const message = (JSON.parse(body) as { message?: unknown }).message; + detail = typeof message === 'string' ? message : ''; + } catch { + detail = body.trim().slice(0, 200); + } + } catch { /* no body */ } + + const parts = [`GitHub answered HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ''}${detail ? `: ${detail}` : ''}.`]; + const remaining = response.headers.get('x-ratelimit-remaining'); + const reset = Number(response.headers.get('x-ratelimit-reset')); + const retryAfter = Number(response.headers.get('retry-after')); + if (remaining === '0' && Number.isFinite(reset) && reset > 0) { + parts.push(`The API rate limit of this network is used up until ${new Date(reset * 1000).toLocaleTimeString()}; setting GITHUB_TOKEN raises it.`); + } else if (Number.isFinite(retryAfter) && retryAfter > 0) { + parts.push(`GitHub asks to retry in ${retryAfter} s.`); + } + return parts.join(' '); +} + const ARCHIVE_EXTENSIONS: Record = { // macOS releases ship a disk image; hdiutil is always available there. 'darwin': ['.dmg', '.tar.gz'], @@ -220,7 +301,7 @@ export async function downloadAndExtract(url: string, assetName: string, destDir let response: Response; try { - response = await fetch(url, { headers, signal: controller.signal }); + response = await fetchImpl(url, { headers, signal: controller.signal }); } catch (error) { clearTimeout(timeoutId); throw error; diff --git a/src/extension.ts b/src/extension.ts index a498c0d..b61fe54 100755 --- a/src/extension.ts +++ b/src/extension.ts @@ -11,7 +11,7 @@ import { updateDiagnostics, clearDiagnostics, getFindingForDiagnostic, FindingRe import { buildCtraceArgs, buildStackAnalyzerArgs, createReportPath, createConfigPath, generateConfigFileIfNeeded, prepareScanDirectory, shellQuoteArgs, CtraceUIState, sourceLanguage, analysesLanguage, workspaceSourceExtensions, PYTHON_EXCLUDED_DIRS, SourceLanguage } from './ctraceRunner'; import { getFunctionSymbols, cleanFunctionName } from './utils/symbolExtractor'; import { CtraceCodeLensProvider } from './codelens/CtraceCodeLensProvider'; -import { ensureBinary, isUpdatingBinary, setBinaryUpdateListener } from './ctrace/BinaryUpdater'; +import { ensureBinary, getLastBinaryProblem, isUpdatingBinary, setBinaryUpdateListener } from './ctrace/BinaryUpdater'; import { clearCache, findCompileCommandsPath, @@ -135,9 +135,26 @@ export function activate(context: vscode.ExtensionContext) { const hint = process.platform === 'darwin' && process.arch !== 'arm64' ? '\nCoreTrace publishes no prebuilt binary for Intel Macs: build it from https://github.com/CoreTrace/coretrace and put `ctrace` on your PATH.' : ''; - vscode.window.showErrorMessage( - `Ctrace binary could not be found or downloaded. Checked: \n- ${globalStorage}/bin\n- ${extPath}\n- PATH${hint}\nSee the "Ctrace" Output channel for details.` - ); + const problem = getLastBinaryProblem(); + // A failed lookup or download can succeed on a retry; a missing platform build cannot. + const retryable = problem && problem.kind !== 'no-asset'; + const message = problem?.kind === 'release-lookup' + ? `No ctrace binary is installed yet, and CoreTrace could not look up its latest release. ${problem.message}` + : problem?.kind === 'download' + ? `No ctrace binary is installed yet, and downloading it failed. ${problem.message}` + : `Ctrace binary could not be found or downloaded. Checked: \n- ${globalStorage}/bin\n- ${extPath}\n- PATH${problem ? `\n${problem.message}` : ''}${hint}`; + const actions = retryable ? ['Retry', 'Show Output'] : ['Show Output']; + void vscode.window.showErrorMessage(message, ...actions).then(async action => { + if (action === 'Show Output') { output.show(true); } + if (action === 'Retry') { + const binary = await ensureBinary(context, output, { force: true }).catch(() => null); + if (binary) { + vscode.window.showInformationMessage('ctrace is installed. Run the analysis again.'); + } else { + void locateOrError(); + } + } + }); } return p; } diff --git a/src/test/binaryUpdater.freshInstall.test.ts b/src/test/binaryUpdater.freshInstall.test.ts new file mode 100644 index 0000000..b85f287 --- /dev/null +++ b/src/test/binaryUpdater.freshInstall.test.ts @@ -0,0 +1,117 @@ +import * as assert from 'assert'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import * as tar from 'tar'; +import * as vscode from 'vscode'; +import { ensureBinary, getAssetForPlatform, getLastBinaryProblem, setFetchForTesting } from '../ctrace/BinaryUpdater'; + +suite('BinaryUpdater fresh install Test Suite', function () { + this.timeout(30000); + let work = ''; + let savedPath: string | undefined; + let calls: string[] = []; + + const osToken = process.platform === 'darwin' ? 'macos' : 'linux'; + const archToken = process.arch === 'arm64' ? 'arm64' : 'amd64'; + const assetName = `coretrace-v9.9.9-${osToken}-${archToken}.tar.gz`; + + function fakeContext(): vscode.ExtensionContext { + const values = new Map(); + return { + extensionUri: vscode.Uri.file(path.join(work, 'extension')), + globalStorageUri: vscode.Uri.file(path.join(work, 'storage')), + globalState: { + get: (key: string, fallback?: unknown) => values.has(key) ? values.get(key) : fallback, + update: async (key: string, value: unknown) => { values.set(key, value); }, + keys: () => [...values.keys()], + }, + } as unknown as vscode.ExtensionContext; + } + const output = { appendLine: () => { /* quiet */ } } as unknown as vscode.OutputChannel; + + /** A release archive like the real ones: one top-level folder holding bin/ctrace. */ + function releaseArchive(): Buffer { + const root = path.join(work, 'release-src'); + fs.mkdirSync(path.join(root, 'coretrace-v9.9.9', 'bin'), { recursive: true }); + fs.writeFileSync(path.join(root, 'coretrace-v9.9.9', 'bin', 'ctrace'), '#!/bin/sh\necho 9.9.9\n', { mode: 0o755 }); + const archive = path.join(work, 'release.tar.gz'); + tar.c({ gzip: true, cwd: root, sync: true, file: archive }, ['coretrace-v9.9.9']); + return fs.readFileSync(archive); + } + + function serve(answers: ((url: string) => Response)[]): void { + calls = []; + setFetchForTesting((async (input: string | URL | Request) => { + const url = String(input); + calls.push(url); + const answer = answers.shift(); + if (!answer) { throw new Error(`unexpected request to ${url}`); } + return answer(url); + }) as typeof fetch); + } + + const json = (status: number, body: unknown, headers: Record = {}) => + new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', ...headers } }); + + setup(() => { + work = fs.mkdtempSync(path.join(os.tmpdir(), 'ctrace-fresh-')); + fs.mkdirSync(path.join(work, 'extension')); + // No ctrace on PATH: a fresh install. + savedPath = process.env.PATH; + process.env.PATH = path.join(work, 'empty-path'); + }); + + teardown(() => { + process.env.PATH = savedPath; + setFetchForTesting(undefined); + fs.rmSync(work, { recursive: true, force: true }); + }); + + test('a 403 from GitHub is explained, then a retry installs the CLI', async function () { + if (!getAssetForPlatform([{ name: assetName, browser_download_url: 'u' }])) { this.skip(); } + const context = fakeContext(); + const reset = Math.floor(Date.now() / 1000) + 600; + serve([() => json(403, { message: 'API rate limit exceeded for 203.0.113.7.' }, + { 'x-ratelimit-remaining': '0', 'x-ratelimit-reset': String(reset) })]); + + assert.strictEqual(await ensureBinary(context, output), null); + const problem = getLastBinaryProblem(); + assert.strictEqual(problem?.kind, 'release-lookup'); + assert.match(problem!.message, /HTTP 403/); + assert.match(problem!.message, /API rate limit exceeded/); + assert.match(problem!.message, /used up until/); + + // Within the backoff, a plain call does not hit GitHub again and keeps the reason. + serve([]); + assert.strictEqual(await ensureBinary(context, output), null); + assert.deepStrictEqual(calls, []); + assert.strictEqual(getLastBinaryProblem()?.kind, 'release-lookup'); + + // Retry: forced past the backoff, GitHub now answers. + const archive = releaseArchive(); + serve([ + () => json(200, { tag_name: 'v9.9.9', assets: [{ name: assetName, browser_download_url: 'https://example.test/release.tar.gz' }] }), + () => new Response(new Uint8Array(archive), { status: 200, headers: { 'content-length': String(archive.length) } }), + ]); + const binary = await ensureBinary(context, output, { force: true }); + assert.ok(binary && fs.existsSync(binary), `no binary installed: ${binary}`); + assert.strictEqual(getLastBinaryProblem(), undefined); + assert.strictEqual(context.globalState.get('coretrace-version'), 'v9.9.9'); + assert.deepStrictEqual(calls, ['https://api.github.com/repos/CoreTrace/coretrace/releases/latest', 'https://example.test/release.tar.gz']); + }); + + test('a release without a file for this platform is told apart from a failed lookup', async () => { + serve([() => json(200, { tag_name: 'v9.9.9', assets: [{ name: 'coretrace-v9.9.9-plan9-mips.tar.gz', browser_download_url: 'u' }] })]); + assert.strictEqual(await ensureBinary(fakeContext(), output), null); + assert.strictEqual(getLastBinaryProblem()?.kind, 'no-asset'); + assert.match(getLastBinaryProblem()!.message, /no prebuilt binary/); + }); + + test('a network error is a failed lookup too', async () => { + serve([() => { throw new TypeError('fetch failed'); }]); + assert.strictEqual(await ensureBinary(fakeContext(), output), null); + assert.strictEqual(getLastBinaryProblem()?.kind, 'release-lookup'); + assert.match(getLastBinaryProblem()!.message, /could not be reached.*fetch failed/); + }); +});