diff --git a/.github/workflows/__bundle-toolcache.yml b/.github/workflows/__bundle-toolcache.yml index 9cc983a843..0055f94705 100644 --- a/.github/workflows/__bundle-toolcache.yml +++ b/.github/workflows/__bundle-toolcache.yml @@ -80,7 +80,8 @@ jobs: - id: init uses: ./../action/init with: - languages: javascript + # Request multiple languages so this check uses the combined bundle. + languages: javascript,python tools: ${{ steps.prepare-test.outputs.tools-url }} - uses: ./../action/analyze with: diff --git a/.github/workflows/__per-language-bundle-validation.yml b/.github/workflows/__per-language-bundle-validation.yml new file mode 100644 index 0000000000..ea900a9e09 --- /dev/null +++ b/.github/workflows/__per-language-bundle-validation.yml @@ -0,0 +1,164 @@ +# Warning: This file is generated automatically, and should not be modified. +# Instead, please modify the template in the pr-checks directory and run: +# pr-checks/sync.sh +# to regenerate this file. + +name: PR Check - Per-language bundles +env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GO111MODULE: auto +on: + push: + branches: + - main + - releases/v* + pull_request: {} + merge_group: + types: + - checks_requested + schedule: + - cron: '0 5 * * *' + workflow_dispatch: + inputs: {} + workflow_call: + inputs: {} +defaults: + run: + shell: bash +concurrency: + cancel-in-progress: ${{ github.event_name == 'pull_request' || false }} + group: per-language-bundle-validation-${{github.ref}} +jobs: + per-language-bundle-validation: + strategy: + fail-fast: false + matrix: + include: + - language: actions + os: ubuntu-latest + version: nightly-latest + expected-extractors: actions javascript + - language: cpp + os: ubuntu-latest + version: nightly-latest + build-mode: manual + build-command: gcc -o main main.c + - language: csharp + os: ubuntu-latest + version: nightly-latest + build-mode: none + - language: go + os: ubuntu-latest + version: nightly-latest + build-mode: autobuild + - language: java + os: ubuntu-latest + version: nightly-latest + build-mode: none + - language: javascript + os: ubuntu-latest + version: nightly-latest + - language: python + os: ubuntu-latest + version: nightly-latest + - language: ruby + os: ubuntu-latest + version: nightly-latest + - language: rust + os: ubuntu-latest + version: nightly-latest + - language: swift + os: macos-latest-xlarge + version: nightly-latest + build-mode: autobuild + name: Per-language bundles + if: github.triggering_actor != 'dependabot[bot]' + permissions: + contents: read + security-events: read + timeout-minutes: 45 + runs-on: ${{ matrix.os }} + steps: + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Prepare test + id: prepare-test + uses: ./.github/actions/prepare-test + with: + version: ${{ matrix.version }} + use-all-platform-bundle: 'false' + setup-kotlin: 'true' + - uses: ./../action/init + id: init + with: + languages: ${{ matrix.language }} + build-mode: ${{ matrix['build-mode'] }} + tools: ${{ steps.prepare-test.outputs.tools-url }} + - name: Check that the bundle contains only the expected extractors + env: + CODEQL_PATH: ${{ steps.init.outputs.codeql-path }} + LANGUAGE: ${{ matrix.language }} + EXPECTED_EXTRACTORS: ${{ matrix['expected-extractors'] || matrix.language }} + run: | + extractors="$("$CODEQL_PATH" resolve languages --format=json | jq -r 'keys[]')" + echo "Extractors in the bundle:" + echo "$extractors" + echo "Expected: $EXPECTED_EXTRACTORS" + + for expected in $EXPECTED_EXTRACTORS; do + if ! echo "$extractors" | grep -qx "$expected"; then + echo "::error::The ${LANGUAGE} bundle does not contain the ${expected} extractor." + exit 1 + fi + done + + # If the bundle contained extractors beyond those the language needs, then it would not + # have been trimmed, and this job would be silently validating the combined bundle. + for other in actions cpp csharp go java javascript python ruby rust swift; do + if echo "$EXPECTED_EXTRACTORS" | grep -qw "$other"; then + continue + fi + if echo "$extractors" | grep -qx "$other"; then + echo "::error::The ${LANGUAGE} bundle also contains the ${other} extractor, so it is not trimmed." + exit 1 + fi + done + - name: Check that the bundle was not added to the toolcache + env: + CODEQL_PATH: ${{ steps.init.outputs.codeql-path }} + run: | + # A bundle that is missing most of its extractors must never be left in the toolcache, + # where a later job analyzing a different language could pick it up. The runner image + # ships with its own CodeQL in the toolcache, so check where this bundle was extracted to + # rather than whether the toolcache contains CodeQL at all. + echo "CodeQL is at $CODEQL_PATH" + if [[ "$CODEQL_PATH" == "$RUNNER_TOOL_CACHE"/* ]]; then + echo "::error::The per-language bundle was added to the toolcache at $CODEQL_PATH." + exit 1 + fi + if [[ "$CODEQL_PATH" != "$RUNNER_TEMP"/* ]]; then + echo "::error::Expected the per-language bundle to be extracted under $RUNNER_TEMP, but found it at $CODEQL_PATH." + exit 1 + fi + - name: Build code + if: matrix['build-command'] + run: ${{ matrix['build-command'] }} + - uses: ./../action/analyze + id: analysis + with: + upload-database: false + - name: Check that a database was created for the language + env: + DB_LOCATIONS: ${{ steps.analysis.outputs.db-locations }} + LANGUAGE: ${{ matrix.language }} + run: | + database="$(echo "$DB_LOCATIONS" | jq -r --arg lang "$LANGUAGE" '.[$lang] // empty')" + if [ -z "$database" ] || [ ! -d "$database" ]; then + echo "::error::No CodeQL database was created for ${LANGUAGE}." + echo "Databases: $DB_LOCATIONS" + exit 1 + fi + echo "Created a ${LANGUAGE} database at ${database}." + env: + CODEQL_ACTION_PER_LANGUAGE_BUNDLES: true + CODEQL_ACTION_TEST_MODE: true diff --git a/.github/workflows/codescanning-config-cli.yml b/.github/workflows/codescanning-config-cli.yml index 7bc6718e35..54474d58fb 100644 --- a/.github/workflows/codescanning-config-cli.yml +++ b/.github/workflows/codescanning-config-cli.yml @@ -75,7 +75,8 @@ jobs: uses: ./../action/.github/actions/check-codescanning-config with: expected-config-file-contents: "{}" - languages: javascript + # Request multiple languages so later checks can reuse the combined bundle. + languages: javascript,python tools: ${{ steps.prepare-test.outputs.tools-url }} - name: Packs from input diff --git a/lib/entry-points.js b/lib/entry-points.js index 35c18d8af8..f8a7d6e76a 100644 --- a/lib/entry-points.js +++ b/lib/entry-points.js @@ -4305,7 +4305,7 @@ var require_util2 = __commonJS({ var { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = require_constants3(); var { getGlobalOrigin } = require_global(); var { collectASequenceOfCodePoints, collectAnHTTPQuotedString, removeChars, parseMIMEType } = require_data_url(); - var { performance: performance6 } = require("node:perf_hooks"); + var { performance: performance8 } = require("node:perf_hooks"); var { isBlobLike, ReadableStreamFrom, isValidHTTPToken, normalizedMethodRecordsBase } = require_util(); var assert = require("node:assert"); var { isUint8Array } = require("node:util/types"); @@ -4464,7 +4464,7 @@ var require_util2 = __commonJS({ }; } function coarsenedSharedCurrentTime(crossOriginIsolatedCapability) { - return coarsenTime(performance6.now(), crossOriginIsolatedCapability); + return coarsenTime(performance8.now(), crossOriginIsolatedCapability); } function createOpaqueTimingInfo(timingInfo) { return { @@ -27216,8 +27216,8 @@ var require_gte = __commonJS({ "node_modules/semver/functions/gte.js"(exports2, module2) { "use strict"; var compare3 = require_compare(); - var gte7 = (a, b, loose) => compare3(a, b, loose) >= 0; - module2.exports = gte7; + var gte8 = (a, b, loose) => compare3(a, b, loose) >= 0; + module2.exports = gte8; } }); @@ -27238,7 +27238,7 @@ var require_cmp = __commonJS({ var eq = require_eq(); var neq = require_neq(); var gt = require_gt(); - var gte7 = require_gte(); + var gte8 = require_gte(); var lt2 = require_lt(); var lte2 = require_lte(); var cmp = (a, op, b, loose) => { @@ -27268,7 +27268,7 @@ var require_cmp = __commonJS({ case ">": return gt(a, b, loose); case ">=": - return gte7(a, b, loose); + return gte8(a, b, loose); case "<": return lt2(a, b, loose); case "<=": @@ -28076,7 +28076,7 @@ var require_outside = __commonJS({ var gt = require_gt(); var lt2 = require_lt(); var lte2 = require_lte(); - var gte7 = require_gte(); + var gte8 = require_gte(); var outside = (version, range2, hilo, options) => { version = new SemVer(version, options); range2 = new Range2(range2, options); @@ -28091,7 +28091,7 @@ var require_outside = __commonJS({ break; case "<": gtfn = lt2; - ltefn = gte7; + ltefn = gte8; ltfn = gt; comp = "<"; ecomp = "<="; @@ -28406,7 +28406,7 @@ var require_semver2 = __commonJS({ var lt2 = require_lt(); var eq = require_eq(); var neq = require_neq(); - var gte7 = require_gte(); + var gte8 = require_gte(); var lte2 = require_lte(); var cmp = require_cmp(); var coerce3 = require_coerce(); @@ -28445,7 +28445,7 @@ var require_semver2 = __commonJS({ lt: lt2, eq, neq, - gte: gte7, + gte: gte8, lte: lte2, cmp, coerce: coerce3, @@ -31721,7 +31721,7 @@ var require_brace_expansion = __commonJS({ function lte2(i, y) { return i <= y; } - function gte7(i, y) { + function gte8(i, y) { return i >= y; } function combine2(acc, base, pre, values, max, maxLength, dropEmpties, outBase) { @@ -31754,7 +31754,7 @@ var require_brace_expansion = __commonJS({ var reverse = y < x; if (reverse) { incr *= -1; - test = gte7; + test = gte8; } var pad = n.some(isPadded2); var length = 0; @@ -33901,8 +33901,8 @@ var require_semver3 = __commonJS({ function neq(a, b, loose) { return compare3(a, b, loose) !== 0; } - exports2.gte = gte7; - function gte7(a, b, loose) { + exports2.gte = gte8; + function gte8(a, b, loose) { return compare3(a, b, loose) >= 0; } exports2.lte = lte2; @@ -33933,7 +33933,7 @@ var require_semver3 = __commonJS({ case ">": return gt(a, b, loose); case ">=": - return gte7(a, b, loose); + return gte8(a, b, loose); case "<": return lt2(a, b, loose); case "<=": @@ -34478,7 +34478,7 @@ var require_semver3 = __commonJS({ break; case "<": gtfn = lt2; - ltefn = gte7; + ltefn = gte8; ltfn = gt; comp = "<"; ecomp = "<="; @@ -34699,7 +34699,7 @@ var require_cacheUtils = __commonJS({ var crypto3 = __importStar2(require("crypto")); var fs32 = __importStar2(require("fs")); var path30 = __importStar2(require("path")); - var semver11 = __importStar2(require_semver3()); + var semver12 = __importStar2(require_semver3()); var util3 = __importStar2(require("util")); var constants_1 = require_constants7(); var versionSalt = "1.0"; @@ -34792,7 +34792,7 @@ var require_cacheUtils = __commonJS({ function getCompressionMethod() { return __awaiter2(this, void 0, void 0, function* () { const versionOutput = yield getVersion("zstd", ["--quiet"]); - const version = semver11.clean(versionOutput); + const version = semver12.clean(versionOutput); core32.debug(`zstd version: ${version}`); if (versionOutput === "") { return constants_1.CompressionMethod.Gzip; @@ -82401,7 +82401,7 @@ var require_manifest = __commonJS({ exports2._findMatch = _findMatch; exports2._getOsVersion = _getOsVersion; exports2._readLinuxVersionFile = _readLinuxVersionFile; - var semver11 = __importStar2(require_semver2()); + var semver12 = __importStar2(require_semver2()); var core_1 = require_core(); var os7 = require("os"); var cp = require("child_process"); @@ -82415,7 +82415,7 @@ var require_manifest = __commonJS({ for (const candidate of candidates) { const version = candidate.version; (0, core_1.debug)(`check ${version} satisfies ${versionSpec}`); - if (semver11.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) { + if (semver12.satisfies(version, versionSpec) && (!stable || candidate.stable === stable)) { file = candidate.files.find((item) => { (0, core_1.debug)(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`); let chk = item.arch === archFilter && item.platform === platFilter; @@ -82424,7 +82424,7 @@ var require_manifest = __commonJS({ if (osVersion === item.platform_version) { chk = true; } else { - chk = semver11.satisfies(osVersion, item.platform_version); + chk = semver12.satisfies(osVersion, item.platform_version); } } return chk; @@ -82684,7 +82684,7 @@ var require_tool_cache = __commonJS({ var os7 = __importStar2(require("os")); var path30 = __importStar2(require("path")); var httpm = __importStar2(require_lib()); - var semver11 = __importStar2(require_semver2()); + var semver12 = __importStar2(require_semver2()); var stream2 = __importStar2(require("stream")); var util3 = __importStar2(require("util")); var assert_1 = require("assert"); @@ -82957,7 +82957,7 @@ var require_tool_cache = __commonJS({ } function cacheDir2(sourceDir, tool, version, arch2) { return __awaiter2(this, void 0, void 0, function* () { - version = semver11.clean(version) || version; + version = semver12.clean(version) || version; arch2 = arch2 || os7.arch(); core32.debug(`Caching tool ${tool} ${version} ${arch2}`); core32.debug(`source dir: ${sourceDir}`); @@ -82975,7 +82975,7 @@ var require_tool_cache = __commonJS({ } function cacheFile(sourceFile, targetFile, tool, version, arch2) { return __awaiter2(this, void 0, void 0, function* () { - version = semver11.clean(version) || version; + version = semver12.clean(version) || version; arch2 = arch2 || os7.arch(); core32.debug(`Caching tool ${tool} ${version} ${arch2}`); core32.debug(`source file: ${sourceFile}`); @@ -83005,7 +83005,7 @@ var require_tool_cache = __commonJS({ } let toolPath = ""; if (versionSpec) { - versionSpec = semver11.clean(versionSpec) || ""; + versionSpec = semver12.clean(versionSpec) || ""; const cachePath = path30.join(_getCacheDirectory(), toolName, versionSpec, arch2); core32.debug(`checking cache: ${cachePath}`); if (fs32.existsSync(cachePath) && fs32.existsSync(`${cachePath}.complete`)) { @@ -83085,7 +83085,7 @@ var require_tool_cache = __commonJS({ } function _createToolPath(tool, version, arch2) { return __awaiter2(this, void 0, void 0, function* () { - const folderPath = path30.join(_getCacheDirectory(), tool, semver11.clean(version) || version, arch2 || ""); + const folderPath = path30.join(_getCacheDirectory(), tool, semver12.clean(version) || version, arch2 || ""); core32.debug(`destination ${folderPath}`); const markerPath = `${folderPath}.complete`; yield io9.rmRF(folderPath); @@ -83095,15 +83095,15 @@ var require_tool_cache = __commonJS({ }); } function _completeToolPath(tool, version, arch2) { - const folderPath = path30.join(_getCacheDirectory(), tool, semver11.clean(version) || version, arch2 || ""); + const folderPath = path30.join(_getCacheDirectory(), tool, semver12.clean(version) || version, arch2 || ""); const markerPath = `${folderPath}.complete`; fs32.writeFileSync(markerPath, ""); core32.debug("finished caching tool"); } function isExplicitVersion(versionSpec) { - const c = semver11.clean(versionSpec) || ""; + const c = semver12.clean(versionSpec) || ""; core32.debug(`isExplicit: ${c}`); - const valid4 = semver11.valid(c) != null; + const valid4 = semver12.valid(c) != null; core32.debug(`explicit? ${valid4}`); return valid4; } @@ -83111,14 +83111,14 @@ var require_tool_cache = __commonJS({ let version = ""; core32.debug(`evaluating ${versions.length} versions`); versions = versions.sort((a, b) => { - if (semver11.gt(a, b)) { + if (semver12.gt(a, b)) { return 1; } return -1; }); for (let i = versions.length - 1; i >= 0; i--) { const potential = versions[i]; - const satisfied = semver11.satisfies(potential, versionSpec); + const satisfied = semver12.satisfies(potential, versionSpec); if (satisfied) { version = potential; break; @@ -89595,7 +89595,7 @@ var require_brace_expansion2 = __commonJS({ function lte2(i, y) { return i <= y; } - function gte7(i, y) { + function gte8(i, y) { return i >= y; } function combine2(acc, pre, values, max, maxLength, dropEmpties) { @@ -89627,7 +89627,7 @@ var require_brace_expansion2 = __commonJS({ var reverse = y < x; if (reverse) { incr *= -1; - test = gte7; + test = gte8; } var pad = n.some(isPadded2); var length = 0; @@ -142119,7 +142119,7 @@ module.exports = __toCommonJS(entry_points_exports); // src/analyze-action.ts var fs23 = __toESM(require("fs")); var import_path5 = __toESM(require("path")); -var import_perf_hooks4 = require("perf_hooks"); +var import_perf_hooks6 = require("perf_hooks"); var core17 = __toESM(require_core()); // src/action-common.ts @@ -142201,6 +142201,7 @@ var fs = __toESM(require("fs")); var fsPromises = __toESM(require("fs/promises")); var os = __toESM(require("os")); var path = __toESM(require("path")); +var import_perf_hooks = require("perf_hooks"); var core2 = __toESM(require_core()); var io = __toESM(require_io()); @@ -145892,6 +145893,9 @@ async function bundleDb(config, language, codeql, dbName, { includeDiagnostics } ); return databaseBundlePath; } +function durationMsSince(startTime) { + return Math.round(import_perf_hooks.performance.now() - startTime); +} async function delay(milliseconds, opts) { const { allowProcessExit } = opts || {}; return new Promise((resolve14) => { @@ -148091,6 +148095,11 @@ var featureConfig = { envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_SKIP_RESOURCE_CHECKS", minimumVersion: void 0 }, + ["per_language_bundles" /* PerLanguageBundles */]: { + defaultValue: false, + envVar: "CODEQL_ACTION_PER_LANGUAGE_BUNDLES", + minimumVersion: void 0 + }, ["qa_telemetry_enabled" /* QaTelemetryEnabled */]: { defaultValue: false, envVar: "CODEQL_ACTION_QA_TELEMETRY", @@ -148606,7 +148615,7 @@ var SarifScanOrder = [ // src/analyze.ts var fs17 = __toESM(require("fs")); var path16 = __toESM(require("path")); -var import_perf_hooks3 = require("perf_hooks"); +var import_perf_hooks5 = require("perf_hooks"); var io5 = __toESM(require_io()); // src/autobuild.ts @@ -148870,7 +148879,7 @@ function wrapCliConfigurationError(cliError) { // src/config-utils.ts var fs10 = __toESM(require("fs")); var path11 = __toESM(require("path")); -var import_perf_hooks = require("perf_hooks"); +var import_perf_hooks2 = require("perf_hooks"); var core10 = __toESM(require_core()); // src/caching-utils.ts @@ -149890,18 +149899,18 @@ var builtin_default = { }; // src/languages/index.ts -var BuiltInLanguage = /* @__PURE__ */ ((BuiltInLanguage3) => { - BuiltInLanguage3["actions"] = "actions"; - BuiltInLanguage3["cpp"] = "cpp"; - BuiltInLanguage3["csharp"] = "csharp"; - BuiltInLanguage3["go"] = "go"; - BuiltInLanguage3["java"] = "java"; - BuiltInLanguage3["javascript"] = "javascript"; - BuiltInLanguage3["python"] = "python"; - BuiltInLanguage3["ruby"] = "ruby"; - BuiltInLanguage3["rust"] = "rust"; - BuiltInLanguage3["swift"] = "swift"; - return BuiltInLanguage3; +var BuiltInLanguage = /* @__PURE__ */ ((BuiltInLanguage4) => { + BuiltInLanguage4["actions"] = "actions"; + BuiltInLanguage4["cpp"] = "cpp"; + BuiltInLanguage4["csharp"] = "csharp"; + BuiltInLanguage4["go"] = "go"; + BuiltInLanguage4["java"] = "java"; + BuiltInLanguage4["javascript"] = "javascript"; + BuiltInLanguage4["python"] = "python"; + BuiltInLanguage4["ruby"] = "ruby"; + BuiltInLanguage4["rust"] = "rust"; + BuiltInLanguage4["swift"] = "swift"; + return BuiltInLanguage4; })(BuiltInLanguage || {}); var builtInLanguageSet = new Set(builtin_default.languages); function isBuiltInLanguage(language) { @@ -150496,9 +150505,9 @@ async function initActionState({ }; } async function downloadCacheWithTime(codeQL, languages, logger) { - const start = import_perf_hooks.performance.now(); + const start = import_perf_hooks2.performance.now(); const trapCaches = await downloadTrapCaches(codeQL, languages, logger); - const trapCacheDownloadTime = import_perf_hooks.performance.now() - start; + const trapCacheDownloadTime = import_perf_hooks2.performance.now() - start; return { trapCaches, trapCacheDownloadTime }; } async function loadUserConfig(actionState, configFile, workspacePath, apiDetails, tempDir) { @@ -150902,10 +150911,10 @@ async function initConfig(actionState, inputs) { } if (await features.getValue("ignore_generated_files" /* IgnoreGeneratedFiles */) && isDynamicWorkflow()) { try { - const generatedFilesCheckStartedAt = import_perf_hooks.performance.now(); + const generatedFilesCheckStartedAt = import_perf_hooks2.performance.now(); const generatedFiles = await getGeneratedFiles(inputs.sourceRoot); const generatedFilesDuration = Math.round( - import_perf_hooks.performance.now() - generatedFilesCheckStartedAt + import_perf_hooks2.performance.now() - generatedFilesCheckStartedAt ); if (generatedFiles.length > 0) { config.computedConfig["paths-ignore"] ??= []; @@ -151189,10 +151198,26 @@ async function logGeneratedFilesTelemetry(config, duration, generatedFilesCount) // src/setup-codeql.ts var fs14 = __toESM(require("fs")); var path13 = __toESM(require("path")); +var import_perf_hooks4 = require("perf_hooks"); var core12 = __toESM(require_core()); var toolcache3 = __toESM(require_tool_cache()); var import_fast_deep_equal = __toESM(require_fast_deep_equal()); -var semver9 = __toESM(require_semver2()); +var semver10 = __toESM(require_semver2()); + +// src/codeql-bundle.ts +var PER_LANGUAGE_BUNDLE_NAME = /^codeql-bundle-(.+)-(?:linux64|osx64|win64)\.tar\.(?:gz|zst)$/; +function getCodeQLBundleFromUrl(url2) { + let assetName; + try { + const pathname = new URL(url2).pathname; + assetName = decodeURIComponent(pathname.split("/").pop() ?? ""); + } catch { + return { kind: "combined", url: url2 }; + } + const match2 = assetName.match(PER_LANGUAGE_BUNDLE_NAME); + const language = match2 ? parseBuiltInLanguage(match2[1]) : void 0; + return language === void 0 ? { kind: "combined", url: url2 } : { kind: "per-language", url: url2, language }; +} // src/overlay/caching.ts var fs11 = __toESM(require("fs")); @@ -151492,6 +151517,97 @@ async function getCodeQlVersionsForOverlayBaseDatabases(rawLanguages, logger) { return versions; } +// src/per-language-bundles.ts +var semver7 = __toESM(require_semver2()); + +// src/platform.ts +function getBundlePlatform(platform2 = process.platform, arch2 = process.arch) { + switch (platform2) { + case "win32": + return "win64" /* Win64 */; + case "linux": + return arch2 === "arm64" ? "linux-arm64" /* LinuxArm64 */ : "linux64" /* Linux64 */; + case "darwin": + return "osx64" /* Osx64 */; + default: + return void 0; + } +} + +// src/per-language-bundles.ts +var MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION = "2.27.1"; +var PER_LANGUAGE_BUNDLE_LANGUAGES = { + ["linux64" /* Linux64 */]: /* @__PURE__ */ new Set([ + "actions" /* actions */, + "cpp" /* cpp */, + "csharp" /* csharp */, + "go" /* go */, + "java" /* java */, + "javascript" /* javascript */, + "python" /* python */, + "ruby" /* ruby */, + "rust" /* rust */ + ]), + ["linux-arm64" /* LinuxArm64 */]: /* @__PURE__ */ new Set(), + ["osx64" /* Osx64 */]: /* @__PURE__ */ new Set(["swift" /* swift */]), + ["win64" /* Win64 */]: /* @__PURE__ */ new Set() +}; +async function getPerLanguageBundleLanguage({ + env, + features, + logger +}, options) { + const { + rawLanguages, + cliVersion: cliVersion2, + compressionMethod, + platform: platform2, + variant, + isLatestNightly + } = options; + const explain = (reason) => { + logger.debug(`Not using a per-language CodeQL bundle since ${reason}.`); + return void 0; + }; + if (!await features.getValue("per_language_bundles" /* PerLanguageBundles */)) { + return explain(`the ${"per_language_bundles" /* PerLanguageBundles */} feature is disabled`); + } + if (rawLanguages?.length !== 1) { + return explain( + `exactly one language must be requested via the 'languages' input, but ${rawLanguages?.length ?? 0} were` + ); + } + const language = parseBuiltInLanguage(rawLanguages[0]); + if (language === void 0) { + return explain(`'${rawLanguages[0]}' is not a known CodeQL language`); + } + if (compressionMethod !== "zstd") { + return explain(`the bundle would be downloaded as '${compressionMethod}'`); + } + if (variant !== "GitHub.com" /* DOTCOM */) { + return explain(`we are running against ${variant}`); + } + if (!isGitHubHostedRunner(env)) { + return explain("the job is not running on a GitHub-hosted runner"); + } + if (!isLatestNightly) { + if (cliVersion2 === void 0) { + return explain("the requested CLI version is unknown"); + } + if (!semver7.gte(cliVersion2, MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION)) { + return explain( + `the requested CodeQL version ${cliVersion2} is older than ${MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION}, which is the first version for which per-language bundles are published` + ); + } + } + if (platform2 === void 0 || !PER_LANGUAGE_BUNDLE_LANGUAGES[platform2].has(language)) { + return explain( + `no per-language bundle is published for ${language} on ${platform2 ?? "an unknown platform"}` + ); + } + return language; +} + // src/tar.ts var import_child_process = require("child_process"); var fs12 = __toESM(require("fs")); @@ -151499,7 +151615,7 @@ var stream = __toESM(require("stream")); var import_toolrunner = __toESM(require_toolrunner()); var io4 = __toESM(require_io()); var toolcache = __toESM(require_tool_cache()); -var semver7 = __toESM(require_semver2()); +var semver8 = __toESM(require_semver2()); var MIN_REQUIRED_BSD_TAR_VERSION = "3.4.3"; var MIN_REQUIRED_GNU_TAR_VERSION = "1.31"; async function getTarVersion() { @@ -151541,9 +151657,9 @@ async function isZstdAvailable(logger) { case "gnu": return { available: foundZstdBinary && // GNU tar only uses major and minor version numbers - semver7.gte( - semver7.coerce(version), - semver7.coerce(MIN_REQUIRED_GNU_TAR_VERSION) + semver8.gte( + semver8.coerce(version), + semver8.coerce(MIN_REQUIRED_GNU_TAR_VERSION) ), foundZstdBinary, version: tarVersion @@ -151552,7 +151668,7 @@ async function isZstdAvailable(logger) { return { available: foundZstdBinary && // Do a loose comparison since these version numbers don't contain // a patch version number. - semver7.gte(version, MIN_REQUIRED_BSD_TAR_VERSION), + semver8.gte(version, MIN_REQUIRED_BSD_TAR_VERSION), foundZstdBinary, version: tarVersion }; @@ -151656,12 +151772,12 @@ function inferCompressionMethod(tarPath) { var fs13 = __toESM(require("fs")); var os4 = __toESM(require("os")); var path12 = __toESM(require("path")); -var import_perf_hooks2 = require("perf_hooks"); +var import_perf_hooks3 = require("perf_hooks"); var core11 = __toESM(require_core()); var import_http_client = __toESM(require_lib()); var toolcache2 = __toESM(require_tool_cache()); var import_follow_redirects = __toESM(require_follow_redirects()); -var semver8 = __toESM(require_semver2()); +var semver9 = __toESM(require_semver2()); var STREAMING_HIGH_WATERMARK_BYTES = 4 * 1024 * 1024; var STREAMING_STALL_TIMEOUT_MS = 5 * 60 * 1e3; var TOOLCACHE_TOOL_NAME = "CodeQL"; @@ -151669,7 +151785,7 @@ async function downloadAndExtract(codeqlURL, compressionMethod, dest, authorizat logger.info( `Downloading CodeQL tools from ${codeqlURL} . This may take a while.` ); - const startTime = import_perf_hooks2.performance.now(); + const startTime = import_perf_hooks3.performance.now(); try { if (compressionMethod === "zstd" && process.platform === "linux") { logger.info(`Streaming the extraction of the CodeQL bundle.`); @@ -151681,7 +151797,7 @@ async function downloadAndExtract(codeqlURL, compressionMethod, dest, authorizat tarVersion, logger ); - const totalDurationMs = Math.round(import_perf_hooks2.performance.now() - startTime); + const totalDurationMs = durationMsSince(startTime); logger.info( `Finished downloading and extracting CodeQL bundle to ${dest} (${formatDuration( totalDurationMs @@ -151699,14 +151815,14 @@ async function downloadAndExtract(codeqlURL, compressionMethod, dest, authorizat ); core11.warning(`Falling back to downloading the bundle before extracting.`); } - const toolsDownloadStart = import_perf_hooks2.performance.now(); + const toolsDownloadStart = import_perf_hooks3.performance.now(); const archivedBundlePath = await toolcache2.downloadTool( codeqlURL, void 0, authorization, headers ); - const downloadDurationMs = Math.round(import_perf_hooks2.performance.now() - toolsDownloadStart); + const downloadDurationMs = durationMsSince(toolsDownloadStart); logger.info( `Finished downloading CodeQL bundle to ${archivedBundlePath} (${formatDuration( downloadDurationMs @@ -151715,7 +151831,7 @@ async function downloadAndExtract(codeqlURL, compressionMethod, dest, authorizat let extractionDurationMs; try { logger.info("Extracting CodeQL bundle."); - const extractionStart = import_perf_hooks2.performance.now(); + const extractionStart = import_perf_hooks3.performance.now(); await extract( archivedBundlePath, dest, @@ -151723,7 +151839,7 @@ async function downloadAndExtract(codeqlURL, compressionMethod, dest, authorizat tarVersion, logger ); - extractionDurationMs = Math.round(import_perf_hooks2.performance.now() - extractionStart); + extractionDurationMs = durationMsSince(extractionStart); logger.info( `Finished extracting CodeQL bundle to ${dest} (${formatDuration( extractionDurationMs @@ -151735,7 +151851,7 @@ async function downloadAndExtract(codeqlURL, compressionMethod, dest, authorizat return { downloadDurationMs, extractionDurationMs, - totalDurationMs: Math.round(import_perf_hooks2.performance.now() - startTime) + totalDurationMs: durationMsSince(startTime) }; } async function downloadAndExtractZstdWithStreaming(codeqlURL, dest, authorization, headers, tarVersion, logger) { @@ -151787,7 +151903,7 @@ function getToolcacheToolDirectory(env) { ); } function getToolcacheVersionDirectoryName(version) { - return semver8.clean(version) || version; + return semver9.clean(version) || version; } function getToolcacheDirectory(version) { return path12.join( @@ -151899,18 +152015,15 @@ function getCodeQLBundleExtension(compressionMethod) { assertNever(compressionMethod); } } -function getCodeQLBundleName(compressionMethod) { +function getCodeQLBundleName(compressionMethod, language) { const extension = getCodeQLBundleExtension(compressionMethod); - let platform2; - if (process.platform === "win32") { - platform2 = "win64"; - } else if (process.platform === "linux") { - platform2 = process.arch === "arm64" ? "linux-arm64" : "linux64"; - } else if (process.platform === "darwin") { - platform2 = "osx64"; - } else { + const platform2 = getBundlePlatform(); + if (platform2 === void 0) { return `codeql-bundle${extension}`; } + if (language !== void 0) { + return `codeql-bundle-${language}-${platform2}${extension}`; + } return `codeql-bundle-${platform2}${extension}`; } function getCodeQLActionRepository(logger) { @@ -151922,7 +152035,7 @@ function getCodeQLActionRepository(logger) { } return getRequiredEnvParam("GITHUB_ACTION_REPOSITORY"); } -async function getCodeQLBundleDownloadURL(tagName, apiDetails, compressionMethod, logger) { +async function getCodeQLBundleDownloadURL(tagName, apiDetails, codeQLBundleName, logger) { const codeQLActionRepository = getCodeQLActionRepository(logger); const potentialDownloadSources = [ // This GitHub instance, and this Action. @@ -151937,7 +152050,6 @@ async function getCodeQLBundleDownloadURL(tagName, apiDetails, compressionMethod return !self2.slice(0, index2).some((other) => (0, import_fast_deep_equal.default)(source, other)); } ); - const codeQLBundleName = getCodeQLBundleName(compressionMethod); for (const downloadSource of uniqueDownloadSources) { const [apiURL, repository] = downloadSource; if (apiURL === GITHUB_DOTCOM_URL && repository === CODEQL_DEFAULT_ACTION_REPOSITORY) { @@ -151992,13 +152104,13 @@ function tryGetTagNameFromUrl(url2, logger) { return match2[1]; } function convertToSemVer(version, logger) { - if (!semver9.valid(version)) { + if (!semver10.valid(version)) { logger.debug( `Bundle version ${version} is not in SemVer format. Will treat it as pre-release 0.0.0-${version}.` ); version = `0.0.0-${version}`; } - const s = semver9.clean(version); + const s = semver10.clean(version); if (!s) { throw new Error(`Bundle version ${version} is not in SemVer format.`); } @@ -152126,6 +152238,7 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO let cliVersion2; let tagName; let url2; + let bundle; const canForceNightlyWithFF = isDynamicWorkflow() || isInTestMode(); const forceNightlyValueFF = await features.getValue("force_nightly" /* ForceNightly */); const forceNightly = forceNightlyValueFF && canForceNightlyWithFF; @@ -152156,7 +152269,12 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO `Using the latest CodeQL CLI nightly, as requested by 'tools: ${toolsInput}'.` ); } - toolsInput = await getNightlyToolsUrl(logger); + bundle = await getLatestNightlyBundle( + { env: getEnv(), features, logger }, + rawLanguages, + variant + ); + toolsInput = bundle.url; } const forceShippedTools = toolsInput && CODEQL_BUNDLE_VERSION_ALIAS.includes(toolsInput); if (forceShippedTools) { @@ -152207,7 +152325,7 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO url2 = toolsInput; if (tagName) { const bundleVersion3 = tryGetBundleVersionFromTagName(tagName, logger); - if (bundleVersion3 !== void 0 && semver9.valid(bundleVersion3)) { + if (bundleVersion3 !== void 0 && semver10.valid(bundleVersion3)) { cliVersion2 = convertToSemVer(bundleVersion3, logger); } } @@ -152309,13 +152427,45 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO } let compressionMethod; if (!url2) { + const bundleTagName = tagName; + if (bundleTagName === void 0) { + throw new Error( + "Could not determine a release tag for the requested CodeQL bundle." + ); + } compressionMethod = cliVersion2 !== void 0 && await useZstdBundle(cliVersion2, tarSupportsZstd) ? "zstd" : "gzip"; - url2 = await getCodeQLBundleDownloadURL( - tagName, + const perLanguageBundleLanguage = await getPerLanguageBundleLanguage( + { env: getEnv(), features, logger }, + { + rawLanguages, + cliVersion: cliVersion2, + compressionMethod, + platform: getBundlePlatform(), + variant + } + ); + const resolveBundleURL = (language) => getCodeQLBundleDownloadURL( + bundleTagName, apiDetails, - compressionMethod, + getCodeQLBundleName(compressionMethod, language), logger ); + const combinedBundleURL = await resolveBundleURL(); + if (perLanguageBundleLanguage !== void 0) { + logger.info( + `Selected the per-language CodeQL bundle for '${perLanguageBundleLanguage}'.` + ); + url2 = await resolveBundleURL(perLanguageBundleLanguage); + bundle = { + kind: "per-language", + url: url2, + language: perLanguageBundleLanguage, + combinedBundleURL + }; + } else { + url2 = combinedBundleURL; + bundle = { kind: "combined", url: url2 }; + } } else { const method = inferCompressionMethod(url2); if (method === void 0) { @@ -152324,6 +152474,12 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO ); } compressionMethod = method; + bundle ??= getCodeQLBundleFromUrl(url2); + if (bundle.kind === "per-language") { + logger.info( + `${url2} appears to be a CodeQL bundle that contains only ${bundle.language}.` + ); + } } if (cliVersion2) { logger.info(`Using CodeQL CLI version ${cliVersion2} sourced from ${url2} .`); @@ -152331,7 +152487,7 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO logger.info(`Using CodeQL CLI sourced from ${url2} .`); } return { - bundle: { kind: "combined", url: url2 }, + bundle, bundleVersion: bundleVersion2, cliVersion: cliVersion2, compressionMethod, @@ -152368,8 +152524,10 @@ var downloadCodeQL = async function(source, apiDetails, tarVersion, tempDir, log codeqlURL ); } - const toolcacheDestination = getToolcacheDestination(source, logger); - const extractedBundlePath = toolcacheDestination ?? getTempExtractionDir(tempDir); + const toolcacheDestination = getToolcacheDestination({ logger }, source); + const extractedBundlePath = toolcacheDestination.orElse( + getTempExtractionDir(tempDir) + ); const statusReport = await downloadAndExtract( codeqlURL, compressionMethod, @@ -152379,27 +152537,37 @@ var downloadCodeQL = async function(source, apiDetails, tarVersion, tempDir, log tarVersion, logger ); - if (toolcacheDestination) { - writeToolcacheMarkerFile(toolcacheDestination, logger); + if (toolcacheDestination.isSuccess()) { + writeToolcacheMarkerFile(toolcacheDestination.value, logger); } else { - logger.debug( - `Could not cache CodeQL tools because we could not determine the bundle version from the URL ${codeqlURL}.` - ); + logger.debug(toolcacheDestination.value); } return { codeqlFolder: extractedBundlePath, - statusReport + statusReport: bundle.kind === "per-language" ? { + ...statusReport, + perLanguage: { tools_bundle_language: bundle.language } + } : statusReport }; }; -function getToolcacheDestination(source, logger) { +function getToolcacheDestination({ logger }, source) { + if (source.bundle.kind !== "combined") { + return new Failure( + "Not caching the CodeQL tools because they came from a bundle that contains only a single language." + ); + } if (!source.bundleVersion) { - return void 0; + return new Failure( + `Could not cache CodeQL tools because we could not determine the bundle version from the URL ${source.bundle.url}.` + ); } - return getToolcacheDirectory( - getCanonicalToolcacheVersion( - source.cliVersion, - source.bundleVersion, - logger + return new Success( + getToolcacheDirectory( + getCanonicalToolcacheVersion( + source.cliVersion, + source.bundleVersion, + logger + ) ) ); } @@ -152496,30 +152664,69 @@ async function setupCodeQLBundle(toolsInput, apiDetails, tempDir, variant, defau }; } async function downloadCodeQLBundle(action, source, apiDetails, tarVersion, tempDir) { + const { bundle } = source; + const { logger } = action; await tryDeleteToolcacheBundles(action); - return await downloadCodeQL( - source, - apiDetails, - tarVersion, - tempDir, - action.logger - ); + const startTime = import_perf_hooks4.performance.now(); + try { + return await downloadCodeQL( + source, + apiDetails, + tarVersion, + tempDir, + logger + ); + } catch (e) { + if (bundle.kind !== "per-language" || bundle.combinedBundleURL === void 0 || asHTTPError(e)?.status !== 404) { + throw e; + } + logger.warning( + `No per-language CodeQL bundle for '${bundle.language}' was found at ${bundle.url}, so falling back to the bundle that contains all languages. This analysis will still produce correct results, but will take longer to set up.` + ); + const result = await downloadCodeQL( + { + ...source, + bundle: { kind: "combined", url: bundle.combinedBundleURL } + }, + apiDetails, + tarVersion, + tempDir, + logger + ); + return { + ...result, + statusReport: { + ...result.statusReport, + totalDurationMs: durationMsSince(startTime), + perLanguage: { tools_per_language_bundle_fallback: true } + } + }; + } } async function useZstdBundle(cliVersion2, tarSupportsZstd) { return ( // In testing, gzip performs better than zstd on Windows. - process.platform !== "win32" && tarSupportsZstd && semver9.gte(cliVersion2, CODEQL_VERSION_ZSTD_BUNDLE) + process.platform !== "win32" && tarSupportsZstd && semver10.gte(cliVersion2, CODEQL_VERSION_ZSTD_BUNDLE) ); } function getTempExtractionDir(tempDir) { return path13.join(tempDir, v4_default()); } -async function getNightlyToolsUrl(logger) { +async function getLatestNightlyBundle(action, rawLanguages, variant) { + const { logger } = action; const zstdAvailability = await isZstdAvailable(logger); const compressionMethod = await useZstdBundle( CODEQL_VERSION_ZSTD_BUNDLE, zstdAvailability.available ) ? "zstd" : "gzip"; + const language = await getPerLanguageBundleLanguage(action, { + rawLanguages, + cliVersion: void 0, + compressionMethod, + platform: getBundlePlatform(), + variant, + isLatestNightly: true + }); try { const release2 = await getApiClient().rest.repos.listReleases({ owner: CODEQL_NIGHTLIES_REPOSITORY_OWNER, @@ -152532,7 +152739,14 @@ async function getNightlyToolsUrl(logger) { if (!latestRelease) { throw new Error("Could not find the latest nightly release."); } - return `https://github.com/${CODEQL_NIGHTLIES_REPOSITORY_OWNER}/${CODEQL_NIGHTLIES_REPOSITORY_NAME}/releases/download/${latestRelease.tag_name}/${getCodeQLBundleName(compressionMethod)}`; + const assetUrl = (name) => `https://github.com/${CODEQL_NIGHTLIES_REPOSITORY_OWNER}/${CODEQL_NIGHTLIES_REPOSITORY_NAME}/releases/download/${latestRelease.tag_name}/${name}`; + const url2 = assetUrl(getCodeQLBundleName(compressionMethod, language)); + return language === void 0 ? { kind: "combined", url: url2 } : { + kind: "per-language", + url: url2, + language, + combinedBundleURL: assetUrl(getCodeQLBundleName(compressionMethod)) + }; } catch (e) { throw new Error( `Failed to retrieve the latest nightly release: ${wrapError(e)}` @@ -152540,7 +152754,7 @@ async function getNightlyToolsUrl(logger) { } } function getLatestToolcacheVersion(logger) { - const allVersions = toolcache3.findAllVersions("CodeQL").sort((a, b) => semver9.compare(b, a)); + const allVersions = toolcache3.findAllVersions("CodeQL").sort((a, b) => semver10.compare(b, a)); logger.debug( `Found the following versions of the CodeQL tools in the toolcache: ${JSON.stringify( allVersions @@ -153647,10 +153861,10 @@ function dbIsFinalized(config, language, logger) { } } async function finalizeDatabaseCreation(codeql, features, config, threadsFlag, memoryFlag, logger) { - const extractionStart = import_perf_hooks3.performance.now(); + const extractionStart = import_perf_hooks5.performance.now(); await runExtraction(codeql, features, config, logger); - const extractionTime = import_perf_hooks3.performance.now() - extractionStart; - const trapImportStart = import_perf_hooks3.performance.now(); + const extractionTime = import_perf_hooks5.performance.now() - extractionStart; + const trapImportStart = import_perf_hooks5.performance.now(); for (const language of config.languages) { if (dbIsFinalized(config, language, logger)) { logger.info( @@ -153667,7 +153881,7 @@ async function finalizeDatabaseCreation(codeql, features, config, threadsFlag, m logger.endGroup(); } } - const trapImportTime = import_perf_hooks3.performance.now() - trapImportStart; + const trapImportTime = import_perf_hooks5.performance.now() - trapImportStart; return { scanned_language_extraction_duration_ms: Math.round(extractionTime), trap_import_duration_ms: Math.round(trapImportTime) @@ -156474,9 +156688,9 @@ async function run({ startedAt, logger }) { features, logger ); - const trapCacheUploadStartTime = import_perf_hooks4.performance.now(); + const trapCacheUploadStartTime = import_perf_hooks6.performance.now(); didUploadTrapCaches = await uploadTrapCaches(codeql, config, logger); - trapCacheUploadTime = import_perf_hooks4.performance.now() - trapCacheUploadStartTime; + trapCacheUploadTime = import_perf_hooks6.performance.now() - trapCacheUploadStartTime; trapCacheCleanupTelemetry = await cleanupTrapCaches( config, features, @@ -156724,7 +156938,7 @@ function isPadded(el) { function lte(i, y) { return i <= y; } -function gte6(i, y) { +function gte7(i, y) { return i >= y; } function combine(acc, pre, values, max, maxLength, dropEmpties) { @@ -156759,7 +156973,7 @@ function expandSequence(body, isAlphaSequence, max, maxLength) { const reverse = y < x; if (reverse) { incr *= -1; - test = gte6; + test = gte7; } const pad = n.some(isPadded); let length = 0; @@ -158656,7 +158870,7 @@ var import_async = __toESM(require_async(), 1); var import_path7 = require("path"); // node_modules/archiver/lib/error.js -var import_util34 = __toESM(require("util"), 1); +var import_util35 = __toESM(require("util"), 1); var ERROR_CODES = { ABORTED: "archive was aborted", DIRECTORYDIRPATHREQUIRED: "diretory dirpath argument must be a non-empty string value", @@ -158681,7 +158895,7 @@ function ArchiverError(code, data) { this.code = code; this.data = data; } -import_util34.default.inherits(ArchiverError, Error); +import_util35.default.inherits(ArchiverError, Error); // node_modules/archiver/lib/core.js var import_readable_stream2 = __toESM(require_ours(), 1); @@ -161613,7 +161827,7 @@ var fs29 = __toESM(require("fs")); var path25 = __toESM(require("path")); var core22 = __toESM(require_core()); var io7 = __toESM(require_io()); -var semver10 = __toESM(require_semver2()); +var semver11 = __toESM(require_semver2()); // src/config/inputs.ts async function getToolsInput(action, repositoryProperties) { @@ -161649,6 +161863,24 @@ async function getToolsInput(action, repositoryProperties) { return void 0; } +// src/status-report/tools-download.ts +function createInitToolsDownloadFields(report, toolsFeatureFlagsValid) { + const fields = { ...report?.perLanguage }; + if (report?.downloadDurationMs !== void 0) { + fields.tools_download_duration_ms = report.downloadDurationMs; + } + if (report?.extractionDurationMs !== void 0) { + fields.tools_extraction_duration_ms = report.extractionDurationMs; + } + if (report?.totalDurationMs !== void 0) { + fields.tools_total_duration_ms = report.totalDurationMs; + } + if (toolsFeatureFlagsValid !== void 0) { + fields.tools_feature_flags_valid = toolsFeatureFlagsValid; + } + return fields; +} + // src/workflow.ts var fs28 = __toESM(require("fs")); var path24 = __toESM(require("path")); @@ -161964,19 +162196,10 @@ async function sendCompletedStatusReport2(startedAt, config, configFile, toolsIn if (toolsInput !== void 0) { initStatusReport.computed_inputs.tools = toolsInput; } - const initToolsDownloadFields = {}; - if (toolsDownloadStatusReport?.downloadDurationMs !== void 0) { - initToolsDownloadFields.tools_download_duration_ms = toolsDownloadStatusReport.downloadDurationMs; - } - if (toolsDownloadStatusReport?.extractionDurationMs !== void 0) { - initToolsDownloadFields.tools_extraction_duration_ms = toolsDownloadStatusReport.extractionDurationMs; - } - if (toolsDownloadStatusReport?.totalDurationMs !== void 0) { - initToolsDownloadFields.tools_total_duration_ms = toolsDownloadStatusReport.totalDurationMs; - } - if (toolsFeatureFlagsValid !== void 0) { - initToolsDownloadFields.tools_feature_flags_valid = toolsFeatureFlagsValid; - } + const initToolsDownloadFields = createInitToolsDownloadFields( + toolsDownloadStatusReport, + toolsFeatureFlagsValid + ); if (config !== void 0) { const initWithConfigStatusReport = await createInitWithConfigStatusReport( config, @@ -162093,12 +162316,12 @@ async function run3(actionState) { const experimental = "2.19.3"; const publicPreview = "2.22.1"; const actualVer = (await codeql.getVersion()).version; - if (semver10.lt(actualVer, experimental)) { + if (semver11.lt(actualVer, experimental)) { throw new ConfigurationError( `Rust analysis is supported by CodeQL CLI version ${experimental} or higher, but found version ${actualVer}` ); } - if (semver10.lt(actualVer, publicPreview)) { + if (semver11.lt(actualVer, publicPreview)) { core22.exportVariable("CODEQL_ENABLE_EXPERIMENTAL_FEATURES" /* EXPERIMENTAL_FEATURES */, "true"); logger.info("Experimental Rust analysis enabled"); } @@ -163012,19 +163235,10 @@ async function sendCompletedStatusReport3(startedAt, toolsInput, toolsDownloadSt if (toolsInput !== void 0) { initStatusReport.computed_inputs.tools = toolsInput; } - const initToolsDownloadFields = {}; - if (toolsDownloadStatusReport?.downloadDurationMs !== void 0) { - initToolsDownloadFields.tools_download_duration_ms = toolsDownloadStatusReport.downloadDurationMs; - } - if (toolsDownloadStatusReport?.extractionDurationMs !== void 0) { - initToolsDownloadFields.tools_extraction_duration_ms = toolsDownloadStatusReport.extractionDurationMs; - } - if (toolsDownloadStatusReport?.totalDurationMs !== void 0) { - initToolsDownloadFields.tools_total_duration_ms = toolsDownloadStatusReport.totalDurationMs; - } - if (toolsFeatureFlagsValid !== void 0) { - initToolsDownloadFields.tools_feature_flags_valid = toolsFeatureFlagsValid; - } + const initToolsDownloadFields = createInitToolsDownloadFields( + toolsDownloadStatusReport, + toolsFeatureFlagsValid + ); await sendStatusReport({ ...initStatusReport, ...initToolsDownloadFields }); } async function run6(actionState) { diff --git a/pr-checks/checks/bundle-toolcache.yml b/pr-checks/checks/bundle-toolcache.yml index 83d1d7d0b5..f74c6af75c 100644 --- a/pr-checks/checks/bundle-toolcache.yml +++ b/pr-checks/checks/bundle-toolcache.yml @@ -30,7 +30,8 @@ steps: - id: init uses: ./../action/init with: - languages: javascript + # Request multiple languages so this check uses the combined bundle. + languages: javascript,python tools: ${{ steps.prepare-test.outputs.tools-url }} - uses: ./../action/analyze with: diff --git a/pr-checks/checks/per-language-bundle-validation.yml b/pr-checks/checks/per-language-bundle-validation.yml new file mode 100644 index 0000000000..21fe33e757 --- /dev/null +++ b/pr-checks/checks/per-language-bundle-validation.yml @@ -0,0 +1,117 @@ +name: Per-language bundles +description: Validates extraction and analysis using each per-language CodeQL bundle. +# TODO: Use a released bundle once releases include per-language bundles. +matrix: + include: + - language: actions + os: ubuntu-latest + version: nightly-latest + # Actions also needs the JavaScript extractor. + expected-extractors: actions javascript + - language: cpp + os: ubuntu-latest + version: nightly-latest + build-mode: manual + build-command: gcc -o main main.c + - language: csharp + os: ubuntu-latest + version: nightly-latest + build-mode: none + - language: go + os: ubuntu-latest + version: nightly-latest + build-mode: autobuild + - language: java + os: ubuntu-latest + version: nightly-latest + build-mode: none + - language: javascript + os: ubuntu-latest + version: nightly-latest + - language: python + os: ubuntu-latest + version: nightly-latest + - language: ruby + os: ubuntu-latest + version: nightly-latest + - language: rust + os: ubuntu-latest + version: nightly-latest + - language: swift + os: macos-latest-xlarge + version: nightly-latest + build-mode: autobuild +env: + CODEQL_ACTION_PER_LANGUAGE_BUNDLES: true +steps: + - uses: ./../action/init + id: init + with: + languages: ${{ matrix.language }} + build-mode: ${{ matrix['build-mode'] }} + tools: ${{ steps.prepare-test.outputs.tools-url }} + - name: Check that the bundle contains only the expected extractors + env: + CODEQL_PATH: ${{ steps.init.outputs.codeql-path }} + LANGUAGE: ${{ matrix.language }} + EXPECTED_EXTRACTORS: ${{ matrix['expected-extractors'] || matrix.language }} + run: | + extractors="$("$CODEQL_PATH" resolve languages --format=json | jq -r 'keys[]')" + echo "Extractors in the bundle:" + echo "$extractors" + echo "Expected: $EXPECTED_EXTRACTORS" + + for expected in $EXPECTED_EXTRACTORS; do + if ! echo "$extractors" | grep -qx "$expected"; then + echo "::error::The ${LANGUAGE} bundle does not contain the ${expected} extractor." + exit 1 + fi + done + + # If the bundle contained extractors beyond those the language needs, then it would not + # have been trimmed, and this job would be silently validating the combined bundle. + for other in actions cpp csharp go java javascript python ruby rust swift; do + if echo "$EXPECTED_EXTRACTORS" | grep -qw "$other"; then + continue + fi + if echo "$extractors" | grep -qx "$other"; then + echo "::error::The ${LANGUAGE} bundle also contains the ${other} extractor, so it is not trimmed." + exit 1 + fi + done + - name: Check that the bundle was not added to the toolcache + env: + CODEQL_PATH: ${{ steps.init.outputs.codeql-path }} + run: | + # A bundle that is missing most of its extractors must never be left in the toolcache, + # where a later job analyzing a different language could pick it up. The runner image + # ships with its own CodeQL in the toolcache, so check where this bundle was extracted to + # rather than whether the toolcache contains CodeQL at all. + echo "CodeQL is at $CODEQL_PATH" + if [[ "$CODEQL_PATH" == "$RUNNER_TOOL_CACHE"/* ]]; then + echo "::error::The per-language bundle was added to the toolcache at $CODEQL_PATH." + exit 1 + fi + if [[ "$CODEQL_PATH" != "$RUNNER_TEMP"/* ]]; then + echo "::error::Expected the per-language bundle to be extracted under $RUNNER_TEMP, but found it at $CODEQL_PATH." + exit 1 + fi + - name: Build code + if: matrix['build-command'] + run: ${{ matrix['build-command'] }} + - uses: ./../action/analyze + id: analysis + with: + upload-database: false + - name: Check that a database was created for the language + env: + DB_LOCATIONS: ${{ steps.analysis.outputs.db-locations }} + LANGUAGE: ${{ matrix.language }} + run: | + database="$(echo "$DB_LOCATIONS" | jq -r --arg lang "$LANGUAGE" '.[$lang] // empty')" + if [ -z "$database" ] || [ ! -d "$database" ]; then + echo "::error::No CodeQL database was created for ${LANGUAGE}." + echo "Databases: $DB_LOCATIONS" + exit 1 + fi + echo "Created a ${LANGUAGE} database at ${database}." diff --git a/pr-checks/sync.ts b/pr-checks/sync.ts index 6dde1ee48e..f0942ad2dd 100755 --- a/pr-checks/sync.ts +++ b/pr-checks/sync.ts @@ -79,6 +79,8 @@ interface Specification extends JobSpecification { useAllPlatformBundle?: string; /** Values for the `analysis-kinds` matrix dimension. */ analysisKinds?: string[]; + /** Overrides the generated job matrix using GitHub Actions matrix syntax. */ + matrix?: Record; /** Container image configuration for the job. */ container?: any; @@ -512,9 +514,6 @@ function generateJob( specDocument: yaml.Document, checkSpecification: Specification, ) { - const matrix: Array> = - generateJobMatrix(checkSpecification); - const useAllPlatformBundle = checkSpecification.useAllPlatformBundle ? checkSpecification.useAllPlatformBundle : "false"; @@ -567,8 +566,8 @@ function generateJob( const checkJob: Record = { strategy: { "fail-fast": false, - matrix: { - include: matrix, + matrix: checkSpecification.matrix ?? { + include: generateJobMatrix(checkSpecification), }, }, name: checkSpecification.name, diff --git a/src/actions-util.ts b/src/actions-util.ts index eb7d92b517..677bb04b1b 100644 --- a/src/actions-util.ts +++ b/src/actions-util.ts @@ -7,7 +7,7 @@ import * as github from "@actions/github"; import * as io from "@actions/io"; import type { Config } from "./config-utils"; -import { Env, EnvVar, ActionsEnvVars } from "./environment"; +import { Env, EnvVar, ActionsEnvVars, ReadOnlyEnv } from "./environment"; import { Logger } from "./logging"; import { doesDirectoryExist, @@ -292,7 +292,7 @@ export function isSelfHostedRunner(env: Env = getEnv()) { * that are configured to resemble hosted ones, such as those that mount a persistent volume at * `/opt/hostedtoolcache`. */ -export function isGitHubHostedRunner(env: Env = getEnv()) { +export function isGitHubHostedRunner(env: ReadOnlyEnv = getEnv()) { return env.getOptional(ActionsEnvVars.RUNNER_ENVIRONMENT) === "github-hosted"; } diff --git a/src/codeql-bundle.test.ts b/src/codeql-bundle.test.ts new file mode 100644 index 0000000000..1014043eab --- /dev/null +++ b/src/codeql-bundle.test.ts @@ -0,0 +1,56 @@ +import test from "ava"; + +import { getCodeQLBundleFromUrl } from "./codeql-bundle"; +import { BuiltInLanguage } from "./languages"; + +for (const [assetName, language] of [ + ["codeql-bundle-java-linux64.tar.zst", BuiltInLanguage.java], + ["codeql-bundle-swift-osx64.tar.zst", BuiltInLanguage.swift], + // Recognize unpublished language/platform combinations to keep them out of the toolcache. + ["codeql-bundle-csharp-win64.tar.gz", BuiltInLanguage.csharp], + ["codeql-bundle-java-kotlin-linux64.tar.zst", BuiltInLanguage.java], + ["codeql-bundle-%70ython-linux64.tar.zst", BuiltInLanguage.python], +] as const) { + test(`getCodeQLBundleFromUrl identifies ${assetName} without adding a fallback`, (t) => { + const url = `https://github.com/github/codeql-action/releases/download/codeql-bundle-v1.2.3/${assetName}`; + t.deepEqual(getCodeQLBundleFromUrl(url), { + kind: "per-language", + url, + language, + }); + }); +} + +test("getCodeQLBundleFromUrl preserves encoding, query parameters and fragments", (t) => { + const url = + "https://github.com/github/codeql-action/releases/download/codeql-bundle-v1.2.3/codeql-bundle-%70ython-linux64.tar.zst?download=1#asset"; + t.deepEqual(getCodeQLBundleFromUrl(url), { + kind: "per-language", + url, + language: BuiltInLanguage.python, + }); +}); + +test("getCodeQLBundleFromUrl treats unrecognized assets as combined bundles", (t) => { + for (const name of [ + "codeql-bundle-linux64.tar.zst", + "codeql-bundle-osx64.tar.gz", + "codeql-bundle-win64.tar.zst", + // The all-platform bundle. + "codeql-bundle.tar.gz", + // A platform we do not publish per-language bundles for, whose name also contains a hyphen. + "codeql-bundle-linux-arm64.tar.zst", + // Not a language we know about. + "codeql-bundle-cobol-linux64.tar.zst", + // A name we cannot decode must not be mistaken for a language either. + "codeql-bundle-%zz-linux64.tar.zst", + ]) { + const url = `https://github.com/github/codeql-action/releases/download/codeql-bundle-v1.2.3/${name}`; + t.deepEqual(getCodeQLBundleFromUrl(url), { kind: "combined", url }); + } +}); + +test("getCodeQLBundleFromUrl preserves URLs it cannot parse", (t) => { + const url = "not a url"; + t.deepEqual(getCodeQLBundleFromUrl(url), { kind: "combined", url }); +}); diff --git a/src/codeql-bundle.ts b/src/codeql-bundle.ts new file mode 100644 index 0000000000..4e9f5d5de1 --- /dev/null +++ b/src/codeql-bundle.ts @@ -0,0 +1,33 @@ +import { BuiltInLanguage, parseBuiltInLanguage } from "./languages"; + +/** Describes the contents and location of a downloadable CodeQL bundle. */ +export type CodeQLBundle = + | { kind: "combined"; url: string } + | { + kind: "per-language"; + url: string; + language: BuiltInLanguage; + /** Only set when the Action selected the bundle, allowing a same-version fallback. */ + combinedBundleURL?: string; + }; + +const PER_LANGUAGE_BUNDLE_NAME = + /^codeql-bundle-(.+)-(?:linux64|osx64|win64)\.tar\.(?:gz|zst)$/; + +/** Classifies an explicit tools URL without changing it or adding a fallback. */ +export function getCodeQLBundleFromUrl(url: string): CodeQLBundle { + let assetName: string; + try { + const pathname = new URL(url).pathname; + // URL-encoded names must not bypass the toolcache safeguard. + assetName = decodeURIComponent(pathname.split("/").pop() ?? ""); + } catch { + return { kind: "combined", url }; + } + + const match = assetName.match(PER_LANGUAGE_BUNDLE_NAME); + const language = match ? parseBuiltInLanguage(match[1]) : undefined; + return language === undefined + ? { kind: "combined", url } + : { kind: "per-language", url, language }; +} diff --git a/src/feature-flags.ts b/src/feature-flags.ts index da7bcceade..afddaea2a4 100644 --- a/src/feature-flags.ts +++ b/src/feature-flags.ts @@ -164,6 +164,11 @@ export enum Feature { OverlayAnalysisStatusCheck = "overlay_analysis_status_check", /** Controls whether overlay build failures on the default branch are stored in the Actions cache. */ OverlayAnalysisStatusSave = "overlay_analysis_status_save", + /** + * Controls whether we may download a bundle containing only the single language being analysed, + * rather than the combined bundle that contains every language. + */ + PerLanguageBundles = "per_language_bundles", QaTelemetryEnabled = "qa_telemetry_enabled", /** Routes (some) API requests through the registry proxy. */ ProxyApiRequests = "proxy_api_requests", @@ -434,6 +439,11 @@ export const featureConfig = { envVar: "CODEQL_ACTION_OVERLAY_ANALYSIS_SKIP_RESOURCE_CHECKS", minimumVersion: undefined, }, + [Feature.PerLanguageBundles]: { + defaultValue: false, + envVar: "CODEQL_ACTION_PER_LANGUAGE_BUNDLES", + minimumVersion: undefined, + }, [Feature.QaTelemetryEnabled]: { defaultValue: false, envVar: "CODEQL_ACTION_QA_TELEMETRY", diff --git a/src/init-action.ts b/src/init-action.ts index 8173d67aaa..79c509a5be 100644 --- a/src/init-action.ts +++ b/src/init-action.ts @@ -63,13 +63,13 @@ import { ToolsSource } from "./setup-codeql"; import { ActionName, InitStatusReport, - InitToolsDownloadFields, InitWithConfigStatusReport, createInitWithConfigStatusReport, createStatusReportBase, getActionsStatus, sendStatusReport, } from "./status-report"; +import { createInitToolsDownloadFields } from "./status-report/tools-download"; import { ToolsDownloadStatusReport } from "./tools-download"; import { ToolsFeature } from "./tools-features"; import { getCombinedTracerConfig } from "./tracer-config"; @@ -168,23 +168,10 @@ async function sendCompletedStatusReport( initStatusReport.computed_inputs.tools = toolsInput; } - const initToolsDownloadFields: InitToolsDownloadFields = {}; - - if (toolsDownloadStatusReport?.downloadDurationMs !== undefined) { - initToolsDownloadFields.tools_download_duration_ms = - toolsDownloadStatusReport.downloadDurationMs; - } - if (toolsDownloadStatusReport?.extractionDurationMs !== undefined) { - initToolsDownloadFields.tools_extraction_duration_ms = - toolsDownloadStatusReport.extractionDurationMs; - } - if (toolsDownloadStatusReport?.totalDurationMs !== undefined) { - initToolsDownloadFields.tools_total_duration_ms = - toolsDownloadStatusReport.totalDurationMs; - } - if (toolsFeatureFlagsValid !== undefined) { - initToolsDownloadFields.tools_feature_flags_valid = toolsFeatureFlagsValid; - } + const initToolsDownloadFields = createInitToolsDownloadFields( + toolsDownloadStatusReport, + toolsFeatureFlagsValid, + ); if (config !== undefined) { // Append fields that are dependent on `config` diff --git a/src/per-language-bundles.test.ts b/src/per-language-bundles.test.ts new file mode 100644 index 0000000000..b8f48512fe --- /dev/null +++ b/src/per-language-bundles.test.ts @@ -0,0 +1,177 @@ +import test from "ava"; + +import { ActionsEnvVars } from "./environment"; +import { Feature } from "./feature-flags"; +import { BuiltInLanguage } from "./languages"; +import { + getPerLanguageBundleLanguage, + MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION, + PerLanguageBundleOptions, +} from "./per-language-bundles"; +import { BundlePlatform } from "./platform"; +import { + createFeatures, + getRecordingLogger, + getTestEnv, + initAllState, + LoggedMessage, +} from "./testing-utils"; +import { GitHubVariant } from "./util"; + +/** Options for which we would use a per-language bundle. */ +const ELIGIBLE_OPTIONS: PerLanguageBundleOptions = { + rawLanguages: ["java"], + // Any version at least as new as the minimum will do. + cliVersion: MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION, + compressionMethod: "zstd", + platform: BundlePlatform.Linux64, + variant: GitHubVariant.DOTCOM, +}; + +async function checkEligibility( + overrides: Partial, + stateOverrides: Partial> = {}, +) { + return getPerLanguageBundleLanguage( + initAllState({ + env: getTestEnv({ + [ActionsEnvVars.RUNNER_ENVIRONMENT]: "github-hosted", + }), + features: createFeatures([Feature.PerLanguageBundles]), + logger: getRecordingLogger([], { logToConsole: false }), + ...stateOverrides, + }), + { ...ELIGIBLE_OPTIONS, ...overrides }, + ); +} + +for (const platform of Object.values(BundlePlatform)) { + test(`getPerLanguageBundleLanguage selects only supported languages on ${platform}`, async (t) => { + for (const language of Object.values(BuiltInLanguage)) { + const supported = + language === BuiltInLanguage.swift + ? platform === BundlePlatform.Osx64 + : platform === BundlePlatform.Linux64; + t.is( + await checkEligibility({ rawLanguages: [language], platform }), + supported ? language : undefined, + language, + ); + } + }); +} + +test("getPerLanguageBundleLanguage normalizes aliases before selecting a bundle", async (t) => { + t.is( + await checkEligibility({ rawLanguages: ["java-kotlin"] }), + BuiltInLanguage.java, + ); +}); + +test("getPerLanguageBundleLanguage rejects unknown platforms", async (t) => { + t.is(await checkEligibility({ platform: undefined }), undefined); +}); + +test("getPerLanguageBundleLanguage requires exactly one language", async (t) => { + t.is(await checkEligibility({ rawLanguages: undefined }), undefined); + t.is(await checkEligibility({ rawLanguages: [] }), undefined); + t.is(await checkEligibility({ rawLanguages: ["java", "python"] }), undefined); +}); + +test("getPerLanguageBundleLanguage requires a known language", async (t) => { + t.is(await checkEligibility({ rawLanguages: ["cobol"] }), undefined); +}); + +test("getPerLanguageBundleLanguage requires a zstd bundle", async (t) => { + t.is(await checkEligibility({ compressionMethod: "gzip" }), undefined); +}); + +test("getPerLanguageBundleLanguage requires GitHub.com", async (t) => { + // Other products resolve the combined bundle against their own instance, so asking for a + // per-language bundle they do not mirror would move the download off that instance. + for (const variant of [GitHubVariant.GHES, GitHubVariant.GHEC_DR]) { + t.is(await checkEligibility({ variant }), undefined); + } +}); + +test("getPerLanguageBundleLanguage requires a GitHub-hosted runner", async (t) => { + // A self-hosted runner may have a toolcache that persists between jobs, which is worth more than + // a smaller download. + t.is( + await checkEligibility( + {}, + { + env: getTestEnv({ [ActionsEnvVars.RUNNER_ENVIRONMENT]: "self-hosted" }), + }, + ), + undefined, + ); + + // Self-hosted runners are routinely configured to look like hosted ones, for example by mounting + // a persistent volume at `/opt/hostedtoolcache`, so we require the service to tell us explicitly. + t.is( + await checkEligibility( + {}, + { + env: getTestEnv({ RUNNER_TOOL_CACHE: "/opt/hostedtoolcache" }), + }, + ), + undefined, + ); +}); + +test("getPerLanguageBundleLanguage requires a supported release version", async (t) => { + t.is(await checkEligibility({ cliVersion: undefined }), undefined); + t.is(await checkEligibility({ cliVersion: "2.27.0" }), undefined); + t.is(await checkEligibility({ cliVersion: "2.27.1" }), BuiltInLanguage.java); +}); + +test("getPerLanguageBundleLanguage requires the feature flag", async (t) => { + t.is(await checkEligibility({}, { features: createFeatures([]) }), undefined); +}); + +test("getPerLanguageBundleLanguage explains a disabled feature before checking eligibility", async (t) => { + const messages: LoggedMessage[] = []; + const language = await getPerLanguageBundleLanguage( + initAllState({ + env: getTestEnv(), + features: createFeatures([]), + logger: getRecordingLogger(messages, { logToConsole: false }), + }), + { ...ELIGIBLE_OPTIONS, rawLanguages: undefined, cliVersion: undefined }, + ); + + t.is(language, undefined); + t.deepEqual( + messages.map((message) => message.message), + [ + "Not using a per-language CodeQL bundle since the per_language_bundles feature is disabled.", + ], + ); +}); + +test("getPerLanguageBundleLanguage skips only the release version check for the latest nightly", async (t) => { + const nightly = { isLatestNightly: true, cliVersion: undefined }; + t.is(await checkEligibility(nightly), BuiltInLanguage.java); + + for (const overrides of [ + { rawLanguages: undefined }, + { rawLanguages: ["java", "python"] }, + { compressionMethod: "gzip" as const }, + { platform: BundlePlatform.Osx64 }, + { variant: GitHubVariant.GHES }, + { variant: GitHubVariant.GHEC_DR }, + ]) { + t.is(await checkEligibility({ ...nightly, ...overrides }), undefined); + } + t.is( + await checkEligibility(nightly, { features: createFeatures([]) }), + undefined, + ); + t.is( + await checkEligibility(nightly, { + env: getTestEnv({ [ActionsEnvVars.RUNNER_ENVIRONMENT]: "self-hosted" }), + }), + undefined, + ); +}); diff --git a/src/per-language-bundles.ts b/src/per-language-bundles.ts new file mode 100644 index 0000000000..f4e46403db --- /dev/null +++ b/src/per-language-bundles.ts @@ -0,0 +1,130 @@ +import * as semver from "semver"; + +import { ActionState } from "./action-common"; +import { isGitHubHostedRunner } from "./actions-util"; +import { Feature } from "./feature-flags"; +import { BuiltInLanguage, parseBuiltInLanguage } from "./languages"; +import { BundlePlatform } from "./platform"; +import * as tar from "./tar"; +import { GitHubVariant } from "./util"; + +/** Minimum CLI version for selecting a per-language release bundle. */ +export const MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION = "2.27.1"; + +/** Languages with per-language bundles published for each platform. */ +const PER_LANGUAGE_BUNDLE_LANGUAGES: Readonly< + Record> +> = { + [BundlePlatform.Linux64]: new Set([ + BuiltInLanguage.actions, + BuiltInLanguage.cpp, + BuiltInLanguage.csharp, + BuiltInLanguage.go, + BuiltInLanguage.java, + BuiltInLanguage.javascript, + BuiltInLanguage.python, + BuiltInLanguage.ruby, + BuiltInLanguage.rust, + ]), + [BundlePlatform.LinuxArm64]: new Set(), + [BundlePlatform.Osx64]: new Set([BuiltInLanguage.swift]), + [BundlePlatform.Win64]: new Set(), +}; + +/** Inputs that determine whether we may download a per-language bundle. */ +export interface PerLanguageBundleOptions { + /** Explicit input only: autodetection needs a CLI instance. */ + rawLanguages: string[] | undefined; + /** Requested CLI version, if known. Ignored when requesting the latest nightly. */ + cliVersion: string | undefined; + compressionMethod: tar.CompressionMethod; + /** Platform for which the bundle is requested. */ + platform: BundlePlatform | undefined; + variant: GitHubVariant; + /** Whether the Action is selecting the latest nightly rather than a release version. */ + isLatestNightly?: boolean; +} + +/** Returns the eligible bundle language, or undefined for the combined bundle. */ +export async function getPerLanguageBundleLanguage( + { + env, + features, + logger, + }: ActionState<["Logger", "ReadOnlyEnv", "FeatureFlags"]>, + options: PerLanguageBundleOptions, +): Promise { + const { + rawLanguages, + cliVersion, + compressionMethod, + platform, + variant, + isLatestNightly, + } = options; + + const explain = (reason: string) => { + logger.debug(`Not using a per-language CodeQL bundle since ${reason}.`); + return undefined; + }; + + if (!(await features.getValue(Feature.PerLanguageBundles))) { + return explain(`the ${Feature.PerLanguageBundles} feature is disabled`); + } + + if (rawLanguages?.length !== 1) { + return explain( + `exactly one language must be requested via the 'languages' input, but ${ + rawLanguages?.length ?? 0 + } were`, + ); + } + + const language = parseBuiltInLanguage(rawLanguages[0]); + if (language === undefined) { + return explain(`'${rawLanguages[0]}' is not a known CodeQL language`); + } + + if (compressionMethod !== "zstd") { + // Per-language bundles are only published as zstd archives. + return explain(`the bundle would be downloaded as '${compressionMethod}'`); + } + + if (variant !== GitHubVariant.DOTCOM) { + // Tenant mirrors may lack these assets, and an unreachable github.com fails with a + // connection error rather than a recoverable 404. + return explain(`we are running against ${variant}`); + } + + if (!isGitHubHostedRunner(env)) { + // Per-language installs stay out of the toolcache; self-hosted runners should retain + // the reusable combined bundle instead. + return explain("the job is not running on a GitHub-hosted runner"); + } + + // Check whether per-language bundles are published for the requested CLI version. + // Latest-nightly selection skips this release-version check, but not the other eligibility checks. + if (!isLatestNightly) { + if (cliVersion === undefined) { + return explain("the requested CLI version is unknown"); + } + + if (!semver.gte(cliVersion, MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION)) { + return explain( + `the requested CodeQL version ${cliVersion} is older than ${MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION}, which is the ` + + "first version for which per-language bundles are published", + ); + } + } + + if ( + platform === undefined || + !PER_LANGUAGE_BUNDLE_LANGUAGES[platform].has(language) + ) { + return explain( + `no per-language bundle is published for ${language} on ${platform ?? "an unknown platform"}`, + ); + } + + return language; +} diff --git a/src/platform.test.ts b/src/platform.test.ts new file mode 100644 index 0000000000..c8a6a7955d --- /dev/null +++ b/src/platform.test.ts @@ -0,0 +1,18 @@ +import test from "ava"; + +import { BundlePlatform, getBundlePlatform } from "./platform"; + +for (const [platform, arch, expected] of [ + ["linux", "x64", BundlePlatform.Linux64], + ["linux", "arm64", BundlePlatform.LinuxArm64], + ["linux", "ia32", BundlePlatform.Linux64], + ["darwin", "x64", BundlePlatform.Osx64], + ["darwin", "arm64", BundlePlatform.Osx64], + ["win32", "x64", BundlePlatform.Win64], + ["win32", "arm64", BundlePlatform.Win64], + ["freebsd", "x64", undefined], +] as const) { + test(`getBundlePlatform maps ${platform}/${arch} to ${expected ?? "an all-platform bundle"}`, (t) => { + t.is(getBundlePlatform(platform, arch), expected); + }); +} diff --git a/src/platform.ts b/src/platform.ts new file mode 100644 index 0000000000..1cc085d6ab --- /dev/null +++ b/src/platform.ts @@ -0,0 +1,26 @@ +/** Platform identifiers used in CodeQL bundle asset names. */ +export enum BundlePlatform { + Linux64 = "linux64", + LinuxArm64 = "linux-arm64", + Osx64 = "osx64", + Win64 = "win64", +} + +/** Returns the bundle platform, or undefined when an all-platform bundle is required. */ +export function getBundlePlatform( + platform: NodeJS.Platform = process.platform, + arch: NodeJS.Architecture = process.arch, +): BundlePlatform | undefined { + switch (platform) { + case "win32": + return BundlePlatform.Win64; + case "linux": + return arch === "arm64" + ? BundlePlatform.LinuxArm64 + : BundlePlatform.Linux64; + case "darwin": + return BundlePlatform.Osx64; + default: + return undefined; + } +} diff --git a/src/setup-codeql-action.ts b/src/setup-codeql-action.ts index bb6b73c9aa..4bd53e517f 100644 --- a/src/setup-codeql-action.ts +++ b/src/setup-codeql-action.ts @@ -22,11 +22,11 @@ import { ToolsSource } from "./setup-codeql"; import { ActionName, InitStatusReport, - InitToolsDownloadFields, createStatusReportBase, getActionsStatus, sendStatusReport, } from "./status-report"; +import { createInitToolsDownloadFields } from "./status-report/tools-download"; import { ToolsDownloadStatusReport } from "./tools-download"; import { checkDiskUsage, @@ -79,23 +79,10 @@ async function sendCompletedStatusReport( initStatusReport.computed_inputs.tools = toolsInput; } - const initToolsDownloadFields: InitToolsDownloadFields = {}; - - if (toolsDownloadStatusReport?.downloadDurationMs !== undefined) { - initToolsDownloadFields.tools_download_duration_ms = - toolsDownloadStatusReport.downloadDurationMs; - } - if (toolsDownloadStatusReport?.extractionDurationMs !== undefined) { - initToolsDownloadFields.tools_extraction_duration_ms = - toolsDownloadStatusReport.extractionDurationMs; - } - if (toolsDownloadStatusReport?.totalDurationMs !== undefined) { - initToolsDownloadFields.tools_total_duration_ms = - toolsDownloadStatusReport.totalDurationMs; - } - if (toolsFeatureFlagsValid !== undefined) { - initToolsDownloadFields.tools_feature_flags_valid = toolsFeatureFlagsValid; - } + const initToolsDownloadFields = createInitToolsDownloadFields( + toolsDownloadStatusReport, + toolsFeatureFlagsValid, + ); await sendStatusReport({ ...initStatusReport, ...initToolsDownloadFields }); } diff --git a/src/setup-codeql.test.ts b/src/setup-codeql.test.ts index 973beef5eb..9346c30e6a 100644 --- a/src/setup-codeql.test.ts +++ b/src/setup-codeql.test.ts @@ -1,6 +1,7 @@ import * as fs from "fs"; import * as os from "os"; import * as path from "path"; +import { performance } from "perf_hooks"; import * as github from "@actions/github"; import * as toolcache from "@actions/tool-cache"; @@ -12,8 +13,10 @@ import * as api from "./api-client"; import * as diagnostics from "./diagnostics"; import { ActionsEnvVars, EnvVar, getEnv, ReadOnlyEnv } from "./environment"; import { Feature } from "./feature-flags"; +import { BuiltInLanguage } from "./languages"; import { getRunnerLogger } from "./logging"; import { getCacheRestoreKeyPrefix } from "./overlay/caching"; +import { MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION } from "./per-language-bundles"; import * as setupCodeql from "./setup-codeql"; import * as tar from "./tar"; import { @@ -22,6 +25,7 @@ import { SAMPLE_DEFAULT_CLI_VERSION, SAMPLE_DOTCOM_API_DETAILS, checkExpectedLogMessages, + checkUnexpectedLogMessages, createFeatures, createTestConfig, getRecordingLogger, @@ -55,6 +59,36 @@ function stubDownloadAndExtract() { }); } +/** Models a hosted Linux runner with zstd and the latest nightly release. */ +function stubHostedNightly(tagName: string) { + sinon.stub(process, "platform").value("linux"); + sinon.stub(process, "arch").value("x64"); + process.env[ActionsEnvVars.RUNNER_ENVIRONMENT] = "github-hosted"; + sinon.stub(tar, "isZstdAvailable").resolves({ + available: true, + foundZstdBinary: true, + }); + const fetchRelease = sinon + .stub, ReturnType>() + .rejects(new Error("Unexpected API request in nightly bundle test")); + fetchRelease + .withArgs( + "https://api.github.com/repos/dsp-testing/codeql-cli-nightlies/releases?per_page=1&page=1&prerelease=true", + sinon.match({ method: "GET" }), + ) + .callsFake( + async () => + new Response(JSON.stringify([{ tag_name: tagName }]), { + headers: { "content-type": "application/json" }, + }), + ); + const client = github.getOctokit("123", { + request: { fetch: fetchRelease }, + }); + sinon.stub(api, "getApiClient").value(() => client); + return fetchRelease; +} + test.serial("parse codeql bundle url version", (t) => { t.deepEqual( setupCodeql.getCodeQLURLVersion( @@ -298,6 +332,10 @@ test.serial( downloadDurationMs: 200, totalDurationMs: 300, }); + checkUnexpectedLogMessages(t, loggedMessages, [ + "Not caching the CodeQL tools", + "Could not cache CodeQL tools", + ]); // Ensure message logging CodeQL CLI version was present in user logs. const expected_message: string = `Using CodeQL CLI version ${LINKED_CLI_VERSION.cliVersion}`; @@ -374,20 +412,7 @@ test.serial( const expectedDate = "30260213"; const expectedTag = `codeql-bundle-${expectedDate}`; - // Ensure that we consistently select "zstd" for the test. - sinon.stub(process, "platform").value("linux"); - sinon.stub(tar, "isZstdAvailable").resolves({ - available: true, - foundZstdBinary: true, - }); - - const client = github.getOctokit("123"); - const listReleases = sinon.stub(client.rest.repos, "listReleases"); - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - listReleases.resolves({ - data: [{ tag_name: expectedTag }], - } as any); - sinon.stub(api, "getApiClient").value(() => client); + stubHostedNightly(expectedTag); await withTmpDir(async (tmpDir) => { setupActionsVars(tmpDir, tmpDir); @@ -456,20 +481,7 @@ test.serial( const expectedDate = "30260213"; const expectedTag = `codeql-bundle-${expectedDate}`; - // Ensure that we consistently select "zstd" for the test. - sinon.stub(process, "platform").value("linux"); - sinon.stub(tar, "isZstdAvailable").resolves({ - available: true, - foundZstdBinary: true, - }); - - const client = github.getOctokit("123"); - const listReleases = sinon.stub(client.rest.repos, "listReleases"); - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - listReleases.resolves({ - data: [{ tag_name: expectedTag }], - } as any); - sinon.stub(api, "getApiClient").value(() => client); + stubHostedNightly(expectedTag); await withTmpDir(async (tmpDir) => { setupActionsVars(tmpDir, tmpDir, { GITHUB_EVENT_NAME: "dynamic" }); @@ -513,6 +525,8 @@ for (const bundlePath of [ "codeql-bundle.tar.gz", "codeql-bundle.tar.zst", "codeql-bundle-/codeql-bundle.tar.gz", + "codeql-bundle-linux64.tar.zst", + "codeql-bundle-ruby-linux64.tar.zst", ]) { test.serial( `setupCodeQLBundle reports an unknown version for ${bundlePath}`, @@ -542,12 +556,21 @@ for (const bundlePath of [ t.is(downloadSpy.firstCall.args[0].toolsVersion, "unknown"); t.is(result.toolsVersion, "unknown"); t.is(result.toolsSource, setupCodeql.ToolsSource.Download); + t.is( + result.toolsDownloadStatusReport?.perLanguage?.tools_bundle_language, + bundlePath === "codeql-bundle-ruby-linux64.tar.zst" + ? BuiltInLanguage.ruby + : undefined, + ); t.is(path.dirname(result.codeqlFolder), tmpDir); t.true(fs.existsSync(result.codeqlFolder)); t.false(fs.existsSync(`${result.codeqlFolder}.complete`)); t.deepEqual(toolcache.findAllVersions("CodeQL"), []); checkExpectedLogMessages(t, messages, [ `Using CodeQL CLI sourced from ${url}`, + bundlePath === "codeql-bundle-ruby-linux64.tar.zst" + ? "Not caching the CodeQL tools because they came from a bundle that contains only a single language." + : `Could not cache CodeQL tools because we could not determine the bundle version from the URL ${url}.`, ]); }); }, @@ -594,6 +617,234 @@ test.serial( }, ); +for (const toolsInput of ["nightly", "nightly-latest"]) { + test.serial( + `getCodeQLSource selects the latest per-language nightly for tools == ${toolsInput}`, + async (t) => { + const expectedTag = "codeql-bundle-30260213"; + const baseURL = `https://github.com/dsp-testing/codeql-cli-nightlies/releases/download/${expectedTag}`; + const latestNightlyRequest = stubHostedNightly(expectedTag); + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + const source = await setupCodeql.getCodeQLSource( + toolsInput, + SAMPLE_DEFAULT_CLI_VERSION, + ["java"], + false, // useOverlayAwareDefaultCliVersion + SAMPLE_DOTCOM_API_DETAILS, + GitHubVariant.DOTCOM, + true, // tarSupportsZstd + createFeatures([Feature.PerLanguageBundles]), + getRunnerLogger(true), + ); + + t.deepEqual(source, { + sourceType: "download", + bundle: { + kind: "per-language", + language: BuiltInLanguage.java, + url: `${baseURL}/codeql-bundle-java-linux64.tar.zst`, + combinedBundleURL: `${baseURL}/codeql-bundle-linux64.tar.zst`, + }, + bundleVersion: "30260213", + cliVersion: undefined, + compressionMethod: "zstd", + toolsVersion: "0.0.0-30260213", + } satisfies setupCodeql.CodeQLDownloadSource); + t.true(latestNightlyRequest.calledOnce); + }); + }, + ); +} + +test.serial( + "getCodeQLSource downloads a combined nightly bundle when per-language selection is ineligible", + async (t) => { + const expectedTag = "codeql-bundle-30260213"; + stubHostedNightly(expectedTag); + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + for (const { languages, features } of [ + // The per-language feature is disabled. + { languages: ["java"], features: createFeatures([]) }, + // More than one language requires a combined bundle. + { + languages: ["java", "python"], + features: createFeatures([Feature.PerLanguageBundles]), + }, + ]) { + const source = await setupCodeql.getCodeQLSource( + "nightly", + SAMPLE_DEFAULT_CLI_VERSION, + languages, + false, // useOverlayAwareDefaultCliVersion + SAMPLE_DOTCOM_API_DETAILS, + GitHubVariant.DOTCOM, + true, // tarSupportsZstd + features, + getRunnerLogger(true), + ); + + t.is(source.sourceType, "download"); + if (source.sourceType === "download") { + t.deepEqual(source.bundle, { + kind: "combined", + url: `https://github.com/dsp-testing/codeql-cli-nightlies/releases/download/${expectedTag}/codeql-bundle-linux64.tar.zst`, + }); + } + } + }); + }, +); + +for (const perLanguageBundles of [false, true]) { + test.serial( + `getCodeQLSource uses the latest ${perLanguageBundles ? "per-language" : "combined"} bundle for a forced nightly`, + async (t) => { + const expectedTag = "codeql-bundle-30260213"; + const baseURL = `https://github.com/dsp-testing/codeql-cli-nightlies/releases/download/${expectedTag}`; + const latestNightlyRequest = stubHostedNightly(expectedTag); + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir, { GITHUB_EVENT_NAME: "dynamic" }); + const source = await setupCodeql.getCodeQLSource( + undefined, // toolsInput: the nightly is selected by ForceNightly + SAMPLE_DEFAULT_CLI_VERSION, + ["java"], + false, // useOverlayAwareDefaultCliVersion + SAMPLE_DOTCOM_API_DETAILS, + GitHubVariant.DOTCOM, + true, // tarSupportsZstd + createFeatures( + perLanguageBundles + ? [Feature.ForceNightly, Feature.PerLanguageBundles] + : [Feature.ForceNightly], + ), + getRunnerLogger(true), + ); + + t.is(source.sourceType, "download"); + t.true(latestNightlyRequest.calledOnce); + if (source.sourceType === "download") { + const combinedURL = `${baseURL}/codeql-bundle-linux64.tar.zst`; + t.deepEqual( + source.bundle, + perLanguageBundles + ? { + kind: "per-language", + language: BuiltInLanguage.java, + url: `${baseURL}/codeql-bundle-java-linux64.tar.zst`, + combinedBundleURL: combinedURL, + } + : { kind: "combined", url: combinedURL }, + ); + } + }); + }, + ); +} + +for (const date of ["20200101", "30260213"]) { + for (const bundle of ["combined", "per-language"] as const) { + test.serial( + `getCodeQLSource preserves an explicit ${bundle} nightly URL for ${date}`, + async (t) => { + const latestNightlyRequest = stubHostedNightly( + "codeql-bundle-30260213", + ); + const asset = + bundle === "combined" + ? "codeql-bundle-linux64.tar.zst" + : "codeql-bundle-java-linux64.tar.zst"; + const url = `https://github.com/dsp-testing/codeql-cli-nightlies/releases/download/codeql-bundle-${date}/${asset}`; + const features = createFeatures([Feature.PerLanguageBundles]); + const logger = getRecordingLogger([], { logToConsole: false }); + const error = new HTTPError("Not Found", 404); + const extractStub = sinon + .stub(toolsDownload, "downloadAndExtract") + .rejects(error); + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + const source = await setupCodeql.getCodeQLSource( + url, + SAMPLE_DEFAULT_CLI_VERSION, + ["java"], + false, + SAMPLE_DOTCOM_API_DETAILS, + GitHubVariant.DOTCOM, + true, + features, + logger, + ); + t.deepEqual(source, { + sourceType: "download", + bundle: + bundle === "combined" + ? { kind: "combined", url } + : { kind: "per-language", url, language: BuiltInLanguage.java }, + bundleVersion: date, + cliVersion: undefined, + compressionMethod: "zstd", + toolsVersion: `0.0.0-${date}`, + } satisfies setupCodeql.CodeQLDownloadSource); + + await t.throwsAsync( + setupCodeql.setupCodeQLBundle( + url, + SAMPLE_DOTCOM_API_DETAILS, + tmpDir, + GitHubVariant.DOTCOM, + SAMPLE_DEFAULT_CLI_VERSION, + ["java"], + false, + features, + logger, + ), + { is: error }, + ); + t.true(extractStub.calledOnce); + t.is(extractStub.firstCall.args[0], url); + t.true(latestNightlyRequest.notCalled); + }); + }, + ); + } +} + +test.serial( + "getCodeQLSource reports a missing release tag when a toolcache entry disappears", + async (t) => { + sinon + .stub(toolcache, "findAllVersions") + .returns([MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION]); + sinon.stub(toolcache, "find").returns(""); + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir, { GITHUB_EVENT_NAME: "dynamic" }); + await t.throwsAsync( + setupCodeql.getCodeQLSource( + "toolcache", + SAMPLE_DEFAULT_CLI_VERSION, + ["java"], + false, + SAMPLE_DOTCOM_API_DETAILS, + GitHubVariant.DOTCOM, + true, + createFeatures([]), + getRunnerLogger(true), + ), + { + message: + "Could not determine a release tag for the requested CodeQL bundle.", + }, + ); + }); + }, +); + test.serial( "getCodeQLSource correctly returns latest version from toolcache when tools == toolcache", async (t) => { @@ -878,6 +1129,475 @@ test.serial( }, ); +const PER_LANGUAGE_CLI_VERSION = { + enabledVersions: [ + { + cliVersion: MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION, + tagName: `codeql-bundle-v${MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION}`, + }, + ], +}; + +test.serial( + "getCodeQLBundleName returns a per-language bundle name only when a language is specified", + (t) => { + sinon.stub(process, "platform").value("linux"); + sinon.stub(process, "arch").value("x64"); + t.is( + setupCodeql.getCodeQLBundleName("zstd", BuiltInLanguage.java), + "codeql-bundle-java-linux64.tar.zst", + ); + t.is( + setupCodeql.getCodeQLBundleName("zstd"), + "codeql-bundle-linux64.tar.zst", + ); + }, +); + +test.serial("getCodeQLBundleName names the Swift bundle for macOS", (t) => { + sinon.stub(process, "platform").value("darwin"); + t.is( + setupCodeql.getCodeQLBundleName("zstd", BuiltInLanguage.swift), + "codeql-bundle-swift-osx64.tar.zst", + ); +}); + +test.serial( + "getCodeQLSource downloads the per-language bundle for a single explicit language", + async (t) => { + sinon.stub(process, "platform").value("linux"); + sinon.stub(process, "arch").value("x64"); + process.env[ActionsEnvVars.RUNNER_ENVIRONMENT] = "github-hosted"; + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + const source = await setupCodeql.getCodeQLSource( + undefined, + PER_LANGUAGE_CLI_VERSION, + ["java-kotlin"], + false, // useOverlayAwareDefaultCliVersion + SAMPLE_DOTCOM_API_DETAILS, + GitHubVariant.DOTCOM, + true, // tarSupportsZstd + createFeatures([Feature.PerLanguageBundles]), + getRunnerLogger(true), + ); + + t.is(source.sourceType, "download"); + if (source.sourceType === "download") { + t.true( + source.bundle.url.endsWith("/codeql-bundle-java-linux64.tar.zst"), + `Unexpected URL ${source.bundle.url}`, + ); + t.is(source.bundle.kind, "per-language"); + if (source.bundle.kind === "per-language") { + t.is(source.bundle.language, BuiltInLanguage.java); + t.true( + source.bundle.combinedBundleURL?.endsWith( + "/codeql-bundle-linux64.tar.zst", + ), + ); + } + } + }); + }, +); + +test.serial( + "getCodeQLSource downloads the combined bundle when the feature is disabled", + async (t) => { + sinon.stub(process, "platform").value("linux"); + sinon.stub(process, "arch").value("x64"); + process.env[ActionsEnvVars.RUNNER_ENVIRONMENT] = "github-hosted"; + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + const source = await setupCodeql.getCodeQLSource( + undefined, + PER_LANGUAGE_CLI_VERSION, + ["java"], + false, // useOverlayAwareDefaultCliVersion + SAMPLE_DOTCOM_API_DETAILS, + GitHubVariant.DOTCOM, + true, // tarSupportsZstd + createFeatures([]), + getRunnerLogger(true), + ); + + t.is(source.sourceType, "download"); + if (source.sourceType === "download") { + t.true(source.bundle.url.endsWith("/codeql-bundle-linux64.tar.zst")); + t.is(source.bundle.kind, "combined"); + } + }); + }, +); + +for (const fallback of [false, true]) { + test.serial( + `setupCodeQLBundle retains the selected release identity for an opaque asset URL${fallback ? " with fallback" : ""}`, + async (t) => { + sinon.stub(process, "platform").value("linux"); + sinon.stub(process, "arch").value("x64"); + sinon.stub(actionsUtil, "isRunningLocalAction").returns(false); + process.env[ActionsEnvVars.RUNNER_ENVIRONMENT] = "github-hosted"; + sinon.stub(tar, "isZstdAvailable").resolves({ + available: true, + foundZstdBinary: true, + }); + const tag = PER_LANGUAGE_CLI_VERSION.enabledVersions[0].tagName; + const assetURL = + "https://api.github.com/repos/codeql-testing/action-fork/releases/assets/123"; + const combinedURL = `${assetURL}4`; + const fetchRelease = sinon + .stub, ReturnType>() + .callsFake( + async () => + new Response( + JSON.stringify({ + assets: [ + { name: "codeql-bundle-java-linux64.tar.zst", url: assetURL }, + { + name: "codeql-bundle-linux64.tar.zst", + url: combinedURL, + }, + ], + }), + { headers: { "content-type": "application/json" } }, + ), + ); + const client = github.getOctokit("123", { + request: { fetch: fetchRelease }, + }); + sinon.stub(api, "getApiClient").value(() => client); + const authorizationSpy = sinon.spy(api, "getAuthorizationHeaderFor"); + const extractStub = stubDownloadAndExtract(); + if (fallback) { + extractStub.onFirstCall().rejects(new HTTPError("Not Found", 404)); + } + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir, { + GITHUB_ACTION_REPOSITORY: "codeql-testing/action-fork", + }); + const result = await setupCodeql.setupCodeQLBundle( + undefined, + SAMPLE_DOTCOM_API_DETAILS, + tmpDir, + GitHubVariant.DOTCOM, + PER_LANGUAGE_CLI_VERSION, + ["java"], + false, // useOverlayAwareDefaultCliVersion + createFeatures([Feature.PerLanguageBundles]), + getRunnerLogger(true), + ); + + t.true(fetchRelease.calledTwice); + t.is( + fetchRelease.firstCall.args[0], + `https://api.github.com/repos/codeql-testing/action-fork/releases/tags/${tag}`, + ); + t.is(extractStub.callCount, fallback ? 2 : 1); + t.is(extractStub.firstCall.args[0], assetURL); + t.is(extractStub.lastCall.args[0], fallback ? combinedURL : assetURL); + t.is(authorizationSpy.callCount, extractStub.callCount); + t.is(authorizationSpy.firstCall.args[2], assetURL); + t.is( + authorizationSpy.lastCall.args[2], + fallback ? combinedURL : assetURL, + ); + t.is(extractStub.lastCall.args[3], "token token"); + t.is(result.toolsVersion, MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION); + t.is( + result.toolsDownloadStatusReport?.perLanguage?.tools_bundle_language, + fallback ? undefined : BuiltInLanguage.java, + ); + t.is( + result.toolsDownloadStatusReport?.perLanguage + ?.tools_per_language_bundle_fallback, + fallback ? true : undefined, + ); + if (fallback) { + t.is( + result.codeqlFolder, + toolcache.find("CodeQL", MIN_PER_LANGUAGE_BUNDLE_CLI_VERSION), + ); + t.true(fs.existsSync(`${result.codeqlFolder}.complete`)); + } else { + t.is(path.dirname(result.codeqlFolder), tmpDir); + t.deepEqual(toolcache.findAllVersions("CodeQL"), []); + t.false(fs.existsSync(`${result.codeqlFolder}.complete`)); + } + }); + }, + ); +} + +for (const bundle of ["per-language", "combined", "fallback"] as const) { + test.serial( + `setupCodeQLBundle preserves the nightly version for a ${bundle} download`, + async (t) => { + const expectedDate = "30260213"; + const expectedTag = `codeql-bundle-${expectedDate}`; + const expectedVersion = `0.0.0-${expectedDate}`; + const baseURL = `https://github.com/dsp-testing/codeql-cli-nightlies/releases/download/${expectedTag}`; + const combinedURL = `${baseURL}/codeql-bundle-linux64.tar.zst`; + const perLanguageURL = `${baseURL}/codeql-bundle-javascript-linux64.tar.zst`; + const loggedMessages: LoggedMessage[] = []; + const logger = getRecordingLogger(loggedMessages); + + stubHostedNightly(expectedTag); + delete process.env[EnvVar.HAS_SET_UP_CODEQL]; + + const downloadSpy = sinon.spy(setupCodeql, "downloadCodeQL"); + let elapsedMs = 1000; + sinon.stub(performance, "now").callsFake(() => elapsedMs); + const extractStub = sinon + .stub(toolsDownload, "downloadAndExtract") + .callsFake(async (_url, _compressionMethod, dest) => { + if (bundle === "fallback" && extractStub.callCount === 1) { + elapsedMs += 700.2; + throw new HTTPError("Not Found", 404); + } + elapsedMs += 300.2; + fs.mkdirSync(dest, { recursive: true }); + return { + downloadDurationMs: 200, + extractionDurationMs: 100, + totalDurationMs: 300, + }; + }); + const addDiagnostic = sinon.stub(diagnostics, "addNoLanguageDiagnostic"); + const features = createFeatures([ + Feature.PerLanguageBundles, + Feature.CleanupToolcacheBundles, + ]); + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + const result = await setupCodeql.setupCodeQLBundle( + "nightly", + SAMPLE_DOTCOM_API_DETAILS, + tmpDir, + GitHubVariant.DOTCOM, + SAMPLE_DEFAULT_CLI_VERSION, + bundle === "combined" ? ["javascript", "python"] : ["javascript"], + false, // useOverlayAwareDefaultCliVersion + features, + logger, + ); + + const source = downloadSpy.firstCall.args[0]; + t.is(result.toolsVersion, expectedVersion); + t.is(result.toolsVersion, source.toolsVersion); + t.is( + source.bundle.kind, + bundle === "combined" ? "combined" : "per-language", + ); + t.is(result.codeqlFolder, extractStub.lastCall.args[2]); + t.is( + result.toolsDownloadStatusReport?.totalDurationMs, + bundle === "fallback" ? 1000 : 300, + ); + t.is(result.toolsDownloadStatusReport?.downloadDurationMs, 200); + t.is(result.toolsDownloadStatusReport?.extractionDurationMs, 100); + t.is( + (await downloadSpy.lastCall.returnValue).statusReport.perLanguage + ?.tools_bundle_language, + bundle === "per-language" ? BuiltInLanguage.javascript : undefined, + ); + t.is(extractStub.callCount, bundle === "fallback" ? 2 : 1); + t.is(downloadSpy.callCount, extractStub.callCount); + t.is( + extractStub.firstCall.args[0], + bundle === "combined" ? combinedURL : perLanguageURL, + ); + t.is( + extractStub.lastCall.args[0], + bundle === "per-language" ? perLanguageURL : combinedURL, + ); + t.is( + result.toolsDownloadStatusReport?.perLanguage?.tools_bundle_language, + bundle === "per-language" ? BuiltInLanguage.javascript : undefined, + ); + t.is( + result.toolsDownloadStatusReport?.perLanguage + ?.tools_per_language_bundle_fallback, + bundle === "fallback" ? true : undefined, + ); + t.is( + addDiagnostic + .getCalls() + .filter( + (call) => + call.args[1].source?.id === + "codeql-action/toolcache-bundle-cleanup", + ).length, + 1, + ); + if (bundle === "fallback") { + t.deepEqual(downloadSpy.secondCall.args[0], { + ...source, + bundle: { kind: "combined", url: combinedURL }, + }); + checkExpectedLogMessages(t, loggedMessages, [ + `No per-language CodeQL bundle for 'javascript' was found at ${perLanguageURL}`, + ]); + } + if (bundle === "per-language") { + t.is(path.dirname(result.codeqlFolder), tmpDir); + t.deepEqual(toolcache.findAllVersions("CodeQL"), []); + t.false(fs.existsSync(`${result.codeqlFolder}.complete`)); + } else { + t.is( + result.codeqlFolder, + toolsDownload.getToolcacheDirectory(expectedVersion), + ); + t.true(fs.existsSync(`${result.codeqlFolder}.complete`)); + + const cachedResult = await setupCodeql.setupCodeQLBundle( + "nightly", + SAMPLE_DOTCOM_API_DETAILS, + tmpDir, + GitHubVariant.DOTCOM, + SAMPLE_DEFAULT_CLI_VERSION, + ["javascript"], + false, // useOverlayAwareDefaultCliVersion + features, + logger, + ); + t.is(cachedResult.toolsSource, setupCodeql.ToolsSource.Toolcache); + t.is(cachedResult.toolsVersion, expectedVersion); + t.is(cachedResult.codeqlFolder, result.codeqlFolder); + t.is(extractStub.callCount, bundle === "fallback" ? 2 : 1); + } + }); + }, + ); +} + +for (const asset of [ + "codeql-bundle-ruby-linux64.tar.zst", + "codeql-bundle-%72uby-linux64.tar.zst", +]) { + test.serial( + `setupCodeQLBundle keeps explicitly requested ${asset} out of the toolcache`, + async (t) => { + const extractStub = stubDownloadAndExtract(); + const messages: LoggedMessage[] = []; + const url = `https://github.com/github/codeql-action/releases/download/codeql-bundle-v9.9.9/${asset}`; + process.env[ActionsEnvVars.RUNNER_ENVIRONMENT] = "self-hosted"; + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + const result = await setupCodeql.setupCodeQLBundle( + url, + SAMPLE_DOTCOM_API_DETAILS, + tmpDir, + GitHubVariant.DOTCOM, + SAMPLE_DEFAULT_CLI_VERSION, + undefined, // rawLanguages + false, // useOverlayAwareDefaultCliVersion + createFeatures([]), + getRecordingLogger(messages), + ); + + t.true(extractStub.calledOnce); + t.is(extractStub.firstCall.args[0], url); + t.is(result.toolsVersion, "9.9.9"); + t.is( + result.toolsDownloadStatusReport?.perLanguage?.tools_bundle_language, + BuiltInLanguage.ruby, + ); + t.is(path.dirname(result.codeqlFolder), tmpDir); + t.deepEqual(toolcache.findAllVersions("CodeQL"), []); + t.false(fs.existsSync(`${result.codeqlFolder}.complete`)); + checkExpectedLogMessages(t, messages, [ + "Not caching the CodeQL tools because they came from a bundle that contains only a single language.", + ]); + checkUnexpectedLogMessages(t, messages, [ + "Could not cache CodeQL tools because we could not determine the bundle version", + ]); + }); + }, + ); +} + +for (const error of [ + new HTTPError("Internal Server Error", 500), + new Error("Connection reset"), +]) { + test.serial( + `setupCodeQLBundle does not fall back after ${error.message}`, + async (t) => { + sinon.stub(process, "platform").value("linux"); + sinon.stub(process, "arch").value("x64"); + process.env[ActionsEnvVars.RUNNER_ENVIRONMENT] = "github-hosted"; + sinon.stub(tar, "isZstdAvailable").resolves({ + available: true, + foundZstdBinary: true, + }); + const extractStub = sinon + .stub(toolsDownload, "downloadAndExtract") + .rejects(error); + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + await t.throwsAsync( + setupCodeql.setupCodeQLBundle( + undefined, + SAMPLE_DOTCOM_API_DETAILS, + tmpDir, + GitHubVariant.DOTCOM, + PER_LANGUAGE_CLI_VERSION, + ["java"], + false, // useOverlayAwareDefaultCliVersion + createFeatures([Feature.PerLanguageBundles]), + getRunnerLogger(true), + ), + { is: error }, + ); + t.true(extractStub.calledOnce); + t.true( + extractStub.firstCall.args[0].endsWith( + "/codeql-bundle-java-linux64.tar.zst", + ), + ); + }); + }, + ); +} + +test.serial( + "setupCodeQLBundle does not substitute a bundle for an explicitly requested one that is missing", + async (t) => { + const error = new HTTPError("Not Found", 404); + const extractStub = sinon + .stub(toolsDownload, "downloadAndExtract") + .rejects(error); + + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + await t.throwsAsync( + setupCodeql.setupCodeQLBundle( + "https://github.com/github/codeql-action/releases/download/codeql-bundle-v9.9.9/codeql-bundle-ruby-linux64.tar.zst", + SAMPLE_DOTCOM_API_DETAILS, + tmpDir, + GitHubVariant.DOTCOM, + SAMPLE_DEFAULT_CLI_VERSION, + undefined, // rawLanguages + false, // useOverlayAwareDefaultCliVersion + createFeatures([]), + getRunnerLogger(true), + ), + { is: error }, + ); + + t.true(extractStub.calledOnce); + }); + }, +); + test.serial( "getEnabledVersionsWithOverlayBaseDatabases returns flag-enabled versions present in cache, sorted desc", async (t) => { diff --git a/src/setup-codeql.ts b/src/setup-codeql.ts index e5d6a77a94..648435d805 100644 --- a/src/setup-codeql.ts +++ b/src/setup-codeql.ts @@ -1,6 +1,7 @@ import * as fs from "fs"; import { OutgoingHttpHeaders } from "http"; import * as path from "path"; +import { performance } from "perf_hooks"; import * as core from "@actions/core"; import * as toolcache from "@actions/tool-cache"; @@ -16,6 +17,7 @@ import { isRunningLocalAction, } from "./actions-util"; import * as api from "./api-client"; +import { CodeQLBundle, getCodeQLBundleFromUrl } from "./codeql-bundle"; import * as defaults from "./defaults.json"; import { addNoLanguageDiagnostic, @@ -30,8 +32,11 @@ import { Feature, FeatureEnablement, } from "./feature-flags"; +import { BuiltInLanguage } from "./languages"; import { Logger } from "./logging"; import { getCodeQlVersionsForOverlayBaseDatabases } from "./overlay/caching"; +import { getPerLanguageBundleLanguage } from "./per-language-bundles"; +import { getBundlePlatform } from "./platform"; import * as tar from "./tar"; import { deleteToolcacheBundles, @@ -72,21 +77,25 @@ function getCodeQLBundleExtension( } } +/** + * Returns the name of the CodeQL bundle asset to download. + * + * @param compressionMethod The compression method of the bundle. + * @param language Optional language for a per-language bundle. If omitted, returns a combined bundle name. + */ export function getCodeQLBundleName( compressionMethod: tar.CompressionMethod, + language?: BuiltInLanguage, ): string { const extension = getCodeQLBundleExtension(compressionMethod); + const platform = getBundlePlatform(); - let platform: string; - if (process.platform === "win32") { - platform = "win64"; - } else if (process.platform === "linux") { - platform = process.arch === "arm64" ? "linux-arm64" : "linux64"; - } else if (process.platform === "darwin") { - platform = "osx64"; - } else { + if (platform === undefined) { return `codeql-bundle${extension}`; } + if (language !== undefined) { + return `codeql-bundle-${language}-${platform}${extension}`; + } return `codeql-bundle-${platform}${extension}`; } @@ -107,7 +116,7 @@ export function getCodeQLActionRepository(logger: Logger): string { async function getCodeQLBundleDownloadURL( tagName: string, apiDetails: api.GitHubApiDetails, - compressionMethod: tar.CompressionMethod, + codeQLBundleName: string, logger: Logger, ): Promise { const codeQLActionRepository = getCodeQLActionRepository(logger); @@ -126,7 +135,6 @@ async function getCodeQLBundleDownloadURL( return !self.slice(0, index).some((other) => deepEqual(source, other)); }, ); - const codeQLBundleName = getCodeQLBundleName(compressionMethod); for (const downloadSource of uniqueDownloadSources) { const [apiURL, repository] = downloadSource; // If we've reached the final case, short-circuit the API check since we know the bundle exists and is public. @@ -215,9 +223,6 @@ export function convertToSemVer(version: string, logger: Logger): string { return s; } -/** Describes the contents and location of a downloadable CodeQL bundle. */ -type CodeQLBundle = { kind: "combined"; url: string }; - /** A resolved download, including its bundle identity and version. */ export interface CodeQLDownloadSource { /** Distinguishes downloads from local archives and cached installations. */ @@ -228,7 +233,7 @@ export interface CodeQLDownloadSource { compressionMethod: tar.CompressionMethod; /** Bundle version of the tools, if known. */ bundleVersion?: string; - /** CLI version of the tools, if known. */ + /** Requested CLI version, if known. */ cliVersion?: string; /** Resolved version for telemetry, independent of whether the bundle can be cached. */ toolsVersion: string; @@ -457,7 +462,7 @@ export async function getCodeQLSource( }; } - /** CLI version number, for example 2.12.6. */ + /** Requested CLI version number, for example 2.12.6. */ let cliVersion: string | undefined; /** Tag name of the CodeQL bundle, for example `codeql-bundle-20230120`. */ let tagName: string | undefined; @@ -467,6 +472,7 @@ export async function getCodeQLSource( * This does not always include a tag name. */ let url: string | undefined; + let bundle: CodeQLBundle | undefined; // We allow forcing the nightly CLI via the FF for `dynamic` events (or in test mode) where the // `tools` input cannot be adjusted to explicitly request it. @@ -475,7 +481,8 @@ export async function getCodeQLSource( const forceNightly = forceNightlyValueFF && canForceNightlyWithFF; // For advanced workflows, a value from `CODEQL_NIGHTLY_TOOLS_INPUTS` can be specified explicitly - // for the `tools` input in the workflow file. + // for the `tools` input. This is the computed input, so it may come from the repository property + // rather than the workflow file. const nightlyRequestedByToolsInput = toolsInput !== undefined && CODEQL_NIGHTLY_TOOLS_INPUTS.includes(toolsInput); @@ -509,7 +516,12 @@ export async function getCodeQLSource( `Using the latest CodeQL CLI nightly, as requested by 'tools: ${toolsInput}'.`, ); } - toolsInput = await getNightlyToolsUrl(logger); + bundle = await getLatestNightlyBundle( + { env: getEnv(), features, logger }, + rawLanguages, + variant, + ); + toolsInput = bundle.url; } /** @@ -732,18 +744,55 @@ export async function getCodeQLSource( let compressionMethod: tar.CompressionMethod; if (!url) { + const bundleTagName = tagName; + if (bundleTagName === undefined) { + throw new Error( + "Could not determine a release tag for the requested CodeQL bundle.", + ); + } + compressionMethod = cliVersion !== undefined && (await useZstdBundle(cliVersion, tarSupportsZstd)) ? "zstd" : "gzip"; - url = await getCodeQLBundleDownloadURL( - tagName!, - apiDetails, - compressionMethod, - logger, + const perLanguageBundleLanguage = await getPerLanguageBundleLanguage( + { env: getEnv(), features, logger }, + { + rawLanguages, + cliVersion, + compressionMethod, + platform: getBundlePlatform(), + variant, + }, ); + + // Resolves the combined or per-language bundle URL for the requested release. + const resolveBundleURL = (language?: BuiltInLanguage) => + getCodeQLBundleDownloadURL( + bundleTagName, + apiDetails, + getCodeQLBundleName(compressionMethod, language), + logger, + ); + + const combinedBundleURL = await resolveBundleURL(); + if (perLanguageBundleLanguage !== undefined) { + logger.info( + `Selected the per-language CodeQL bundle for '${perLanguageBundleLanguage}'.`, + ); + url = await resolveBundleURL(perLanguageBundleLanguage); + bundle = { + kind: "per-language", + url, + language: perLanguageBundleLanguage, + combinedBundleURL, + }; + } else { + url = combinedBundleURL; + bundle = { kind: "combined", url }; + } } else { const method = tar.inferCompressionMethod(url); if (method === undefined) { @@ -753,6 +802,13 @@ export async function getCodeQLSource( ); } compressionMethod = method; + + bundle ??= getCodeQLBundleFromUrl(url); + if (bundle.kind === "per-language") { + logger.info( + `${url} appears to be a CodeQL bundle that contains only ${bundle.language}.`, + ); + } } if (cliVersion) { @@ -761,7 +817,7 @@ export async function getCodeQLSource( logger.info(`Using CodeQL CLI sourced from ${url} .`); } return { - bundle: { kind: "combined", url }, + bundle, bundleVersion, cliVersion, compressionMethod, @@ -823,9 +879,10 @@ export const downloadCodeQL = async function ( ); } - const toolcacheDestination = getToolcacheDestination(source, logger); - const extractedBundlePath = - toolcacheDestination ?? getTempExtractionDir(tempDir); + const toolcacheDestination = getToolcacheDestination({ logger }, source); + const extractedBundlePath = toolcacheDestination.orElse( + getTempExtractionDir(tempDir), + ); const statusReport = await downloadAndExtract( codeqlURL, @@ -837,38 +894,51 @@ export const downloadCodeQL = async function ( logger, ); - if (toolcacheDestination) { - writeToolcacheMarkerFile(toolcacheDestination, logger); + if (toolcacheDestination.isSuccess()) { + writeToolcacheMarkerFile(toolcacheDestination.value, logger); } else { - logger.debug( - "Could not cache CodeQL tools because we could not determine the bundle version from the " + - `URL ${codeqlURL}.`, - ); + logger.debug(toolcacheDestination.value); } return { codeqlFolder: extractedBundlePath, - statusReport, + statusReport: + bundle.kind === "per-language" + ? { + ...statusReport, + perLanguage: { tools_bundle_language: bundle.language }, + } + : statusReport, }; }; /** - * Returns the canonical toolcache directory for a resolved download, or `undefined` if its bundle - * version is unknown. + * Returns the canonical toolcache directory, or the reason the bundle cannot be cached. */ function getToolcacheDestination( + { logger }: ActionState<["Logger"]>, source: CodeQLDownloadSource, - logger: Logger, -): string | undefined { +): util.Result { + if (source.bundle.kind !== "combined") { + return new util.Failure( + "Not caching the CodeQL tools because they came from a bundle that contains only a " + + "single language.", + ); + } if (!source.bundleVersion) { - return undefined; + return new util.Failure( + "Could not cache CodeQL tools because we could not determine the bundle version from the " + + `URL ${source.bundle.url}.`, + ); } - return getToolcacheDirectory( - getCanonicalToolcacheVersion( - source.cliVersion, - source.bundleVersion, - logger, + return new util.Success( + getToolcacheDirectory( + getCanonicalToolcacheVersion( + source.cliVersion, + source.bundleVersion, + logger, + ), ), ); } @@ -1046,6 +1116,9 @@ export async function setupCodeQLBundle( /** * Performs eligible toolcache cleanup once, then downloads and extracts the resolved bundle. * + * If an automatically selected per-language bundle is missing, downloads the combined bundle + * from the same release instead. Explicit bundle URLs are not substituted. + * * @returns The extraction directory and download timings. */ export async function downloadCodeQLBundle( @@ -1058,14 +1131,53 @@ export async function downloadCodeQLBundle( codeqlFolder: string; statusReport: ToolsDownloadStatusReport; }> { + const { bundle } = source; + const { logger } = action; + await tryDeleteToolcacheBundles(action); - return await downloadCodeQL( - source, - apiDetails, - tarVersion, - tempDir, - action.logger, - ); + + const startTime = performance.now(); + try { + return await downloadCodeQL( + source, + apiDetails, + tarVersion, + tempDir, + logger, + ); + } catch (e) { + if ( + bundle.kind !== "per-language" || + bundle.combinedBundleURL === undefined || + util.asHTTPError(e)?.status !== 404 + ) { + throw e; + } + logger.warning( + `No per-language CodeQL bundle for '${bundle.language}' was found at ${bundle.url}, so ` + + "falling back to the bundle that contains all languages. This analysis will still " + + "produce correct results, but will take longer to set up.", + ); + + const result = await downloadCodeQL( + { + ...source, + bundle: { kind: "combined", url: bundle.combinedBundleURL }, + }, + apiDetails, + tarVersion, + tempDir, + logger, + ); + return { + ...result, + statusReport: { + ...result.statusReport, + totalDurationMs: util.durationMsSince(startTime), + perLanguage: { tools_per_language_bundle_fallback: true }, + }, + }; + } } async function useZstdBundle( @@ -1085,9 +1197,15 @@ function getTempExtractionDir(tempDir: string) { } /** - * Get the URL of the latest nightly CodeQL bundle. + * Selects a bundle from the latest nightly release, preferring a per-language bundle when eligible. + * Records the combined bundle URL from that release for use if the selected asset is missing. */ -async function getNightlyToolsUrl(logger: Logger) { +async function getLatestNightlyBundle( + action: ActionState<["Logger", "ReadOnlyEnv", "FeatureFlags"]>, + rawLanguages: string[] | undefined, + variant: util.GitHubVariant, +): Promise { + const { logger } = action; const zstdAvailability = await tar.isZstdAvailable(logger); // The nightly is guaranteed to have a zstd bundle const compressionMethod = (await useZstdBundle( @@ -1097,6 +1215,15 @@ async function getNightlyToolsUrl(logger: Logger) { ? "zstd" : "gzip"; + const language = await getPerLanguageBundleLanguage(action, { + rawLanguages, + cliVersion: undefined, + compressionMethod, + platform: getBundlePlatform(), + variant, + isLatestNightly: true, + }); + try { // Since nightlies are prereleases, we can't just download the latest release // on the repository. So instead we need to find the latest pre-release @@ -1112,7 +1239,17 @@ async function getNightlyToolsUrl(logger: Logger) { if (!latestRelease) { throw new Error("Could not find the latest nightly release."); } - return `https://github.com/${CODEQL_NIGHTLIES_REPOSITORY_OWNER}/${CODEQL_NIGHTLIES_REPOSITORY_NAME}/releases/download/${latestRelease.tag_name}/${getCodeQLBundleName(compressionMethod)}`; + const assetUrl = (name: string) => + `https://github.com/${CODEQL_NIGHTLIES_REPOSITORY_OWNER}/${CODEQL_NIGHTLIES_REPOSITORY_NAME}/releases/download/${latestRelease.tag_name}/${name}`; + const url = assetUrl(getCodeQLBundleName(compressionMethod, language)); + return language === undefined + ? { kind: "combined", url } + : { + kind: "per-language", + url, + language, + combinedBundleURL: assetUrl(getCodeQLBundleName(compressionMethod)), + }; } catch (e) { throw new Error( `Failed to retrieve the latest nightly release: ${util.wrapError(e)}`, diff --git a/src/status-report.ts b/src/status-report.ts index a2acd631d6..c392b51922 100644 --- a/src/status-report.ts +++ b/src/status-report.ts @@ -624,29 +624,6 @@ export interface InitWithConfigStatusReport extends InitStatusReport { config_file: string; } -/** Fields of the init status report populated when the tools source is `download`. */ -export interface InitToolsDownloadFields { - /** - * Time taken to download the bundle, in milliseconds. Not populated when the bundle is downloaded - * and extracted concurrently. - */ - tools_download_duration_ms?: number; - /** - * Time taken to extract the bundle, in milliseconds. Not populated when the bundle is downloaded - * and extracted concurrently. - */ - tools_extraction_duration_ms?: number; - /** - * Total time taken to make the bundle available on disk, in milliseconds. This includes any time - * spent on a streaming attempt that failed and fell back to downloading before extracting. - */ - tools_total_duration_ms?: number; - /** - * Whether the relevant tools dotcom feature flags have been misconfigured. - * Only populated if we attempt to determine the default version based on the dotcom feature flags. */ - tools_feature_flags_valid?: boolean; -} - /** * Composes a `InitWithConfigStatusReport` from the given values. * diff --git a/src/status-report/tools-download.test.ts b/src/status-report/tools-download.test.ts new file mode 100644 index 0000000000..856bf882f6 --- /dev/null +++ b/src/status-report/tools-download.test.ts @@ -0,0 +1,80 @@ +import test from "ava"; + +import { BuiltInLanguage } from "../languages"; + +import { createInitToolsDownloadFields } from "./tools-download"; + +test("createInitToolsDownloadFields omits absent download data", (t) => { + t.deepEqual(createInitToolsDownloadFields(undefined, undefined), {}); +}); + +test("createInitToolsDownloadFields reports feature flags without a download", (t) => { + t.deepEqual(createInitToolsDownloadFields(undefined, false), { + tools_feature_flags_valid: false, + }); +}); + +test("createInitToolsDownloadFields reports only the total for a streaming download", (t) => { + t.deepEqual( + createInitToolsDownloadFields({ totalDurationMs: 300 }, undefined), + { tools_total_duration_ms: 300 }, + ); +}); + +test("createInitToolsDownloadFields preserves per-language metadata", (t) => { + t.deepEqual( + createInitToolsDownloadFields( + { + totalDurationMs: 300, + perLanguage: { tools_bundle_language: BuiltInLanguage.java }, + }, + true, + ), + { + tools_total_duration_ms: 300, + tools_bundle_language: BuiltInLanguage.java, + tools_feature_flags_valid: true, + }, + ); +}); + +test("createInitToolsDownloadFields preserves fallback and per-attempt timings", (t) => { + t.deepEqual( + createInitToolsDownloadFields( + { + downloadDurationMs: 200, + extractionDurationMs: 100, + totalDurationMs: 1000, + perLanguage: { tools_per_language_bundle_fallback: true }, + }, + undefined, + ), + { + tools_download_duration_ms: 200, + tools_extraction_duration_ms: 100, + tools_total_duration_ms: 1000, + tools_per_language_bundle_fallback: true, + }, + ); +}); + +test("createInitToolsDownloadFields preserves zero durations and false flags", (t) => { + t.deepEqual( + createInitToolsDownloadFields( + { + downloadDurationMs: 0, + extractionDurationMs: 0, + totalDurationMs: 0, + perLanguage: { tools_per_language_bundle_fallback: false }, + }, + false, + ), + { + tools_download_duration_ms: 0, + tools_extraction_duration_ms: 0, + tools_total_duration_ms: 0, + tools_per_language_bundle_fallback: false, + tools_feature_flags_valid: false, + }, + ); +}); diff --git a/src/status-report/tools-download.ts b/src/status-report/tools-download.ts new file mode 100644 index 0000000000..a5f7dffbf8 --- /dev/null +++ b/src/status-report/tools-download.ts @@ -0,0 +1,56 @@ +import type { ToolsDownloadStatusReport } from "../tools-download"; + +/** Telemetry describing per-language bundle downloads. */ +export interface PerLanguageToolsStatusReport { + /** The language of the single-language bundle that was downloaded, if any. */ + tools_bundle_language?: string; + /** + * Whether we tried to download a single-language bundle, but it did not exist and we fell back to + * the combined bundle. + */ + tools_per_language_bundle_fallback?: boolean; +} + +/** Fields of the init status report populated when the tools source is `download`. */ +export interface InitToolsDownloadFields extends PerLanguageToolsStatusReport { + /** + * Time taken to download the bundle, in milliseconds. Not populated when the bundle is downloaded + * and extracted concurrently. + */ + tools_download_duration_ms?: number; + /** + * Time taken to extract the bundle, in milliseconds. Not populated when the bundle is downloaded + * and extracted concurrently. + */ + tools_extraction_duration_ms?: number; + /** + * Total time taken to make the bundle available on disk, including failed download attempts + * before a fallback, in milliseconds. + */ + tools_total_duration_ms?: number; + /** + * Whether the relevant tools dotcom feature flags have been misconfigured. + * Only populated if we attempt to determine the default version based on the dotcom feature flags. */ + tools_feature_flags_valid?: boolean; +} + +/** Converts download results to telemetry fields shared by the init and setup-codeql Actions. */ +export function createInitToolsDownloadFields( + report: ToolsDownloadStatusReport | undefined, + toolsFeatureFlagsValid: boolean | undefined, +): InitToolsDownloadFields { + const fields: InitToolsDownloadFields = { ...report?.perLanguage }; + if (report?.downloadDurationMs !== undefined) { + fields.tools_download_duration_ms = report.downloadDurationMs; + } + if (report?.extractionDurationMs !== undefined) { + fields.tools_extraction_duration_ms = report.extractionDurationMs; + } + if (report?.totalDurationMs !== undefined) { + fields.tools_total_duration_ms = report.totalDurationMs; + } + if (toolsFeatureFlagsValid !== undefined) { + fields.tools_feature_flags_valid = toolsFeatureFlagsValid; + } + return fields; +} diff --git a/src/testing-utils.ts b/src/testing-utils.ts index 7d33589ec6..f15cee2e71 100644 --- a/src/testing-utils.ts +++ b/src/testing-utils.ts @@ -32,6 +32,7 @@ import { } from "./feature-flags"; import { Logger } from "./logging"; import { OverlayDatabaseMode } from "./overlay/overlay-database-mode"; +import { getBundlePlatform } from "./platform"; import { ActionName } from "./status-report"; import { DEFAULT_DEBUG_ARTIFACT_NAME, @@ -933,21 +934,14 @@ export function mockBundleDownloadApi({ platformSpecific?: boolean; tagName: string; }): string { - const platform = - process.platform === "win32" - ? "win64" - : process.platform === "linux" - ? process.arch === "arm64" - ? "linux-arm64" - : "linux64" - : "osx64"; + const platform = platformSpecific ? getBundlePlatform() : undefined; const baseUrl = apiDetails?.url ?? "https://example.com"; const bundleUrls = ["tar.gz", "tar.zst"].map((extension) => { const relativeUrl = apiDetails ? `/${repo}/releases/download/${tagName}/codeql-bundle${ - platformSpecific ? `-${platform}` : "" + platform !== undefined ? `-${platform}` : "" }.${extension}` : `/download/${tagName}/codeql-bundle.${extension}`; diff --git a/src/tools-download.ts b/src/tools-download.ts index 222a18cd91..a92dad0acf 100644 --- a/src/tools-download.ts +++ b/src/tools-download.ts @@ -13,10 +13,12 @@ import * as semver from "semver"; import { ActionState } from "./action-common"; import { ActionsEnvVars, getEnv, ReadOnlyEnv } from "./environment"; import { formatDuration, Logger } from "./logging"; +import type { PerLanguageToolsStatusReport } from "./status-report/tools-download"; import * as tar from "./tar"; import { asHTTPError, cleanUpPath, + durationMsSince, getErrorMessage, getRequiredEnvParam, HTTPError, @@ -50,10 +52,11 @@ export type ToolsDownloadStatusReport = { */ extractionDurationMs?: number; /** - * Total time taken to make the bundle available on disk, in milliseconds. This includes any time - * spent on a streaming attempt that failed and fell back to downloading before extracting. + * Total time taken to make the bundle available on disk, including failed download attempts + * before a fallback, in milliseconds. */ totalDurationMs: number; + perLanguage?: PerLanguageToolsStatusReport; }; export async function downloadAndExtract( @@ -84,7 +87,7 @@ export async function downloadAndExtract( logger, ); - const totalDurationMs = Math.round(performance.now() - startTime); + const totalDurationMs = durationMsSince(startTime); logger.info( `Finished downloading and extracting CodeQL bundle to ${dest} (${formatDuration( totalDurationMs, @@ -117,7 +120,7 @@ export async function downloadAndExtract( authorization, headers, ); - const downloadDurationMs = Math.round(performance.now() - toolsDownloadStart); + const downloadDurationMs = durationMsSince(toolsDownloadStart); logger.info( `Finished downloading CodeQL bundle to ${archivedBundlePath} (${formatDuration( @@ -137,7 +140,7 @@ export async function downloadAndExtract( tarVersion, logger, ); - extractionDurationMs = Math.round(performance.now() - extractionStart); + extractionDurationMs = durationMsSince(extractionStart); logger.info( `Finished extracting CodeQL bundle to ${dest} (${formatDuration( extractionDurationMs, @@ -150,7 +153,7 @@ export async function downloadAndExtract( return { downloadDurationMs, extractionDurationMs, - totalDurationMs: Math.round(performance.now() - startTime), + totalDurationMs: durationMsSince(startTime), }; } diff --git a/src/util.test.ts b/src/util.test.ts index cca457cbe6..074310279f 100644 --- a/src/util.test.ts +++ b/src/util.test.ts @@ -1,6 +1,7 @@ import * as fs from "fs"; import * as os from "os"; import path from "path"; +import { performance } from "perf_hooks"; import * as core from "@actions/core"; import test from "ava"; @@ -508,6 +509,26 @@ test("joinAtMost - truncates list if array is > than limit", (t) => { t.false(result.includes("test6")); }); +test.serial( + "durationMsSince rounds elapsed milliseconds rather than the timestamps", + (t) => { + const startTime = 1000.25; + const now = sinon.stub(performance, "now"); + for (const [endTime, expected] of [ + [1000.25, 0], + [1000.74, 0], + [1000.75, 1], + [1001.74, 1], + [1001.75, 2], + [2000.74, 1000], + [2000.75, 1001], + ]) { + now.returns(endTime); + t.is(util.durationMsSince(startTime), expected); + } + }, +); + test("Success creates a success result", (t) => { const result = new util.Success("test value"); t.true(result.isSuccess()); diff --git a/src/util.ts b/src/util.ts index 49fe924f66..456cd7c3d2 100644 --- a/src/util.ts +++ b/src/util.ts @@ -2,6 +2,7 @@ import * as fs from "fs"; import * as fsPromises from "fs/promises"; import * as os from "os"; import * as path from "path"; +import { performance } from "perf_hooks"; import * as core from "@actions/core"; import * as io from "@actions/io"; @@ -681,6 +682,11 @@ export async function bundleDb( return databaseBundlePath; } +/** Returns the elapsed milliseconds, rounded, since a `performance.now()` timestamp. */ +export function durationMsSince(startTime: number): number { + return Math.round(performance.now() - startTime); +} + /** * @param milliseconds time to delay * @param opts options