diff --git a/.github/actions/setup-electron/action.yml b/.github/actions/setup-electron/action.yml index ae346d7bd5597a..a3e0486cbcf269 100644 --- a/.github/actions/setup-electron/action.yml +++ b/.github/actions/setup-electron/action.yml @@ -1,5 +1,5 @@ name: Setup Electron -description: Restores cached Electron archives, validates and prepares Electron, and optionally saves the cache. Expects pnpm to be set up, except in lookup-only mode. +description: Restores cached Electron archives, validates and prepares Electron, and optionally saves the cache. Keeps an Electron that was prepared from the same inputs, as in a workspace image. Expects pnpm to be set up, except in lookup-only mode. inputs: arch: @@ -20,6 +20,22 @@ outputs: runs: using: composite steps: + # `pnpm run electron` prepares .build/electron from these inputs, including the root package.json, + # which it packages and which holds the Electron version, and the pnpm-lock.yaml that pins + # @vscode/gulp-electron. A workspace image holds the Electron that it prepared (see + # .github/workflows/workspace_image/README.md). + - name: Check the prepared Electron + id: prepared + if: inputs.lookup-only != 'true' + shell: bash + run: | + if [ -d .build/electron ] && [ "$(cat .build/electron.stamp 2>/dev/null)" = "$STAMP" ]; then + echo "Electron is prepared from the same inputs" + echo "current=true" >> "$GITHUB_OUTPUT" + fi + env: + STAMP: ${{ runner.os }}-${{ inputs.arch }}-${{ hashFiles('build/checksums/electron.txt', 'product.json', 'package.json', 'pnpm-lock.yaml', 'build/lib/electron.ts', 'build/lib/electronVersion.ts', 'build/pnpm-lock.yaml', 'resources/darwin/*.icns', 'resources/win32/code.ico') }} + - name: Prepare Electron cache path if: runner.os != 'Windows' shell: bash @@ -39,6 +55,7 @@ runs: - name: Restore Electron cache id: restore + if: steps.prepared.outputs.current != 'true' uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ env.ELECTRON_CACHE_PATH }} @@ -46,9 +63,10 @@ runs: lookup-only: ${{ inputs.lookup-only }} - name: Download Electron - if: inputs.lookup-only != 'true' && runner.os != 'Windows' + if: inputs.lookup-only != 'true' && steps.prepared.outputs.current != 'true' && runner.os != 'Windows' shell: bash run: | + rm -f .build/electron.stamp for i in {1..3}; do if pnpm run electron "$VSCODE_ARCH"; then echo "Download successful on attempt $i" @@ -67,12 +85,13 @@ runs: VSCODE_ARCH: ${{ inputs.arch }} - name: Download Electron - if: inputs.lookup-only != 'true' && runner.os == 'Windows' + if: inputs.lookup-only != 'true' && steps.prepared.outputs.current != 'true' && runner.os == 'Windows' shell: pwsh run: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" + Remove-Item -Force -ErrorAction SilentlyContinue .build/electron.stamp for ($i = 1; $i -le 3; $i++) { try { exec { pnpm run electron $env:VSCODE_ARCH } @@ -90,8 +109,15 @@ runs: env: VSCODE_ARCH: ${{ inputs.arch }} + - name: Stamp the prepared Electron + if: inputs.lookup-only != 'true' && steps.prepared.outputs.current != 'true' + shell: bash + run: echo "$STAMP" > .build/electron.stamp + env: + STAMP: ${{ runner.os }}-${{ inputs.arch }}-${{ hashFiles('build/checksums/electron.txt', 'product.json', 'package.json', 'pnpm-lock.yaml', 'build/lib/electron.ts', 'build/lib/electronVersion.ts', 'build/pnpm-lock.yaml', 'resources/darwin/*.icns', 'resources/win32/code.ico') }} + - name: Save Electron cache - if: inputs.lookup-only != 'true' && inputs.save-cache == 'true' && steps.restore.outputs.cache-hit != 'true' + if: inputs.lookup-only != 'true' && inputs.save-cache == 'true' && steps.prepared.outputs.current != 'true' && steps.restore.outputs.cache-hit != 'true' uses: actions/cache/save@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0 with: path: ${{ env.ELECTRON_CACHE_PATH }} diff --git a/.github/workflows/node_modules_cache/README.md b/.github/workflows/node_modules_cache/README.md index 7842b9d2fac222..d288f5d4e944ce 100644 --- a/.github/workflows/node_modules_cache/README.md +++ b/.github/workflows/node_modules_cache/README.md @@ -84,7 +84,10 @@ on Linux and `LOCALAPPDATA` on Windows. Cache paths and keys are handled within the action. Even on a cache hit, PR jobs run `pnpm run electron` to validate and prepare the -application from the cached archives using the current checkout. Checksum +application from the cached archives using the current checkout, unless +`.build/electron` was prepared from the same inputs: `setup-electron` stamps +them in `.build/electron.stamp`, which keeps the Electron of a +[workspace image](../workspace_image/README.md). Checksum validation remains enabled: the current downloader still fetches `SHASUMS256.txt` from GitHub, so this cache avoids the large ZIP downloads but does not make Electron setup entirely network-independent. diff --git a/.github/workflows/pr-darwin-test.yml b/.github/workflows/pr-darwin-test.yml index 8eff8dda77fd0d..d14b4c49fc2ad6 100644 --- a/.github/workflows/pr-darwin-test.yml +++ b/.github/workflows/pr-darwin-test.yml @@ -41,6 +41,10 @@ on: description: Reason for selecting the Agent Host test profile type: string default: Change detection unavailable + workspace_image_branch: + description: The branch whose workspace images the jobs use (see .github/workflows/workspace_image/README.md) + type: string + default: main env: NPM_ARCH: arm64 @@ -79,28 +83,79 @@ jobs: UNIT_TESTS: 'true' TEST_SELECTION: 'true' steps: &steps + # A workspace image of main holds a workspace whose dependencies, Electron and Playwright browsers + # are installed, which the checkout updates (see .github/workflows/workspace_image/README.md). Its + # scripts run before the checkout, so they come from the API, at the commit that the job tests. + - name: Download the workspace image scripts + id: image-scripts + continue-on-error: true + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + dir="$RUNNER_TEMP/workspace-image" + mkdir -p "$dir" + echo '{ "type": "module" }' > "$dir/package.json" + files=(.nvmrc .github/workflows/workspace_image/image.ts) + args=() + for file in "${files[@]}"; do + args+=(-o "$dir/${file##*/}" "$GITHUB_API_URL/repos/$GITHUB_REPOSITORY/contents/$file?ref=$GITHUB_SHA") + done + curl -fsSL --retry 3 --parallel -H "Authorization: Bearer $GH_TOKEN" -H 'Accept: application/vnd.github.raw' "${args[@]}" + for file in "${files[@]}"; do + [ -s "$dir/${file##*/}" ] + done + echo "node-version=$(tr -d '[:space:]' < "$dir/.nvmrc")" >> "$GITHUB_OUTPUT" + + - name: Setup Node.js + if: steps.image-scripts.outcome == 'success' + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: ${{ steps.image-scripts.outputs.node-version }} + + # Without an image, the job installs everything as before + - name: Restore the workspace image + id: image + if: steps.image-scripts.outcome == 'success' + continue-on-error: true + timeout-minutes: 5 + working-directory: ${{ runner.temp }} + run: node "$RUNNER_TEMP/workspace-image/image.ts" restore --name workspace-image-darwin-arm64.img --branch "$WORKSPACE_IMAGE_BRANCH" + env: + GH_TOKEN: ${{ github.token }} + WORKSPACE_IMAGE_BRANCH: ${{ inputs.workspace_image_branch }} + - name: Checkout microsoft/vscode uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: lfs: true + # Keeps the files of the workspace image, and reuses its .git + clean: false - name: Setup Node.js + if: steps.image-scripts.outcome != 'success' uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version-file: .nvmrc + - name: Compare the dependencies with the workspace image + id: image-deps + if: steps.image.outputs.used == 'true' + run: node "$RUNNER_TEMP/workspace-image/image.ts" deps + - name: Setup pnpm uses: ./.github/actions/setup-pnpm - name: Restore node_modules cache id: cache-node-modules + if: steps.image.outputs.used != 'true' uses: ./.github/actions/restore-node-modules with: key-prefix: node_modules-macos key-args: "darwin ${{ env.VSCODE_ARCH }} $(node -p process.arch)" - name: Install dependencies - if: steps.cache-node-modules.outputs.cache-hit != 'true' + if: steps.cache-node-modules.outputs.cache-hit != 'true' && steps.image-deps.outputs.current != 'true' run: | set -e c++ --version @@ -164,8 +219,9 @@ jobs: run: pnpm run compile # pr-node-modules.yml fills this cache on main, so pull requests don't download the browsers. + # A workspace image holds them already (PLAYWRIGHT_BROWSERS_PATH). - name: Restore Playwright browsers - if: ${{ env.BROWSER_TESTS == 'true' }} + if: ${{ env.BROWSER_TESTS == 'true' && steps.image.outputs.used != 'true' }} uses: ./.github/actions/restore-playwright with: browsers: --only-shell chromium webkit diff --git a/.github/workflows/pr-linux-test.yml b/.github/workflows/pr-linux-test.yml index f177b40c3bab56..a75d1c3bc201db 100644 --- a/.github/workflows/pr-linux-test.yml +++ b/.github/workflows/pr-linux-test.yml @@ -37,6 +37,10 @@ on: description: Reason for selecting the Agent Host test profile type: string default: Change detection unavailable + workspace_image_branch: + description: The branch whose workspace images the jobs use (see .github/workflows/workspace_image/README.md) + type: string + default: main env: NPM_ARCH: x64 @@ -69,16 +73,66 @@ jobs: UNIT_TESTS: 'true' UNIT_TEST_SUITE: electron steps: &steps + # A workspace image of main holds a workspace whose dependencies, Electron and Playwright browsers + # are installed, which the checkout updates (see .github/workflows/workspace_image/README.md). Its + # scripts run before the checkout, so they come from the API, at the commit that the job tests. + - name: Download the workspace image scripts + id: image-scripts + continue-on-error: true + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + dir="$RUNNER_TEMP/workspace-image" + mkdir -p "$dir" + echo '{ "type": "module" }' > "$dir/package.json" + files=(.nvmrc .github/workflows/workspace_image/image.ts) + args=() + for file in "${files[@]}"; do + args+=(-o "$dir/${file##*/}" "$GITHUB_API_URL/repos/$GITHUB_REPOSITORY/contents/$file?ref=$GITHUB_SHA") + done + curl -fsSL --retry 3 --parallel -H "Authorization: Bearer $GH_TOKEN" -H 'Accept: application/vnd.github.raw' "${args[@]}" + for file in "${files[@]}"; do + [ -s "$dir/${file##*/}" ] + done + echo "node-version=$(tr -d '[:space:]' < "$dir/.nvmrc")" >> "$GITHUB_OUTPUT" + + - name: Setup Node.js + if: steps.image-scripts.outcome == 'success' + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: ${{ steps.image-scripts.outputs.node-version }} + + # Without an image, the job installs everything as before + - name: Restore the workspace image + id: image + if: steps.image-scripts.outcome == 'success' + continue-on-error: true + timeout-minutes: 5 + working-directory: ${{ runner.temp }} + run: node "$RUNNER_TEMP/workspace-image/image.ts" restore --name workspace-image-linux-x64.img --branch "$WORKSPACE_IMAGE_BRANCH" + env: + GH_TOKEN: ${{ github.token }} + WORKSPACE_IMAGE_BRANCH: ${{ inputs.workspace_image_branch }} + - name: Checkout microsoft/vscode uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: lfs: true + # Keeps the files of the workspace image, and reuses its .git + clean: false - name: Setup Node.js + if: steps.image-scripts.outcome != 'success' uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version-file: .nvmrc + - name: Compare the dependencies with the workspace image + id: image-deps + if: steps.image.outputs.used == 'true' + run: node "$RUNNER_TEMP/workspace-image/image.ts" deps + - name: Setup pnpm uses: ./.github/actions/setup-pnpm @@ -106,13 +160,14 @@ jobs: - name: Restore node_modules cache id: cache-node-modules + if: steps.image.outputs.used != 'true' uses: ./.github/actions/restore-node-modules with: key-prefix: node_modules-linux key-args: "linux ${{ env.VSCODE_ARCH }} $(node -p process.arch)" - name: Install build dependencies - if: steps.cache-node-modules.outputs.cache-hit != 'true' + if: steps.cache-node-modules.outputs.cache-hit != 'true' && steps.image-deps.outputs.current != 'true' working-directory: build run: | set -e @@ -129,7 +184,7 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Install dependencies - if: steps.cache-node-modules.outputs.cache-hit != 'true' + if: steps.cache-node-modules.outputs.cache-hit != 'true' && steps.image-deps.outputs.current != 'true' run: | set -e @@ -306,8 +361,9 @@ jobs: run: pnpm run compile # pr-node-modules.yml fills this cache on main, so pull requests don't download the browsers. + # A workspace image holds them already (PLAYWRIGHT_BROWSERS_PATH). - name: Restore Playwright browsers - if: ${{ env.BROWSER_TESTS == 'true' }} + if: ${{ env.BROWSER_TESTS == 'true' && steps.image.outputs.used != 'true' }} uses: ./.github/actions/restore-playwright with: browsers: --only-shell chromium diff --git a/.github/workflows/pr-win32-test.yml b/.github/workflows/pr-win32-test.yml index 75aba80e48b826..8842c2b44c3394 100644 --- a/.github/workflows/pr-win32-test.yml +++ b/.github/workflows/pr-win32-test.yml @@ -41,6 +41,10 @@ on: description: Reason for selecting the Agent Host test profile type: string default: Change detection unavailable + workspace_image_branch: + description: The branch whose workspace images the jobs use (see .github/workflows/workspace_image/README.md) + type: string + default: main env: NPM_ARCH: x64 @@ -74,6 +78,53 @@ jobs: UNIT_TESTS: 'true' TEST_SELECTION: 'true' steps: &steps + # A workspace image of main holds a workspace whose dependencies, Electron and Playwright browsers + # are installed, which the checkout updates (see .github/workflows/workspace_image/README.md). Its + # scripts run before the checkout, so they come from the API, at the commit that the job tests. + - name: Download the workspace image scripts + id: image-scripts + continue-on-error: true + shell: bash + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + dir="$RUNNER_TEMP/workspace-image" + mkdir -p "$dir" + echo '{ "type": "module" }' > "$dir/package.json" + files=(.nvmrc .github/workflows/workspace_image/{image.ts,vhd.ps1,Vhd.cs}) + args=() + for file in "${files[@]}"; do + args+=(-o "$dir/${file##*/}" "$GITHUB_API_URL/repos/$GITHUB_REPOSITORY/contents/$file?ref=$GITHUB_SHA") + done + curl -fsSL --retry 3 --parallel -H "Authorization: Bearer $GH_TOKEN" -H 'Accept: application/vnd.github.raw' "${args[@]}" + for file in "${files[@]}"; do + [ -s "$dir/${file##*/}" ] + done + echo "node-version=$(tr -d '[:space:]' < "$dir/.nvmrc")" >> "$GITHUB_OUTPUT" + + - name: Setup Node.js + if: steps.image-scripts.outcome == 'success' + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: ${{ steps.image-scripts.outputs.node-version }} + + # The image is a Dev Drive in a VHDX, mounted at the parent of the workspace like the Dev Drive + # below, which the job creates without an image. The WSL shard keeps its workspace on drive C. + # The first PowerShell of a job takes seconds to start, so this step runs in bash, and the + # PowerShell that attaches the image (vhd.ps1) starts while the image downloads. + - name: Restore the workspace image + id: image + if: ${{ steps.image-scripts.outcome == 'success' && !(env.ELECTRON_TESTS == 'true' && env.SMOKE_TESTS == 'true' && env.SMOKE_SHARD_INDEX == '1') }} + continue-on-error: true + timeout-minutes: 5 + shell: bash + working-directory: ${{ runner.temp }} + run: node "$RUNNER_TEMP/workspace-image/image.ts" restore --name workspace-image-win32-x64.img --branch "$WORKSPACE_IMAGE_BRANCH" + env: + GH_TOKEN: ${{ github.token }} + WORKSPACE_IMAGE_BRANCH: ${{ inputs.workspace_image_branch }} + # The larger runners keep the workspace on the OS disk, where creating many small files, such as # extracting node_modules, takes twice as long as on the 1ES runners' temporary disk. A Dev Drive in # a VHDX on the same disk is faster than both. It is mounted at the parent of the workspace, so that @@ -82,7 +133,7 @@ jobs: # runs-on of electron-smoke-1), and WSL cannot open folders on a volume that is mounted in a folder of # drive C: anyway. - name: Move the workspace to a Dev Drive - if: ${{ !(env.ELECTRON_TESTS == 'true' && env.SMOKE_TESTS == 'true' && env.SMOKE_SHARD_INDEX == '1') }} + if: ${{ steps.image.outputs.used != 'true' && !(env.ELECTRON_TESTS == 'true' && env.SMOKE_TESTS == 'true' && env.SMOKE_SHARD_INDEX == '1') }} shell: pwsh working-directory: ${{ runner.temp }} run: | @@ -119,6 +170,8 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: lfs: true + # Keeps the files of the workspace image, and reuses its .git + clean: false # The WSL steps only run in shard 1, which is where test/smoke/src/shard.ts pins the WSL suite. # pr-node-modules.yml fills this cache on main, so pull requests don't download the installer. @@ -136,22 +189,30 @@ jobs: WSL_INSTALLER_CACHE_DIR: ${{ github.workspace }}\.build\wsl-installer - name: Setup Node.js + if: steps.image-scripts.outcome != 'success' uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version-file: .nvmrc + - name: Compare the dependencies with the workspace image + id: image-deps + if: steps.image.outputs.used == 'true' + shell: pwsh + run: node "$env:RUNNER_TEMP\workspace-image\image.ts" deps + - name: Setup pnpm uses: ./.github/actions/setup-pnpm - name: Restore node_modules cache id: cache-node-modules + if: steps.image.outputs.used != 'true' uses: ./.github/actions/restore-node-modules with: key-prefix: node_modules-windows key-args: "win32 ${{ env.VSCODE_ARCH }} $(node -p process.arch)" - name: Install dependencies - if: steps.cache-node-modules.outputs.cache-hit != 'true' + if: steps.cache-node-modules.outputs.cache-hit != 'true' && steps.image-deps.outputs.current != 'true' shell: pwsh run: | . build/azure-pipelines/win32/exec.ps1 @@ -222,8 +283,9 @@ jobs: run: pnpm run compile # pr-node-modules.yml fills this cache on main, so pull requests don't download the browsers. + # A workspace image holds them already (PLAYWRIGHT_BROWSERS_PATH). - name: Restore Playwright browsers - if: ${{ env.BROWSER_TESTS == 'true' }} + if: ${{ env.BROWSER_TESTS == 'true' && steps.image.outputs.used != 'true' }} uses: ./.github/actions/restore-playwright with: browsers: --only-shell chromium diff --git a/.github/workflows/pr-workspace-images.yml b/.github/workflows/pr-workspace-images.yml new file mode 100644 index 00000000000000..c130f5d5c9d8ae --- /dev/null +++ b/.github/workflows/pr-workspace-images.yml @@ -0,0 +1,378 @@ +name: Code OSS (workspace images) + +# Builds the workspace images that the test jobs of pull requests (pr-linux-test.yml, +# pr-darwin-test.yml and pr-win32-test.yml) mount instead of installing the dependencies, Electron and +# the Playwright browsers: a disk image of a workspace of main at the path of the workspaces of the +# jobs, with a .git that their checkouts reuse. See .github/workflows/workspace_image/README.md. +on: + # Only when an input of the images changes: the source code doesn't need to be current, as the + # checkout of a job fetches and writes only what changed since the commit of its image + push: + branches: + - main + # The inputs of the install (see build/npm/installStateHash.ts), of the native builds (see + # NATIVE_BUILD_INPUTS in workspace_image/image.ts) and of the prepared Electron (see the stamp in + # .github/actions/setup-electron/action.yml) + paths: + - '**/pnpm-lock.yaml' + - '**/pnpm-workspace.yaml' + - '**/.pnpmfile.mjs' + - package.json + - remote/package.json + - .nvmrc + - extensions/copilot/.nvmrc + - build/npm/** + - build/checksums/electron.txt + - build/lib/electron.ts + - build/lib/electronVersion.ts + - product.json + - resources/darwin/*.icns + - resources/win32/code.ico + - build/.cachesalt + - .github/workflows/pr-workspace-images.yml + - .github/workflows/workspace_image/** + workflow_dispatch: + # Builds the images of a branch, for the workspace_image_branch input of the test workflows + workflow_call: + +permissions: + contents: read + +# Unlike `github.workflow`, the name of the group differs from that of a calling workflow +concurrency: + group: workspace-images-${{ github.ref }} + cancel-in-progress: false + +jobs: + linux: + name: Linux + runs-on: vscode-large-runners-ubuntu-8-core + timeout-minutes: 60 + env: + NPM_ARCH: x64 + VSCODE_ARCH: x64 + steps: + # The volume of an image exists before the checkout, so the jobs download the scripts the way + # the test jobs do + - &download-scripts + name: Download the workspace image scripts + id: image-scripts + shell: bash + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + dir="$RUNNER_TEMP/workspace-image" + mkdir -p "$dir" + echo '{ "type": "module" }' > "$dir/package.json" + files=(.nvmrc .github/workflows/workspace_image/{image.ts,vhd.ps1,Vhd.cs}) + args=() + for file in "${files[@]}"; do + args+=(-o "$dir/${file##*/}" "$GITHUB_API_URL/repos/$GITHUB_REPOSITORY/contents/$file?ref=$GITHUB_SHA") + done + curl -fsSL --retry 3 --parallel -H "Authorization: Bearer $GH_TOKEN" -H 'Accept: application/vnd.github.raw' "${args[@]}" + for file in "${files[@]}"; do + [ -s "$dir/${file##*/}" ] + done + echo "node-version=$(tr -d '[:space:]' < "$dir/.nvmrc")" >> "$GITHUB_OUTPUT" + + - &setup-node + name: Setup Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: ${{ steps.image-scripts.outputs.node-version }} + + # An ext4 volume in a sparse file, mounted at the parent folder of the workspace like in the jobs: + # without a journal or reserved blocks, and with the inode tables left to initialize, so that + # they stay zeros, which the image doesn't store + - name: Create the volume of the image + working-directory: ${{ runner.temp }} + run: | + set -euo pipefail + root="$(dirname "$GITHUB_WORKSPACE")" + truncate -s 64G "$RUNNER_TEMP/workspace-image.ext4" + mkfs.ext4 -q -F -O ^has_journal -m 0 -E "lazy_itable_init=1,root_owner=$(id -u):$(id -g)" "$RUNNER_TEMP/workspace-image.ext4" + sudo mount -o loop,noatime,noinit_itable "$RUNNER_TEMP/workspace-image.ext4" "$root" + mkdir "$GITHUB_WORKSPACE" + + - &checkout + name: Checkout microsoft/vscode + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + lfs: true + # No credentials in the .git of an image + persist-credentials: false + + # pnpm/action-setup itself instead of .github/actions/setup-pnpm: the runner reads the action.yml + # of a local action again for its post step, after the jobs unmounted the volume of the workspace + - &setup-pnpm + name: Setup pnpm + uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0 + + - &tool-folders + name: Put the pnpm store and the Playwright browsers into the image + shell: bash + run: node "$RUNNER_TEMP/workspace-image/image.ts" env + + # The same packages as in pr-node-modules.yml, for the native modules + - name: Install build tools + run: | + set -e + ./build/azure-pipelines/linux/apt-retry.sh sudo apt-get update + ./build/azure-pipelines/linux/apt-retry.sh sudo apt-get install -y pkg-config libxkbfile-dev libkrb5-dev + + - name: Install build dependencies + working-directory: build + run: | + set -e + + for i in {1..5}; do # try 5 times + pnpm install --frozen-lockfile && break + if [ $i -eq 5 ]; then + echo "pnpm install failed too many times" >&2 + exit 1 + fi + echo "pnpm install failed $i, trying again..." + done + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + # The sysroots, compilers and headers of setup-env.sh stay in .build, for the jobs whose + # dependencies changed + - name: Install dependencies + run: | + set -e + + source ./build/azure-pipelines/linux/setup-env.sh + + for i in {1..5}; do # try 5 times + pnpm install --frozen-lockfile && break + if [ $i -eq 5 ]; then + echo "pnpm install failed too many times" >&2 + exit 1 + fi + echo "pnpm install failed $i, trying again..." + done + env: + npm_config_arch: ${{ env.NPM_ARCH }} + VSCODE_ARCH: ${{ env.VSCODE_ARCH }} + ELECTRON_SKIP_BINARY_DOWNLOAD: 1 + PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1 + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + # pnpm doesn't fail when it skips an optional dependency, such as a native binary, which the + # jobs would then keep using + - &check-native-optional-deps + name: Verify native optional dependency binaries + run: node build/azure-pipelines/common/checkNativeOptionalDeps.ts + + - &setup-electron + name: Setup Electron + uses: ./.github/actions/setup-electron + with: + arch: ${{ env.VSCODE_ARCH }} + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Install Playwright Chromium + run: pnpm exec playwright install --only-shell chromium + + - &seed + name: Prepare the workspace for the image + shell: bash + run: node "$RUNNER_TEMP/workspace-image/image.ts" seed + + - name: Build the image + working-directory: ${{ runner.temp }} + run: | + set -euo pipefail + root="$(dirname "$GITHUB_WORKSPACE")" + du -sh "$root"/.[!.]* "$root"/*/node_modules "$root"/*/.build "$root"/*/.git || true + df -h "$root" + sudo umount "$root" + node "$RUNNER_TEMP/workspace-image/image.ts" pack --in "$RUNNER_TEMP/workspace-image.ext4" --out "$RUNNER_TEMP/workspace-image-linux-x64.img" + + - name: Upload the image + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + path: ${{ runner.temp }}/workspace-image-linux-x64.img + archive: false + retention-days: 2 + if-no-files-found: error + + macOS: + name: macOS + runs-on: vscode-large-runners-macos-5-core-0 + timeout-minutes: 60 + env: + NPM_ARCH: arm64 + VSCODE_ARCH: arm64 + steps: + - *download-scripts + - *setup-node + + # An APFS volume in a sparse ASIF image, mounted at the parent folder of the workspace like in the jobs + - name: Create the volume of the image + working-directory: ${{ runner.temp }} + run: | + set -euo pipefail + root="$(dirname "$GITHUB_WORKSPACE")" + diskutil image create blank --fs APFS --format ASIF --size 100G --volumeName vscode-workspace "$RUNNER_TEMP/workspace-image.asif" + diskutil image attach --nobrowse --mountPoint "$root" "$RUNNER_TEMP/workspace-image.asif" + # Spotlight leaves the volume alone + touch "$root/.metadata_never_index" + mkdir "$GITHUB_WORKSPACE" + + - *checkout + - *setup-pnpm + - *tool-folders + + - name: Install dependencies + run: | + set -e + c++ --version + xcode-select -print-path + python3 -m pip install --break-system-packages setuptools + + for i in {1..5}; do # try 5 times + pnpm install --frozen-lockfile && break + if [ $i -eq 5 ]; then + echo "pnpm install failed too many times" >&2 + exit 1 + fi + echo "pnpm install failed $i, trying again..." + done + env: + npm_config_arch: ${{ env.NPM_ARCH }} + VSCODE_ARCH: ${{ env.VSCODE_ARCH }} + ELECTRON_SKIP_BINARY_DOWNLOAD: 1 + PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1 + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # Same as in pr-darwin-test.yml + GYP_DEFINES: "kerberos_use_rtld=false" + + - *check-native-optional-deps + + - *setup-electron + + - name: Install Playwright Chromium and WebKit + run: pnpm exec playwright install --only-shell chromium webkit + + - *seed + + - name: Build the image + working-directory: ${{ runner.temp }} + run: | + set -euo pipefail + root="$(dirname "$GITHUB_WORKSPACE")" + du -sh "$root"/.[!.]* "$root"/*/node_modules "$root"/*/.build "$root"/*/.git || true + df -h "$root" + # Retried, in case Spotlight or a process that just ended still holds a file + hdiutil detach "$root" || { sleep 5; hdiutil detach -force "$root"; } + ls -la "$RUNNER_TEMP/workspace-image.asif" + node "$RUNNER_TEMP/workspace-image/image.ts" pack --in "$RUNNER_TEMP/workspace-image.asif" --out "$RUNNER_TEMP/workspace-image-darwin-arm64.img" + + - name: Upload the image + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + path: ${{ runner.temp }}/workspace-image-darwin-arm64.img + archive: false + retention-days: 2 + if-no-files-found: error + + windows: + name: Windows + runs-on: vscode-large-runners-windows-8-core + timeout-minutes: 90 + env: + NPM_ARCH: x64 + VSCODE_ARCH: x64 + steps: + - *download-scripts + - *setup-node + + # A Dev Drive in a VHDX with blocks of 1 MB, mounted at the parent folder of the workspace like + # in the jobs: pnpm links the packages of different folders with junctions, whose targets are + # absolute paths. 64 GB leave the jobs room, and less of the VHDX to ReFS's metadata than 200 GB. + - name: Create the volume of the image + shell: pwsh + working-directory: ${{ runner.temp }} + run: | + $ErrorActionPreference = 'Stop' + $workspace = $env:GITHUB_WORKSPACE + $root = Split-Path $workspace -Parent + if (Get-ChildItem -Force $workspace) { throw "$workspace is not empty" } + Remove-Item $workspace + if (Get-ChildItem -Force $root) { throw "$root holds more than the workspace" } + & "$env:RUNNER_TEMP\workspace-image\vhd.ps1" -Path "$env:RUNNER_TEMP\workspace-image.vhdx" -Create -MaximumSizeGB 64 -MountFolder $root + New-Item -ItemType Directory -Path $workspace | Out-Null + + - *checkout + - *setup-pnpm + - *tool-folders + + - name: Install dependencies + shell: pwsh + run: | + . build/azure-pipelines/win32/exec.ps1 + $ErrorActionPreference = "Stop" + + # Run preinstall script before root dependencies are installed + # so that Electron/v8 headers are patched correctly for native modules. + exec { node build/npm/preinstall.ts } + + for ($i = 1; $i -le 5; $i++) { + try { + exec { pnpm install --frozen-lockfile } + break + } + catch { + if ($i -eq 5) { + Write-Error "pnpm install failed after 5 attempts" + throw + } + Write-Host "pnpm install failed attempt $i, retrying..." + Start-Sleep -Seconds 2 + } + } + env: + npm_config_arch: ${{ env.NPM_ARCH }} + VSCODE_ARCH: ${{ env.VSCODE_ARCH }} + ELECTRON_SKIP_BINARY_DOWNLOAD: 1 + PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1 + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - *check-native-optional-deps + + - *setup-electron + + - name: Install Playwright Chromium + shell: pwsh + run: | + . build/azure-pipelines/win32/exec.ps1 + $ErrorActionPreference = "Stop" + exec { pnpm exec playwright install --only-shell chromium } + + - *seed + + - name: Build the image + shell: pwsh + working-directory: ${{ runner.temp }} + run: | + $ErrorActionPreference = 'Stop' + $root = Split-Path $env:GITHUB_WORKSPACE -Parent + fsutil volume diskfree $root | Out-Host + & "$env:RUNNER_TEMP\workspace-image\vhd.ps1" -Path "$env:RUNNER_TEMP\workspace-image.vhdx" -MountFolder $root -Detach + # The next steps start in the workspace + New-Item -ItemType Directory -Path $env:GITHUB_WORKSPACE -Force | Out-Null + Get-Item "$env:RUNNER_TEMP\workspace-image.vhdx" | Format-List Name, Length + node "$env:RUNNER_TEMP\workspace-image\image.ts" pack --in "$env:RUNNER_TEMP\workspace-image.vhdx" --out "$env:RUNNER_TEMP\workspace-image-win32-x64.img" + if ($LASTEXITCODE -ne 0) { throw "image.ts pack exited with $LASTEXITCODE" } + + - name: Upload the image + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + path: ${{ runner.temp }}/workspace-image-win32-x64.img + archive: false + retention-days: 2 + if-no-files-found: error diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 3e0c7718ce5958..57aa3ad849cb0e 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -491,6 +491,11 @@ jobs: name: Linux needs: changes if: ${{ !cancelled() }} + # actions: read finds and downloads the workspace image (see .github/workflows/workspace_image/README.md) + permissions: + contents: read + pull-requests: read + actions: read uses: ./.github/workflows/pr-linux-test.yml with: electron_unit_affected: ${{ needs.changes.result != 'success' || needs.changes.outputs.unit-tests == 'true' }} @@ -508,6 +513,11 @@ jobs: name: macOS needs: changes if: ${{ !cancelled() }} + # actions: read finds and downloads the workspace image (see .github/workflows/workspace_image/README.md) + permissions: + contents: read + pull-requests: read + actions: read uses: ./.github/workflows/pr-darwin-test.yml with: electron_unit_affected: ${{ needs.changes.result != 'success' || needs.changes.outputs.selected-unit-tests == 'true' }} @@ -528,6 +538,11 @@ jobs: name: Windows needs: changes if: ${{ !cancelled() }} + # actions: read finds and downloads the workspace image (see .github/workflows/workspace_image/README.md) + permissions: + contents: read + pull-requests: read + actions: read uses: ./.github/workflows/pr-win32-test.yml with: electron_unit_affected: ${{ needs.changes.result != 'success' || needs.changes.outputs.selected-unit-tests == 'true' }} diff --git a/.github/workflows/workspace-images-validation.yml b/.github/workflows/workspace-images-validation.yml new file mode 100644 index 00000000000000..d6bb50d250f401 --- /dev/null +++ b/.github/workflows/workspace-images-validation.yml @@ -0,0 +1,230 @@ +name: Workspace images (validation) + +# Temporary, for the draft pull request: builds the workspace images of this branch, runs every test +# job of pull requests with them, and brings each image to a dependency change. Remove it, and the +# workflow_call trigger of pr-workspace-images.yml if unused, before merging. +on: + push: + branches: + - agents/workspace-images + workflow_dispatch: + +permissions: + contents: read + pull-requests: read + actions: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + images: + name: Images + uses: ./.github/workflows/pr-workspace-images.yml + + linux-tests: + name: Linux + needs: images + if: ${{ !cancelled() }} + uses: ./.github/workflows/pr-linux-test.yml + with: + workspace_image_branch: ${{ github.ref_name }} + electron_unit_affected: true + electron_affected: true + agent_host_e2e_affected: true + electron_smoke_affected: true + browser_unit_affected: true + browser_affected: true + remote_affected: true + + macos-tests: + name: macOS + needs: images + if: ${{ !cancelled() }} + uses: ./.github/workflows/pr-darwin-test.yml + with: + workspace_image_branch: ${{ github.ref_name }} + electron_unit_affected: true + electron_affected: true + electron_smoke_affected: true + browser_unit_affected: true + browser_affected: true + remote_affected: true + node_integration_tests: true + agent_host_e2e_tests: true + + windows-tests: + name: Windows + needs: images + if: ${{ !cancelled() }} + uses: ./.github/workflows/pr-win32-test.yml + with: + workspace_image_branch: ${{ github.ref_name }} + electron_unit_affected: true + electron_affected: true + agent_host_e2e_affected: true + electron_smoke_affected: true + browser_unit_affected: true + browser_affected: true + remote_affected: true + node_integration_tests: true + + # Brings an image to the commit with a dependency change in two install roots, the workspace and + # remote/web, the way the test jobs do, and checks that it installed them + dependency-change: + name: 'Dependency change: ${{ matrix.os }}' + needs: images + if: ${{ !cancelled() }} + runs-on: ${{ matrix.runner }} + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + include: + - { os: Linux, runner: vscode-large-runners-ubuntu-8-core, image: workspace-image-linux-x64.img, arch: x64 } + - { os: macOS, runner: vscode-large-runners-macos-5-core-0, image: workspace-image-darwin-arm64.img, arch: arm64 } + - { os: Windows, runner: vscode-large-runners-windows-8-core, image: workspace-image-win32-x64.img, arch: x64 } + env: + NPM_ARCH: ${{ matrix.arch }} + VSCODE_ARCH: ${{ matrix.arch }} + steps: + - name: Download the workspace image scripts + id: image-scripts + shell: bash + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + dir="$RUNNER_TEMP/workspace-image" + mkdir -p "$dir" + echo '{ "type": "module" }' > "$dir/package.json" + files=(.nvmrc .github/workflows/workspace_image/{image.ts,vhd.ps1,Vhd.cs}) + args=() + for file in "${files[@]}"; do + args+=(-o "$dir/${file##*/}" "$GITHUB_API_URL/repos/$GITHUB_REPOSITORY/contents/$file?ref=$GITHUB_SHA") + done + curl -fsSL --retry 3 --parallel -H "Authorization: Bearer $GH_TOKEN" -H 'Accept: application/vnd.github.raw' "${args[@]}" + echo "node-version=$(tr -d '[:space:]' < "$dir/.nvmrc")" >> "$GITHUB_OUTPUT" + + - name: Setup Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: ${{ steps.image-scripts.outputs.node-version }} + + - name: Restore the workspace image + id: image + shell: bash + working-directory: ${{ runner.temp }} + run: | + set -euo pipefail + node "$RUNNER_TEMP/workspace-image/image.ts" restore --name "${{ matrix.image }}" --branch "$GITHUB_REF_NAME" + grep -q '^used=true' "$GITHUB_OUTPUT" + env: + GH_TOKEN: ${{ github.token }} + + - name: Checkout microsoft/vscode + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + lfs: true + clean: false + + - name: Downgrade @vscode/codicons in the workspace and in remote/web, as a pull request would + shell: bash + run: | + node -e ' + const fs = require("fs"); + const integrity = ["sha512-0McyVlyRjenut3PBwULxuaC5YoKPF8qkNHf9DhS6UOXUmLr31Ga6vECnNx70SSIZnI4ULLOEktcIkRqiwFvkbg==", "sha512-HhX6VUa84nR9C9ceyiZvR1lRCOc4dZC1vSwnyPWiqIpN+06x+KDaGGn0WFmFLG0APariLhFPlBUljep1cIWk/Q=="]; + for (const file of ["package.json", "pnpm-lock.yaml", "remote/web/package.json", "remote/web/pnpm-lock.yaml"]) { + const before = fs.readFileSync(file, "utf8"); + const after = before.replaceAll("^0.0.46-49", "0.0.46-48").replaceAll("0.0.46-49", "0.0.46-48").replaceAll(integrity[0], integrity[1]); + if (after === before) { throw new Error(`${file} did not change`); } + fs.writeFileSync(file, after); + }' + git status --short + + - name: Compare the dependencies with the workspace image + id: image-deps + shell: bash + run: | + set -euo pipefail + node "$RUNNER_TEMP/workspace-image/image.ts" deps + grep -q '^current=false' "$GITHUB_OUTPUT" + + - name: Setup pnpm + uses: ./.github/actions/setup-pnpm + + - name: Install build dependencies + if: runner.os == 'Linux' + working-directory: build + run: pnpm install --frozen-lockfile + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Install dependencies + if: runner.os == 'Linux' + run: | + set -e + source ./build/azure-pipelines/linux/setup-env.sh + pnpm install --frozen-lockfile + env: + npm_config_arch: ${{ env.NPM_ARCH }} + VSCODE_ARCH: ${{ env.VSCODE_ARCH }} + ELECTRON_SKIP_BINARY_DOWNLOAD: 1 + PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1 + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Install dependencies + if: runner.os == 'macOS' + run: | + set -e + python3 -m pip install --break-system-packages setuptools + pnpm install --frozen-lockfile + env: + npm_config_arch: ${{ env.NPM_ARCH }} + VSCODE_ARCH: ${{ env.VSCODE_ARCH }} + ELECTRON_SKIP_BINARY_DOWNLOAD: 1 + PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1 + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GYP_DEFINES: "kerberos_use_rtld=false" + + - name: Install dependencies + if: runner.os == 'Windows' + shell: pwsh + run: | + . build/azure-pipelines/win32/exec.ps1 + $ErrorActionPreference = "Stop" + exec { node build/npm/preinstall.ts } + exec { pnpm install --frozen-lockfile } + env: + npm_config_arch: ${{ env.NPM_ARCH }} + VSCODE_ARCH: ${{ env.VSCODE_ARCH }} + ELECTRON_SKIP_BINARY_DOWNLOAD: 1 + PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1 + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Check the installed packages + shell: bash + run: | + set -euo pipefail + for folder in . remote/web; do + version=$(node -p "require('./$folder/node_modules/@vscode/codicons/package.json').version") + echo "$folder: @vscode/codicons $version" + [ "$version" = 0.0.46-48 ] + done + node "$RUNNER_TEMP/workspace-image/image.ts" deps + grep -q '^current=true' "$GITHUB_OUTPUT" + + - name: Install again, as a job whose dependencies did not change + shell: bash + run: time pnpm install --frozen-lockfile + + - name: Setup Electron + uses: ./.github/actions/setup-electron + with: + arch: ${{ env.VSCODE_ARCH }} + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Transpile client and extensions + run: pnpm run gulp transpile-client-esbuild transpile-extensions diff --git a/.github/workflows/workspace_image/README.md b/.github/workflows/workspace_image/README.md new file mode 100644 index 00000000000000..990fa3f43924cc --- /dev/null +++ b/.github/workflows/workspace_image/README.md @@ -0,0 +1,35 @@ +# Workspace images + +The test jobs of pull requests ([pr-linux-test.yml](../pr-linux-test.yml), [pr-darwin-test.yml](../pr-darwin-test.yml) and [pr-win32-test.yml](../pr-win32-test.yml)) start from a disk image of a workspace of `main` instead of an empty folder: its dependencies, Electron and the Playwright browsers are installed, and its `.git` holds the commit it was built at. A job mounts the image, checks out its own commit, and installs only what changed since, which for most pull requests is nothing. + +[pr-workspace-images.yml](../pr-workspace-images.yml) builds an image for each platform on the runners of the jobs when one of its inputs changes on `main`: those of the install, of the native builds (`NATIVE_BUILD_INPUTS` in `image.ts`) and of the prepared Electron. It doesn't build them for other changes, as the checkout of a job fetches and writes only what changed since the commit of its image. The images are kept for 2 days, so the jobs install everything as before when no input changed for longer. [image.ts](image.ts) restores, checks and builds them; it has no dependencies, as the jobs run it before they check out the repository. + +## What a job does + +1. **Downloads the scripts** of its commit from the API (`image.ts`, and on Windows `vhd.ps1` and `Vhd.cs`), and `.nvmrc` for the Node.js version. +2. **Restores the image** (`image.ts restore`): finds the newest image of `main`, downloads it with parallel range requests, and mounts it at the parent folder of the workspace, so that the workspace keeps its path. Without an image, or on any error, it warns and the job installs everything as before. The job also doesn't use an image when the inputs of the base key of the `node_modules` caches (`computeNodeModulesBaseCacheKey` in `build/azure-pipelines/common/cacheKeys.ts`: the salt of the CI caches, the pnpmfiles, the `nativeBuild` targets and `packageManager` of `package.json`, the Node.js versions and the pnpm settings of the install roots, mirrored in `NATIVE_BUILD_INPUTS` of `image.ts`) differ between the commit of the image and its own, which the restore compares through the API before it downloads anything: installing on top of an image wouldn't build its native modules again, for example after an Electron update. +3. **Checks out its commit** with `clean: false`, which keeps the untracked files of the image and reuses its checkout: the shallow fetch sends the tag at the commit of the image, and downloads only what changed since, and git writes only the files that changed, as it compares their sizes and modification times, which the image keeps. +4. **Compares the dependencies** (`image.ts deps`) with the install state that `build/npm/postinstall.ts` saved in the image (see `build/npm/installStateHash.ts`). When an input of the install changed, the job runs its usual install steps on the `node_modules` of the image, and pnpm installs only what changed. +5. **Keeps the prepared Electron** when it was prepared from the same inputs (see [setup-electron](../../actions/setup-electron/action.yml)), and finds the Playwright browsers in the image (`PLAYWRIGHT_BROWSERS_PATH`). + +## The images + +The workspace of an image is at the path of the workspaces of the jobs, because pnpm links packages of different folders with junctions on Windows, whose targets are absolute paths, and records its store in `node_modules/.modules.yaml`: with another store, pnpm installs every package again. The store (`pnpm_config_store_dir`) and the Playwright browsers are beside the workspace, in the image. The jobs don't need the content of the store: with an empty store at the same path, pnpm only downloads the packages that changed. On Windows, pnpm hard links the packages from the store, as its clones on ReFS store them again. + +| Platform | Image | Restore | +| -------- | ----- | ------- | +| Linux | ext4 volume without a journal in a sparse file | Attached to a loop device while still empty, recreated from chunks of zstd, then mounted with `barrier=0`, while the kernel writes the image to the disk | +| macOS | APFS volume in a sparse ASIF image | Recreated from chunks of zstd, then attached | +| Windows | Dev Drive in a VHDX with blocks of 1 MB | Recreated from chunks of zstd into a temporary file, which Windows keeps in memory, then attached through the file system cache with the virtual disk API ([Vhd.cs](Vhd.cs)) | + +All three are writable volumes. A squashfs under an overlay, which Linux mounts without writing it, took seconds to look up the files of a checkout or `node_modules` for the first time, as squashfs reads its metadata past the caches of the kernel. + +The chunks of 32 MB download and decompress in parallel, and the restore writes them in order as they arrive, without the pages of zeros where the file can be sparse. On Windows, the disk sets the pace, at 250-650 MB/s, as a VHDX can be neither sparse nor written later. The first PowerShell of a job takes seconds to start, so `vhd.ps1` starts and compiles the virtual disk API while the image downloads into the file that `image.ts` created. On Linux, attaching a file to a loop device waits for the kernel to write the file to the disk, so the restore attaches the empty file while the image downloads, and drops what udev read from it before it mounts the volume. With `barrier=0`, an fsync in the volume doesn't wait for the rest of the image to reach the disk either. Images keep everything of the workspace: the checkout of their commit with HEAD detached (`image.ts seed`), the files that pnpm installed, and the `.build` folder (Electron, and on Linux the sysroots and compilers of `setup-env.sh`). + +## Trust + +A job only uses images of runs of this repository for pushes to `main` and manual dispatches, as any pull request could upload an artifact of the same name. The `.git` of an image holds no credentials. The test jobs need `actions: read` to find and download the artifacts. + +## Testing changes + +The test workflows take a `workspace_image_branch` input, which is `main` unless a workflow that calls them builds the images of another branch: `pr-workspace-images.yml` can be called with `workflow_call`. diff --git a/.github/workflows/workspace_image/Vhd.cs b/.github/workflows/workspace_image/Vhd.cs new file mode 100644 index 00000000000000..3721e87d0324be --- /dev/null +++ b/.github/workflows/workspace_image/Vhd.cs @@ -0,0 +1,239 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// The virtual disk API for vhd.ps1: it attaches a VHDX without diskpart, the Virtual Disk Service or +// the storage cmdlets, which take seconds to start on a new runner, and it creates a VHDX with blocks +// of 1 MB, which diskpart can't (it always uses 32 MB, which the VHDX allocates in full). vhd.ps1 +// compiles it with the C# compiler of the .NET Framework, which takes about a second, unlike Add-Type +// of PowerShell 7 (over 10 seconds on a new runner), so it sticks to C# 5. + +using System; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; + +public static class WorkspaceImageVhd +{ + [StructLayout(LayoutKind.Sequential)] + private struct VirtualStorageType + { + public uint DeviceId; + public Guid VendorId; + } + + // OPEN_VIRTUAL_DISK_PARAMETERS of version 1, in the size of the later versions + [StructLayout(LayoutKind.Explicit, Size = 48)] + private struct OpenParameters + { + [FieldOffset(0)] public uint Version; + [FieldOffset(4)] public uint RWDepth; + } + + [StructLayout(LayoutKind.Sequential)] + private struct AttachParameters + { + public uint Version; + public uint Reserved; + } + + // CREATE_VIRTUAL_DISK_PARAMETERS of version 2, whose union starts at offset 8. Padded beyond the + // fields of version 2, in case the API reads the size of a later version. + [StructLayout(LayoutKind.Explicit, Size = 256)] + private struct CreateParameters + { + [FieldOffset(0)] public uint Version; + [FieldOffset(8)] public Guid UniqueId; + [FieldOffset(24)] public ulong MaximumSize; + [FieldOffset(32)] public uint BlockSizeInBytes; + [FieldOffset(36)] public uint SectorSizeInBytes; + [FieldOffset(40)] public uint PhysicalSectorSizeInBytes; + } + + [DllImport("virtdisk.dll", CharSet = CharSet.Unicode)] + private static extern uint CreateVirtualDisk(ref VirtualStorageType type, string path, uint access, IntPtr securityDescriptor, uint flags, uint providerSpecificFlags, ref CreateParameters parameters, IntPtr overlapped, out IntPtr handle); + + [DllImport("virtdisk.dll", CharSet = CharSet.Unicode)] + private static extern uint OpenVirtualDisk(ref VirtualStorageType type, string path, uint access, uint flags, ref OpenParameters parameters, out IntPtr handle); + + [DllImport("virtdisk.dll", CharSet = CharSet.Unicode)] + private static extern uint AttachVirtualDisk(IntPtr handle, IntPtr securityDescriptor, uint flags, uint providerSpecificFlags, ref AttachParameters parameters, IntPtr overlapped); + + [DllImport("virtdisk.dll", CharSet = CharSet.Unicode)] + private static extern uint GetVirtualDiskPhysicalPath(IntPtr handle, ref uint size, StringBuilder path); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool CloseHandle(IntPtr handle); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern IntPtr FindFirstVolume(StringBuilder name, uint length); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern bool FindNextVolume(IntPtr handle, StringBuilder name, uint length); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool FindVolumeClose(IntPtr handle); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern IntPtr CreateFile(string name, uint access, uint share, IntPtr security, uint disposition, uint flags, IntPtr template); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool DeviceIoControl(IntPtr handle, uint code, IntPtr input, uint inputSize, IntPtr output, uint outputSize, out uint returned, IntPtr overlapped); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern bool SetVolumeMountPoint(string mountPoint, string volumeName); + + private static readonly IntPtr Invalid = new IntPtr(-1); + + private static VirtualStorageType Vhdx() + { + VirtualStorageType type = new VirtualStorageType(); + // VIRTUAL_STORAGE_TYPE_DEVICE_VHDX of VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT + type.DeviceId = 3; + type.VendorId = new Guid("EC984AEC-A0F9-47e9-901F-71415A66345B"); + return type; + } + + /// Creates an empty dynamic VHDX with the given block size. + public static void Create(string path, ulong maximumSize, uint blockSize) + { + VirtualStorageType type = Vhdx(); + CreateParameters parameters = new CreateParameters(); + parameters.Version = 2; + parameters.UniqueId = Guid.NewGuid(); + parameters.MaximumSize = maximumSize; + parameters.BlockSizeInBytes = blockSize; + parameters.SectorSizeInBytes = 512; + parameters.PhysicalSectorSizeInBytes = 4096; + IntPtr handle; + // VIRTUAL_DISK_ACCESS_NONE and CREATE_VIRTUAL_DISK_FLAG_NONE, which version 2 requires for a dynamic VHDX + uint result = CreateVirtualDisk(ref type, path, 0, IntPtr.Zero, 0, 0, ref parameters, IntPtr.Zero, out handle); + if (result != 0) + { + throw new Exception("CreateVirtualDisk failed with error " + result); + } + CloseHandle(handle); + } + + /// + /// Opens the VHDX with version 1 of the open parameters, the only one that takes + /// OPEN_VIRTUAL_DISK_FLAG_CACHED_IO, then attaches it for good, without a drive letter. Returns the + /// error of OpenVirtualDisk, 0 when it attached. + /// + public static uint TryAttach(string path, uint openFlags, out int disk) + { + disk = -1; + VirtualStorageType type = Vhdx(); + OpenParameters open = new OpenParameters(); + open.Version = 1; + open.RWDepth = 1; + IntPtr handle; + // VIRTUAL_DISK_ACCESS_ALL + uint result = OpenVirtualDisk(ref type, path, 0x003f0000, openFlags, ref open, out handle); + if (result != 0) + { + return result; + } + try + { + AttachParameters attach = new AttachParameters(); + attach.Version = 1; + // ATTACH_VIRTUAL_DISK_FLAG_NO_DRIVE_LETTER | ATTACH_VIRTUAL_DISK_FLAG_PERMANENT_LIFETIME + result = AttachVirtualDisk(handle, IntPtr.Zero, 0x2 | 0x4, 0, ref attach, IntPtr.Zero); + if (result != 0) + { + throw new Exception("AttachVirtualDisk failed with error " + result); + } + uint size = 1024; + StringBuilder physical = new StringBuilder((int)size); + result = GetVirtualDiskPhysicalPath(handle, ref size, physical); + if (result != 0) + { + throw new Exception("GetVirtualDiskPhysicalPath failed with error " + result); + } + string text = physical.ToString(); + disk = int.Parse(text.Substring(text.LastIndexOf("PhysicalDrive", StringComparison.OrdinalIgnoreCase) + "PhysicalDrive".Length)); + return 0; + } + finally + { + CloseHandle(handle); + } + } + + /// Waits for the volume of the disk and returns its \\?\Volume{GUID}\ path. + public static string WaitForVolume(int disk, int timeoutMilliseconds) + { + DateTime deadline = DateTime.UtcNow.AddMilliseconds(timeoutMilliseconds); + while (true) + { + string volume = FindVolume(disk); + if (volume != null) + { + return volume; + } + if (DateTime.UtcNow > deadline) + { + throw new TimeoutException("No volume on disk " + disk); + } + Thread.Sleep(25); + } + } + + private static string FindVolume(int disk) + { + StringBuilder name = new StringBuilder(1024); + IntPtr find = FindFirstVolume(name, 1024); + if (find == Invalid) + { + return null; + } + try + { + do + { + string volume = name.ToString(); + IntPtr handle = CreateFile(volume.TrimEnd('\\'), 0, 3, IntPtr.Zero, 3, 0, IntPtr.Zero); + if (handle == Invalid) + { + continue; + } + IntPtr buffer = Marshal.AllocHGlobal(1024); + try + { + uint returned; + // IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS returns VOLUME_DISK_EXTENTS, whose DISK_EXTENTs of 24 bytes start at offset 8 + if (DeviceIoControl(handle, 0x00560000, IntPtr.Zero, 0, buffer, 1024, out returned, IntPtr.Zero)) + { + int count = Marshal.ReadInt32(buffer); + for (int i = 0; i < count; i++) + { + if (Marshal.ReadInt32(buffer, 8 + i * 24) == disk) + { + return volume; + } + } + } + } + finally + { + Marshal.FreeHGlobal(buffer); + CloseHandle(handle); + } + } while (FindNextVolume(find, name, 1024)); + } + finally + { + FindVolumeClose(find); + } + return null; + } + + /// Mounts the volume at an empty folder, whose path ends with a backslash. + public static void Mount(string folder, string volume) + { + if (!SetVolumeMountPoint(folder, volume)) + { + throw new Exception("SetVolumeMountPoint failed with error " + Marshal.GetLastWin32Error()); + } + } +} diff --git a/.github/workflows/workspace_image/image.ts b/.github/workflows/workspace_image/image.ts new file mode 100644 index 00000000000000..6e33982ef7c77f --- /dev/null +++ b/.github/workflows/workspace_image/image.ts @@ -0,0 +1,915 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +// Workspace images: a disk image of a workspace of main with its dependencies, Electron and the +// Playwright browsers installed, which a test job mounts instead of installing them (see README.md). +// Dependency-free, as the jobs download it from the API and run it before they check out. +// +// node image.ts restore --name NAME [--branch main] [--connections 32] +// Mounts the newest image NAME of a branch at the parent folder of the empty workspace, where +// actions/checkout then reuses its .git. Sets the output `used` to 'true' when it did, and warns +// instead of failing otherwise, as the job can still install everything. Skips an image whose +// commit has other native build inputs (NATIVE_BUILD_INPUTS) than the commit of the job. +// node image.ts deps +// After the checkout, compares the install state that the image saved with the checkout, and +// sets the output `current` to 'true' when no dependency changed. +// node image.ts env +// Points the pnpm store and the Playwright browsers into the image, for the next steps. +// node image.ts seed +// Prepares the checkout of an image for the checkouts of the jobs. +// node image.ts pack --in FILE --out FILE [--level 9] [--chunk-mb 32] +// Compresses a disk image in chunks that `restore` downloads and decompresses in parallel. +// +// `restore` reads the API with the token in GH_TOKEN, which needs `actions: read`. + +import { execFile, spawn, spawnSync, type SpawnSyncOptions } from 'child_process'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { pathToFileURL } from 'url'; +import { promisify } from 'util'; +import * as zlib from 'zlib'; + +// Decompression runs in the thread pool of libuv, next to the file writes +process.env.UV_THREADPOOL_SIZE ??= String(Math.max(16, os.availableParallelism() * 2)); + +/** The events of the workflow runs that build images: never a pull request */ +const TRUSTED_EVENTS = new Set(['push', 'workflow_dispatch']); +/** At the root of an image: the commit and the path of its workspace */ +const METADATA_FILE = '.workspace-image.json'; +/** The tag at the commit of an image, which the shallow fetch of actions/checkout sends, so that it downloads only what changed */ +const SEED_TAG = 'workspace-image'; +/** _O_SHORT_LIVED of the C runtime of Windows, which Node.js doesn't name */ +const O_SHORT_LIVED = 0x1000; +/** + * The inputs of computeNodeModulesBaseCacheKey in build/azure-pipelines/common/cacheKeys.ts, without + * the roots of the distro, which build/lib/test/workspaceImage.test.ts compares with: the files, and + * the fields of `package.json` files. They decide how the dependencies are built, and installing on + * top of an image doesn't build its native modules again, so a job only uses an image whose commit + * has the same inputs as its own. + */ +export const NATIVE_BUILD_INPUTS: { readonly files: readonly string[]; readonly packageJsonFields: Readonly> } = { + files: [ + 'build/.cachesalt', + '.pnpmfile.mjs', + 'build/.pnpmfile.mjs', + 'remote/.pnpmfile.mjs', + 'build/npm/pnpm/nativeBuildEnv.ts', + '.nvmrc', + 'extensions/copilot/.nvmrc', + 'pnpm-workspace.yaml', + 'build/pnpm-workspace.yaml', + 'remote/pnpm-workspace.yaml', + 'remote/web/pnpm-workspace.yaml', + 'extensions/copilot/pnpm-workspace.yaml', + ], + packageJsonFields: { + 'package.json': ['nativeBuild', 'packageManager'], + 'remote/package.json': ['nativeBuild'], + }, +}; + +const started = performance.now(); + +function log(message: string): void { + console.log(`${((performance.now() - started) / 1000).toFixed(1).padStart(6)}s ${message}`); +} + +type Args = Map; + +function parseArgs(argv: readonly string[]): Args { + const args: Args = new Map(); + for (let i = 0; i < argv.length; i += 2) { + args.set(argv[i].replace(/^--/, ''), argv[i + 1]); + } + return args; +} + +function required(args: Args, name: string): string { + const value = args.get(name); + if (!value) { + throw new Error(`Missing --${name}`); + } + return value; +} + +function setOutput(name: string, value: string): void { + console.log(`${name}=${value}`); + if (process.env.GITHUB_OUTPUT) { + fs.appendFileSync(process.env.GITHUB_OUTPUT, `${name}=${value}\n`); + } +} + +function setEnv(values: Record): void { + for (const [name, value] of Object.entries(values)) { + console.log(`${name}=${value}`); + if (process.env.GITHUB_ENV) { + fs.appendFileSync(process.env.GITHUB_ENV, `${name}=${value}\n`); + } + } +} + +function summary(line: string): void { + if (process.env.GITHUB_STEP_SUMMARY) { + fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, `${line}\n`); + } +} + +function run(command: string, args: readonly string[], options: SpawnSyncOptions = {}): string { + // `git ls-files` lists over 1 MB, the default + const result = spawnSync(command, args, { stdio: 'inherit', encoding: 'utf8', maxBuffer: 1024 * 1024 * 1024, ...options }); + if (result.error) { + throw result.error; + } + if (result.status !== 0) { + throw new Error(`${command} ${args.join(' ')} exited with ${result.status}`); + } + return typeof result.stdout === 'string' ? result.stdout : ''; +} + +function workspace(): string { + const folder = process.env.GITHUB_WORKSPACE; + if (!folder) { + throw new Error('No GITHUB_WORKSPACE'); + } + return path.resolve(folder); +} + +/** The folder where a job mounts an image: the parent folder of its workspace, so that the workspace keeps its path */ +function imageRoot(): string { + return path.dirname(workspace()); +} + +/** The folders of the tools in an image, outside of the workspace, so that the checkout of a job doesn't see them */ +function toolFolders(root: string): Record { + return { + // pnpm records its store in node_modules/.modules.yaml, and installs everything again with another one + pnpm_config_store_dir: path.join(root, '.pnpm-store'), + PLAYWRIGHT_BROWSERS_PATH: path.join(root, '.playwright'), + // The clones of pnpm on ReFS store the packages again, unlike the hard links + ...(process.platform === 'win32' ? { pnpm_config_package_import_method: 'hardlink' } : {}), + }; +} + +//#region downloads + +function githubHeaders(): Record { + const token = process.env.GH_TOKEN; + if (!token) { + throw new Error('No GH_TOKEN'); + } + return { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' }; +} + +function repositoryUrl(): string { + return `${process.env.GITHUB_API_URL ?? 'https://api.github.com'}/repos/${process.env.GITHUB_REPOSITORY}`; +} + +async function api(route: string): Promise { + const response = await fetch(`${repositoryUrl()}/${route}`, { headers: githubHeaders() }); + if (!response.ok) { + throw new Error(`GET ${route}: HTTP ${response.status}`); + } + return await response.json() as T; +} + +interface Artifact { + readonly id: number; + readonly name: string; + readonly size_in_bytes: number; + readonly created_at: string; + readonly expired: boolean; + readonly workflow_run?: { readonly id: number; readonly repository_id: number; readonly head_repository_id: number; readonly head_branch: string; readonly head_sha: string }; +} + +/** + * The newest image of a branch. Only runs of this repository for pushes or manual dispatches build + * images, as a pull request could upload an artifact of the same name. + */ +async function locate(name: string, branch: string): Promise { + const { artifacts } = await api<{ artifacts: Artifact[] }>(`actions/artifacts?name=${encodeURIComponent(name)}&per_page=50`); + const candidates = artifacts + .filter(artifact => !artifact.expired && artifact.workflow_run?.head_branch === branch && artifact.workflow_run.head_repository_id === artifact.workflow_run.repository_id) + .sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at)); + for (const artifact of candidates) { + const workflowRun = await api<{ event: string }>(`actions/runs/${artifact.workflow_run!.id}`); + if (TRUSTED_EVENTS.has(workflowRun.event)) { + return artifact; + } + log(`Skipped artifact ${artifact.id} of a ${workflowRun.event} run`); + } + throw new Error(`No ${name} of ${branch}`); +} + +interface GitObject { + readonly oid: string; + readonly text?: string | null; + readonly isTruncated?: boolean; +} + +/** The git objects of files in commits, in one request, with the text of the files in `texts`: undefined for a missing file */ +async function gitObjects(commits: readonly string[], files: readonly string[], texts: ReadonlySet): Promise<(GitObject | undefined)[][]> { + const [owner, name] = (process.env.GITHUB_REPOSITORY ?? '').split('/'); + const fields = commits.flatMap((commit, i) => files.map((file, j) => `f${i}_${j}: object(expression: ${JSON.stringify(`${commit}:${file}`)}) { oid${texts.has(file) ? ' ... on Blob { text isTruncated }' : ''} }`)); + const response = await fetch(process.env.GITHUB_GRAPHQL_URL ?? 'https://api.github.com/graphql', { + method: 'POST', + headers: { ...githubHeaders(), 'Content-Type': 'application/json' }, + body: JSON.stringify({ query: `query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { ${fields.join(' ')} } }`, variables: { owner, name } }), + }); + if (!response.ok) { + throw new Error(`POST graphql: HTTP ${response.status}`); + } + const { data, errors } = await response.json() as { data?: { repository: Record }; errors?: { message: string }[] }; + if (!data?.repository || errors?.length) { + throw new Error(`POST graphql: ${errors?.map(error => error.message).join('; ') ?? 'no repository'}`); + } + return commits.map((_, i) => files.map((_, j) => data.repository[`f${i}_${j}`] ?? undefined)); +} + +/** The JSON of a field of a `package.json` file, as computeNodeModulesBaseCacheKey hashes it */ +function packageJsonField(file: string, object: GitObject | undefined, field: string): string { + if (!object) { + return 'null'; + } + if (typeof object.text !== 'string' || object.isTruncated) { + throw new Error(`Could not read ${file}`); + } + return JSON.stringify(JSON.parse(object.text)[field] ?? null); +} + +/** + * Throws when the commit of the job has other native build inputs than the commit of the image, so + * that the job installs without the image, as installing on top of it wouldn't build its native + * modules again. For example, it would keep modules and the libc++ of Linux built for an older Electron. + */ +async function checkNativeBuildInputs(imageCommit: string): Promise { + const jobCommit = process.env.GITHUB_SHA; + if (!jobCommit) { + throw new Error('No GITHUB_SHA'); + } + const { files, packageJsonFields } = NATIVE_BUILD_INPUTS; + const packageJsonFiles = Object.keys(packageJsonFields); + const [image, job] = await gitObjects([imageCommit, jobCommit], [...files, ...packageJsonFiles], new Set(packageJsonFiles)); + const changed = files.filter((_, i) => image[i]?.oid !== job[i]?.oid); + packageJsonFiles.forEach((file, j) => { + const i = files.length + j; + if (image[i]?.oid !== job[i]?.oid) { + changed.push(...packageJsonFields[file].filter(field => packageJsonField(file, image[i], field) !== packageJsonField(file, job[i], field)).map(field => `${field} of ${file}`)); + } + }); + if (changed.length) { + throw new Error(`The native modules of the image are built from other inputs than those of ${jobCommit}: ${changed.join(', ')}`); + } + log(`checked the ${files.length} files and ${Object.values(packageJsonFields).flat().length} package.json fields of the native build inputs`); +} + +/** The signed URL of an artifact, which expires after a minute */ +async function artifactUrl(id: number): Promise { + const response = await fetch(`${repositoryUrl()}/actions/artifacts/${id}/zip`, { headers: githubHeaders(), redirect: 'manual' }); + await response.body?.cancel(); + const location = response.headers.get('location'); + if (!location) { + throw new Error(`No download URL for artifact ${id}: HTTP ${response.status}`); + } + return location; +} + +async function fetchRange(url: string, from: number, to: number): Promise { + for (let attempt = 1; ; attempt++) { + let status = 0; + try { + const response = await fetch(url, { headers: { Range: `bytes=${from}-${to}` } }); + status = response.status; + if (status !== 206) { + await response.body?.cancel(); + throw new Error(`HTTP ${status}`); + } + const data = Buffer.from(await response.arrayBuffer()); + if (data.length !== to - from + 1) { + throw new Error(`${data.length} bytes instead of ${to - from + 1}`); + } + return data; + } catch (err) { + // An expired URL needs a new one + if (status === 403 || attempt === 5) { + throw err; + } + await new Promise(resolve => setTimeout(resolve, 250 * attempt)); + } + } +} + +/** Where the data of a file is in a download: the file itself, or the entry of a zip that stores it uncompressed */ +interface Located { + readonly start: number; + readonly size: number; +} + +/** + * The data of an artifact: the file itself, which upload-artifact uploads without a zip with + * `archive: false`, or else the stored entry of its zip. + */ +async function locateArtifactData(url: string): Promise { + const response = await fetch(url, { headers: { Range: 'bytes=0-3' } }); + const range = response.headers.get('content-range'); + const head = Buffer.from(await response.arrayBuffer()); + if (response.status !== 206 || !range) { + throw new Error(`No range support: HTTP ${response.status}`); + } + const total = Number(range.split('/')[1]); + return head.readUInt32LE(0) === 0x04034b50 ? await locateZipEntry(url, total) : { start: 0, size: total }; +} + +/** Finds the data of the first entry of a zip that stores it uncompressed, with a few small range requests */ +async function locateZipEntry(url: string, total: number): Promise { + const tail = await fetchRange(url, Math.max(0, total - 65_600), total - 1); + let eocd = -1; + for (let i = tail.length - 22; i >= 0 && eocd === -1; i--) { + if (tail.readUInt32LE(i) === 0x06054b50) { + eocd = i; + } + } + if (eocd === -1) { + throw new Error('No end of central directory record'); + } + let directorySize = tail.readUInt32LE(eocd + 12); + let directoryOffset = tail.readUInt32LE(eocd + 16); + if (directoryOffset === 0xffffffff || directorySize === 0xffffffff) { + const locator = eocd - 20; + if (tail.readUInt32LE(locator) !== 0x07064b50) { + throw new Error('No zip64 end of central directory locator'); + } + const recordOffset = Number(tail.readBigUInt64LE(locator + 8)); + const record = await fetchRange(url, recordOffset, recordOffset + 55); + directorySize = Number(record.readBigUInt64LE(40)); + directoryOffset = Number(record.readBigUInt64LE(48)); + } + const directory = await fetchRange(url, directoryOffset, directoryOffset + directorySize - 1); + if (directory.readUInt32LE(0) !== 0x02014b50) { + throw new Error('No central directory'); + } + const method = directory.readUInt16LE(10); + let compressedSize = directory.readUInt32LE(20); + let uncompressedSize = directory.readUInt32LE(24); + const nameLength = directory.readUInt16LE(28); + const extraLength = directory.readUInt16LE(30); + let localOffset = directory.readUInt32LE(42); + for (let extra = 46 + nameLength; extra + 4 <= 46 + nameLength + extraLength;) { + const id = directory.readUInt16LE(extra); + const fieldLength = directory.readUInt16LE(extra + 2); + if (id === 0x0001) { + let field = extra + 4; + const next = () => { + const value = Number(directory.readBigUInt64LE(field)); + field += 8; + return value; + }; + if (uncompressedSize === 0xffffffff) { + uncompressedSize = next(); + } + if (compressedSize === 0xffffffff) { + compressedSize = next(); + } + if (localOffset === 0xffffffff) { + localOffset = next(); + } + } + extra += 4 + fieldLength; + } + if (method !== 0) { + throw new Error(`The entry of the zip is compressed with method ${method}`); + } + const local = await fetchRange(url, localOffset, localOffset + 29); + return { start: localOffset + 30 + local.readUInt16LE(26) + local.readUInt16LE(28), size: compressedSize }; +} + +/** Reads ranges of the file of an artifact, and renews the signed URL when it expires */ +interface Source { + readonly size: number; + read(from: number, length: number): Promise; +} + +async function openArtifact(id: number): Promise { + const open = async () => { + const url = await artifactUrl(id); + return { url, ...await locateArtifactData(url) }; + }; + let current = await open(); + let renewal: Promise | undefined; + const read = async (from: number, length: number, attempt = 1): Promise => { + const used = current; + try { + return await fetchRange(used.url, used.start + from, used.start + from + length - 1); + } catch (err) { + if (!String(err).includes('HTTP 403') || attempt > 3) { + throw err; + } + if (current === used) { + renewal ??= open().finally(() => renewal = undefined); + current = await renewal; + } + return read(from, length, attempt + 1); + } + }; + return { size: current.size, read }; +} + +async function writeAll(handle: fs.promises.FileHandle, data: Buffer, position: number): Promise { + for (let offset = 0; offset < data.length;) { + const { bytesWritten } = await handle.write(data, offset, data.length - offset, position + offset); + offset += bytesWritten; + } +} + +async function readAll(handle: fs.promises.FileHandle, length: number, position: number): Promise { + const buffer = Buffer.allocUnsafe(length); + for (let offset = 0; offset < length;) { + const { bytesRead } = await handle.read(buffer, offset, length - offset, position + offset); + if (bytesRead === 0) { + throw new Error(`Unexpected end of file at ${position + offset}`); + } + offset += bytesRead; + } + return buffer; +} + +//#endregion + +//#region packed disk images + +const IMAGE_MAGIC = Buffer.from('VSCWIMG1'); +/** The unit of the holes of a packed image: the pages of zeros are neither stored nor written */ +const PAGE = 1024 * 1024; +/** Larger output buffers than the default of 16 KB, which would take a trip to the thread pool each */ +const ZLIB_CHUNK = 4 * 1024 * 1024; + +interface ImageHeader { + readonly rawSize: number; + readonly chunkSize: number; + readonly level: number; + /** For each chunk, the size of its zstd frame and the bit mask of its pages that are not zeros, which the frame holds in order */ + readonly chunks: readonly (readonly [size: number, pages: number])[]; +} + +const zstdCompress = promisify(zlib.zstdCompress); +const zstdDecompress = promisify(zlib.zstdDecompress); + +/** The runs of consecutive set bits of a page mask, as [first page, page count] */ +function pageRuns(mask: number, pages: number): [number, number][] { + const runs: [number, number][] = []; + for (let page = 0; page < pages; page++) { + if (mask & (1 << page)) { + const last = runs[runs.length - 1]; + if (last && last[0] + last[1] === page) { + last[1]++; + } else { + runs.push([page, 1]); + } + } + } + return runs; +} + +async function pack(args: Args): Promise { + const input = required(args, 'in'); + const output = required(args, 'out'); + const chunkSize = Number(args.get('chunk-mb') ?? '32') * PAGE; + if (chunkSize > 32 * PAGE || chunkSize % PAGE) { + throw new Error('The chunks hold at most 32 pages of 1 MB'); + } + const level = Number(args.get('level') ?? '9'); + const rawSize = fs.statSync(input).size; + const count = Math.ceil(rawSize / chunkSize); + const frames: (Buffer | undefined)[] = new Array(count); + const masks: number[] = new Array(count).fill(0); + const zeros = Buffer.alloc(PAGE); + const options: zlib.ZstdOptions = { chunkSize: ZLIB_CHUNK, params: { [zlib.constants.ZSTD_c_compressionLevel]: level, [zlib.constants.ZSTD_c_checksumFlag]: 1 } }; + const handle = await fs.promises.open(input, 'r'); + let next = 0; + try { + await Promise.all(Array.from({ length: os.availableParallelism() }, async () => { + while (next < count) { + const index = next++; + const raw = await readAll(handle, Math.min(chunkSize, rawSize - index * chunkSize), index * chunkSize); + const pages: Buffer[] = []; + for (let page = 0; page * PAGE < raw.length; page++) { + const data = raw.subarray(page * PAGE, (page + 1) * PAGE); + if (!data.equals(zeros.subarray(0, data.length))) { + masks[index] |= 1 << page; + pages.push(data); + } + } + if (pages.length) { + frames[index] = await zstdCompress(pages.length === Math.ceil(raw.length / PAGE) ? raw : Buffer.concat(pages), options); + } + } + })); + } finally { + await handle.close(); + } + const header: ImageHeader = { rawSize, chunkSize, level, chunks: Array.from({ length: count }, (_, index) => [frames[index]?.length ?? 0, masks[index] >>> 0]) }; + const json = Buffer.from(JSON.stringify(header)); + const prefix = Buffer.alloc(IMAGE_MAGIC.length + 4); + IMAGE_MAGIC.copy(prefix); + prefix.writeUInt32LE(json.length, IMAGE_MAGIC.length); + const out = await fs.promises.open(output, 'w'); + try { + let position = 0; + for (const part of [prefix, json, ...frames]) { + if (part) { + await writeAll(out, part, position); + position += part.length; + } + } + } finally { + await out.close(); + } + const packed = header.chunks.reduce((sum, [length]) => sum + length, 0); + log(`packed ${Math.round(rawSize / 1e6)} MB into ${Math.round(packed / 1e6)} MB with zstd -${level}, ${header.chunks.filter(([length]) => !length).length} of ${count} chunks empty`); +} + +/** + * Recreates a disk image from a packed one: downloads, decompresses and writes its chunks at the + * same time, in order. With `sparse`, the pages of zeros stay holes of the file. With `temporary`, + * Windows creates the file as a temporary file, whose data it keeps in memory while it has enough, + * instead of writing it to the disk. With `sized`, the file gets the size of the image first, and + * `sized` is called before the chunks are written. + */ +async function unpack(source: Source, file: string, options: { readonly sparse: boolean; readonly temporary?: boolean; readonly connections: number; readonly sized?: () => void }): Promise { + let head = await source.read(0, Math.min(source.size, PAGE)); + if (!head.subarray(0, IMAGE_MAGIC.length).equals(IMAGE_MAGIC)) { + throw new Error('Not a packed image'); + } + const headerEnd = IMAGE_MAGIC.length + 4 + head.readUInt32LE(IMAGE_MAGIC.length); + if (headerEnd > head.length) { + head = await source.read(0, headerEnd); + } + const header: ImageHeader = JSON.parse(head.toString('utf8', IMAGE_MAGIC.length + 4, headerEnd)); + const offsets: number[] = []; + let offset = headerEnd; + for (const [length] of header.chunks) { + offsets.push(offset); + offset += length; + } + const count = header.chunks.length; + // Bounds the memory to the decompressed chunks of the window + const window = 64; + const ready = new Map(); + let next = 0; + let written = 0; + let wakeWriter: (() => void) | undefined; + let wakeWorkers: (() => void)[] = []; + let writtenBytes = 0; + // Summed over the workers: how long they waited for the network and for the thread pool + let downloadSeconds = 0; + let decompressSeconds = 0; + // How long the writer wrote, and how long it waited for the next chunk + let writeSeconds = 0; + let idleSeconds = 0; + const worker = async () => { + while (next < count) { + const index = next++; + while (index >= written + window) { + await new Promise(resolve => wakeWorkers.push(resolve)); + } + const [length] = header.chunks[index]; + let data: Buffer | undefined; + if (length > 0) { + let time = performance.now(); + const frame = await source.read(offsets[index], length); + downloadSeconds += (performance.now() - time) / 1000; + time = performance.now(); + data = await zstdDecompress(frame, { chunkSize: ZLIB_CHUNK }); + decompressSeconds += (performance.now() - time) / 1000; + } + ready.set(index, data); + wakeWriter?.(); + } + }; + // libuv creates the file with FILE_ATTRIBUTE_TEMPORARY for _O_SHORT_LIVED of the C runtime + const flags = options.temporary ? fs.constants.O_CREAT | fs.constants.O_TRUNC | fs.constants.O_WRONLY | O_SHORT_LIVED : 'w'; + const handle = await fs.promises.open(file, flags); + const writer = async () => { + if (options.sized) { + await handle.truncate(header.rawSize); + options.sized(); + } + for (let index = 0; index < count; index++) { + const waited = performance.now(); + while (!ready.has(index)) { + await new Promise(resolve => wakeWriter = resolve); + } + idleSeconds += (performance.now() - waited) / 1000; + const writing = performance.now(); + wakeWriter = undefined; + const data = ready.get(index); + ready.delete(index); + const position = index * header.chunkSize; + const length = Math.min(header.chunkSize, header.rawSize - position); + const runs = pageRuns(header.chunks[index][1], Math.ceil(length / PAGE)); + const pageBytes = (page: number, pages: number) => Math.min(pages * PAGE, length - page * PAGE); + const stored = runs.reduce((sum, [page, pages]) => sum + pageBytes(page, pages), 0); + if ((data?.length ?? 0) !== stored) { + throw new Error(`Chunk ${index} has ${data?.length ?? 0} bytes instead of ${stored}`); + } + if (options.sparse) { + let from = 0; + for (const [page, pages] of runs) { + const bytes = pageBytes(page, pages); + await writeAll(handle, data!.subarray(from, from + bytes), position + page * PAGE); + from += bytes; + writtenBytes += bytes; + } + } else { + let chunk = data ?? Buffer.alloc(length); + if (data && stored !== length) { + chunk = Buffer.alloc(length); + let from = 0; + for (const [page, pages] of runs) { + const bytes = pageBytes(page, pages); + data.copy(chunk, page * PAGE, from, from + bytes); + from += bytes; + } + } + await writeAll(handle, chunk, position); + writtenBytes += length; + } + writeSeconds += (performance.now() - writing) / 1000; + written = index + 1; + const waiting = wakeWorkers; + wakeWorkers = []; + waiting.forEach(resolve => resolve()); + } + await handle.truncate(header.rawSize); + }; + let closeSeconds = 0; + try { + await Promise.all([writer(), ...Array.from({ length: options.connections }, worker)]); + } finally { + const closing = performance.now(); + await handle.close(); + closeSeconds = (performance.now() - closing) / 1000; + } + const seconds = (value: number) => value.toFixed(1); + return `downloaded ${Math.round(source.size / 1e6)} MB and wrote ${Math.round(writtenBytes / 1e6)} MB of ${Math.round(header.rawSize / 1e6)} MB, with ${options.connections} connections (downloads ${seconds(downloadSeconds)} s and decompression ${seconds(decompressSeconds)} s in all, writes ${seconds(writeSeconds)} s, waits for chunks ${seconds(idleSeconds)} s, close ${seconds(closeSeconds)} s)`; +} + +//#endregion + +//#region restore + +interface Metadata { + readonly commit: string; + readonly workspace: string; + readonly created: string; +} + +function samePath(a: string, b: string): boolean { + return process.platform === 'win32' ? path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase() : path.resolve(a) === path.resolve(b); +} + +/** Mounts a disk image at the root folder, and returns how to unmount it */ +async function mount(source: Source, root: string, connections: number): Promise<() => void> { + const temp = process.env.RUNNER_TEMP ?? os.tmpdir(); + const ws = workspace(); + switch (process.platform) { + case 'linux': { + // An ext4 volume in a sparse file. The loop device attaches the file while the image + // downloads, as attaching a file waits for the kernel to write its changes to the disk. udev + // reads the volume when it appears, before the image is in it, so the restore drops what udev + // read before the mount. barrier=0 keeps an fsync in the volume from making the loop device + // wait for all of the image to reach the disk, which the kernel writes while the job goes on. + // noinit_itable leaves the inode tables that mkfs left to initialize alone, as they are zeros + // already, instead of writing them during the job. + const file = path.join(temp, 'workspace-image.ext4'); + const sized = Promise.withResolvers(); + const attached = sized.promise.then(async () => { + const device = (await promisify(execFile)('sudo', ['losetup', '--find', '--show', file])).stdout.trim(); + log(`attached the image to ${device}`); + return device; + }); + // Awaited once the image is written + attached.catch(() => { }); + let loop: string; + try { + log(await unpack(source, file, { sparse: true, connections, sized: () => sized.resolve() })); + loop = await attached; + spawnSync('udevadm', ['settle', '--timeout=5'], { stdio: 'inherit' }); + run('sudo', ['blockdev', '--flushbufs', loop]); + run('sudo', ['mount', '-o', 'noatime,noinit_itable,barrier=0', loop, root]); + } catch (err) { + sized.reject(err); + const device = await attached.catch(() => undefined); + if (device) { + spawnSync('sudo', ['losetup', '--detach', device], { stdio: 'inherit' }); + } + throw err; + } + return () => { + spawnSync('sudo', ['umount', root], { stdio: 'inherit' }); + spawnSync('sudo', ['losetup', '--detach', loop], { stdio: 'inherit' }); + }; + } + case 'darwin': { + // An APFS volume in a sparse ASIF image, which hides the empty workspace folder of the runner + const file = path.join(temp, 'workspace-image.asif'); + log(await unpack(source, file, { sparse: true, connections })); + run('diskutil', ['image', 'attach', '--nobrowse', '--mountPoint', root, file]); + return () => { + spawnSync('diskutil', ['unmount', 'force', root], { stdio: 'inherit' }); + }; + } + case 'win32': { + // A Dev Drive in a VHDX, in a temporary file, attached through the file system cache. The + // first PowerShell of a job takes seconds to start, so one starts while the image downloads, + // compiles the virtual disk API, and attaches the VHDX when it is complete. + const file = path.join(temp, 'workspace-image.vhdx'); + const ready = `${file}.ready`; + fs.rmSync(file, { force: true }); + fs.rmSync(ready, { force: true }); + const attach = spawn('pwsh', ['-NoProfile', '-NonInteractive', '-File', path.join(import.meta.dirname, 'vhd.ps1'), '-Path', file, '-WaitFor', ready, '-MountFolder', root, '-CachedIo', '-Trust'], { stdio: 'inherit' }); + const exited = new Promise(resolve => { + attach.on('error', () => resolve(null)); + attach.on('exit', code => resolve(code)); + }); + let removed = false; + try { + log(await unpack(source, file, { sparse: false, temporary: true, connections })); + // A volume can only be mounted at an empty folder + fs.rmdirSync(ws); + removed = true; + fs.writeFileSync(ready, ''); + const code = await exited; + if (code !== 0) { + throw new Error(`vhd.ps1 exited with ${code}`); + } + } catch (err) { + attach.kill(); + if (removed) { + fs.mkdirSync(ws, { recursive: true }); + } + throw err; + } + return () => { + spawnSync('mountvol', [`${root}\\`, '/D'], { stdio: 'inherit' }); + fs.mkdirSync(ws, { recursive: true }); + }; + } + default: + throw new Error(`No workspace images on ${process.platform}`); + } +} + +async function restoreImage(args: Args): Promise { + const name = required(args, 'name'); + const branch = args.get('branch') || 'main'; + const connections = Number(args.get('connections') ?? '32'); + const ws = workspace(); + const root = imageRoot(); + if (fs.readdirSync(ws).length) { + throw new Error(`${ws} is not empty`); + } + const others = fs.readdirSync(root).filter(entry => entry !== path.basename(ws)); + if (others.length) { + throw new Error(`${root} holds more than the workspace: ${others.join(', ')}`); + } + const artifact = await locate(name, branch); + const imageCommit = artifact.workflow_run!.head_sha; + log(`found artifact ${artifact.id} of ${Math.round(artifact.size_in_bytes / 1e6)} MB, built at ${imageCommit} on ${artifact.created_at}`); + const [source] = await Promise.all([openArtifact(artifact.id), checkNativeBuildInputs(imageCommit)]); + log('opened the artifact'); + const unmount = await mount(source, root, connections); + log(`mounted the image at ${root}`); + let metadata: Metadata; + try { + metadata = JSON.parse(fs.readFileSync(path.join(root, METADATA_FILE), 'utf8')); + // The native build inputs were compared at the commit of the run that built the image + if (metadata.commit !== imageCommit) { + throw new Error(`The image holds the commit ${metadata.commit}, not ${imageCommit}`); + } + // pnpm links the packages of different folders with absolute paths on Windows + if (!samePath(metadata.workspace, ws)) { + throw new Error(`The image holds the workspace ${metadata.workspace}, not ${ws}`); + } + if (!fs.existsSync(path.join(ws, '.git'))) { + throw new Error('The image holds no .git'); + } + } catch (err) { + unmount(); + throw err; + } + setEnv(toolFolders(root)); + // The files of an image belong to the user of the machine that built it + run('git', ['config', '--global', '--add', 'safe.directory', '*']); + setOutput('used', 'true'); + setOutput('commit', metadata.commit); + const seconds = ((performance.now() - started) / 1000).toFixed(1); + log(`restored the workspace image of ${metadata.commit} in ${seconds} s`); + summary(`Restored the workspace image of ${metadata.commit} (artifact ${artifact.id}, ${Math.round(artifact.size_in_bytes / 1e6)} MB) in ${seconds} s`); +} + +async function restore(args: Args): Promise { + try { + await restoreImage(args); + } catch (err) { + // The job installs everything instead + console.log(`::warning title=Workspace image::No workspace image: ${err instanceof Error ? err.message : String(err)}`); + setOutput('used', 'false'); + } +} + +//#endregion + +//#region after the checkout + +interface InstallState { + readonly nodeVersion: string; + readonly fileHashes: Record; +} + +/** + * Compares the install state that the postinstall script saved in the image with the checkout: + * the dependencies are current when no input of the install changed (see build/npm/installStateHash.ts). + */ +async function deps(): Promise { + const ws = workspace(); + const installState: { readSavedState(): InstallState | undefined; computeState(): InstallState } = await import(pathToFileURL(path.join(ws, 'build', 'npm', 'installStateHash.ts')).href); + const saved = installState.readSavedState(); + const current = installState.computeState(); + const changed: string[] = []; + if (!saved) { + changed.push('node_modules/.postinstall-state'); + } else { + if (saved.nodeVersion !== current.nodeVersion) { + changed.push(`Node.js ${saved.nodeVersion} → ${current.nodeVersion}`); + } + for (const file of [...new Set([...Object.keys(saved.fileHashes), ...Object.keys(current.fileHashes)])].sort()) { + if (saved.fileHashes[file] !== current.fileHashes[file]) { + changed.push(file); + } + } + } + if (changed.length) { + console.log(`::notice title=Workspace image::${changed.length} inputs of the install changed since the image, so the job installs the dependencies: ${changed.join(', ')}`); + } else { + log('The dependencies of the image are current'); + } + setOutput('current', String(changed.length === 0)); +} + +//#endregion + +//#region building images + +function env(): void { + const folders = toolFolders(imageRoot()); + for (const folder of [folders.pnpm_config_store_dir, folders.PLAYWRIGHT_BROWSERS_PATH]) { + fs.mkdirSync(folder, { recursive: true }); + } + setEnv(folders); +} + +/** + * Leaves the checkout of an image ready for the checkouts of the jobs: HEAD detached at its commit, + * which actions/checkout would otherwise check out again, a tag at the commit, which actions/checkout + * keeps when it reuses the repository (it deletes the branches) and which its shallow fetch sends, + * so that it downloads only what changed, and git comparing only the sizes and modification times + * of the files, which the images keep (unlike their inodes and change times), so that the checkout + * writes only the files that changed. + */ +async function seed(): Promise { + const ws = workspace(); + const git = (...args: string[]) => run('git', ['-C', ws, ...args], { stdio: ['ignore', 'pipe', 'inherit'] }); + const commit = git('rev-parse', 'HEAD').trim(); + git('checkout', '--quiet', '--detach'); + git('tag', '--force', SEED_TAG, 'HEAD'); + git('config', '--local', 'core.checkStat', 'minimal'); + git('config', '--local', 'core.trustctime', 'false'); + // No credentials in an image + const keys = spawnSync('git', ['-C', ws, 'config', '--local', '--name-only', '--get-regexp', '^(http\\..*\\.extraheader|includeif\\..*)$'], { encoding: 'utf8' }).stdout ?? ''; + for (const key of new Set(keys.split(/\r?\n/).filter(Boolean))) { + git('config', '--local', '--unset-all', key); + } + const metadata: Metadata = { commit, workspace: ws, created: new Date().toISOString() }; + fs.writeFileSync(path.join(imageRoot(), METADATA_FILE), `${JSON.stringify(metadata, null, '\t')}\n`); + log(`prepared the checkout of ${commit}`); +} + +//#endregion + +if (import.meta.main) { + const [command, ...rest] = process.argv.slice(2); + const args = parseArgs(rest); + switch (command) { + case 'restore': await restore(args); break; + case 'deps': await deps(); break; + case 'env': env(); break; + case 'seed': await seed(); break; + case 'pack': await pack(args); break; + default: + console.error(`Unknown command: ${command}`); + process.exit(1); + } +} diff --git a/.github/workflows/workspace_image/vhd.ps1 b/.github/workflows/workspace_image/vhd.ps1 new file mode 100644 index 00000000000000..9980db12193ae8 --- /dev/null +++ b/.github/workflows/workspace_image/vhd.ps1 @@ -0,0 +1,110 @@ +# Attaches the VHDX of a workspace image and mounts its volume at a folder, or creates one (see +# README.md). +# +# vhd.ps1 -Path C:\a\_temp\workspace-image.vhdx -MountFolder C:\a\vscode [-WaitFor C:\a\_temp\workspace-image.vhdx.ready] [-CachedIo] [-Trust] +# vhd.ps1 -Path C:\a\_temp\workspace-image.vhdx -Create -MountFolder C:\a\vscode [-MaximumSizeGB 200] [-BlockSizeMB 1] +# vhd.ps1 -Path C:\a\_temp\workspace-image.vhdx -MountFolder C:\a\vscode -Detach +# +# Without -Create or -Detach, attaches the VHDX with the virtual disk API (see Vhd.cs), and mounts its +# volume at the empty folder. With -WaitFor, it compiles the virtual disk API while image.ts restores +# the VHDX, and attaches it when image.ts creates the file that -WaitFor names, so that neither takes +# time of the job. -CachedIo opens the VHDX through the file system cache, so that the data of the +# temporary file that image.ts restores is read from memory. -Trust trusts the Dev Drive of the VHDX +# on this machine, like a Dev Drive that it formats. +# -Create creates a Dev Drive in a new dynamic VHDX with blocks of 1 MB, and mounts it at the empty +# folder. -Detach flushes its volume, removes its mount point, which would be left dangling, and +# detaches it. Neither trimming the volume nor compacting the VHDX makes it smaller. +param( + [Parameter(Mandatory = $true)] + [string] $Path, + [string] $MountFolder, + [string] $WaitFor, + [switch] $CachedIo, + [switch] $Trust, + [switch] $Create, + [switch] $Detach, + [int] $MaximumSizeGB = 200, + [int] $BlockSizeMB = 1 +) + +$ErrorActionPreference = 'Stop' +$watch = [Diagnostics.Stopwatch]::StartNew() +function Step([string] $name) { + Write-Output ("{0,8:N3}s {1}" -f $watch.Elapsed.TotalSeconds, $name) +} + +function Import-Vhd { + $source = Join-Path $PSScriptRoot 'Vhd.cs' + $hash = (Get-FileHash -Algorithm SHA256 $source).Hash.Substring(0, 16) + $dll = Join-Path ([IO.Path]::GetTempPath()) "workspace-image-vhd-$hash.dll" + if (-not (Test-Path $dll)) { + $csc = Join-Path $env:WINDIR 'Microsoft.NET\Framework64\v4.0.30319\csc.exe' + & $csc /nologo /target:library /optimize+ "/out:$dll" $source | Out-Host + if ($LASTEXITCODE -ne 0) { throw "csc exited with $LASTEXITCODE" } + Step 'compiled Vhd.cs' + } + Add-Type -Path $dll + Step 'loaded the virtual disk API' +} + +if ($Detach) { + Get-DiskImage -ImagePath $Path | Get-Disk | Get-Partition | Get-Volume | Write-VolumeCache + Step 'flushed the volume' + if ($MountFolder) { + mountvol "$($MountFolder.TrimEnd('\'))\" /D + if ($LASTEXITCODE -ne 0) { throw "mountvol exited with $LASTEXITCODE" } + Step "unmounted $MountFolder" + } + Dismount-DiskImage -ImagePath $Path | Out-Null + Step "detached $Path" + return +} + +if (-not $MountFolder) { throw 'Missing -MountFolder' } +$folder = "$($MountFolder.TrimEnd('\'))\" +Import-Vhd + +if ($Create) { + [WorkspaceImageVhd]::Create($Path, [uint64]$MaximumSizeGB * 1GB, [uint32]$BlockSizeMB * 1MB) + Step "created $Path, $MaximumSizeGB GB in blocks of $BlockSizeMB MB" + $script = Join-Path ([IO.Path]::GetTempPath()) 'workspace-image-diskpart.txt' + @("select vdisk file=`"$Path`"", 'attach vdisk', 'create partition primary', 'assign letter=W') | Set-Content $script + diskpart /s $script | Out-Host + if ($LASTEXITCODE -ne 0) { throw "diskpart exited with $LASTEXITCODE" } + Format-Volume -DriveLetter W -DevDrive -Confirm:$false -Force | Out-Host + Add-PartitionAccessPath -DriveLetter W -AccessPath $folder + # Without a drive letter, the native realpath of the files stays under the folder + Remove-PartitionAccessPath -DriveLetter W -AccessPath 'W:\' + Step "formatted a Dev Drive and mounted it at $MountFolder" + fsutil devdrv query $MountFolder | Out-Host + return +} + +if ($WaitFor) { + $deadline = (Get-Date).AddMinutes(10) + while (-not (Test-Path $WaitFor)) { + if ((Get-Date) -gt $deadline) { throw "No $WaitFor" } + Start-Sleep -Milliseconds 20 + } + Step "found $WaitFor, and $Path is $((Get-Item $Path).Attributes)" +} + +# OPEN_VIRTUAL_DISK_FLAG_CACHED_IO, then without it +$attempts = @() +if ($CachedIo) { $attempts += 0x8 } +$attempts += 0x0 +$disk = -1 +foreach ($flags in $attempts) { + $result = [WorkspaceImageVhd]::TryAttach($Path, [uint32]$flags, [ref]$disk) + Step ("open flags 0x{0:x}: {1}" -f $flags, $(if ($result -eq 0) { "attached as disk $disk" } else { "error $result" })) + if ($result -eq 0) { break } +} +if ($disk -lt 0) { throw 'The VHDX did not attach' } +$volume = [WorkspaceImageVhd]::WaitForVolume($disk, 60000) +Step "found volume $volume" +[WorkspaceImageVhd]::Mount($folder, $volume) +Step "mounted it at $MountFolder" +if ($Trust) { + fsutil devdrv trust $MountFolder | Out-Host + Step 'trusted the Dev Drive' +} diff --git a/build/lib/test/detectMissingCaches.test.ts b/build/lib/test/detectMissingCaches.test.ts index 2dfa0324049f33..3f2fc154425f50 100644 --- a/build/lib/test/detectMissingCaches.test.ts +++ b/build/lib/test/detectMissingCaches.test.ts @@ -171,13 +171,20 @@ suite('Detect missing caches', () => { }); test('the Windows cache warmer installs on the Dev Drive of the Windows test jobs', () => { - // pr-win32-test.yml explains the step. It must come first, as it needs an empty workspace. + // pr-win32-test.yml explains the step. It needs an empty workspace: the cache warmer creates it + // first, and the test jobs after the steps of the workspace image, which leave the workspace + // empty when they mount no image (see .github/workflows/workspace_image/README.md). const devDrive = (relativePath: string, jobName: string) => { const steps = loadYaml<{ jobs: Record }>(relativePath).jobs[jobName].steps; const index = steps.findIndex(step => step.name === 'Move the workspace to a Dev Drive'); - return { index, run: steps[index]?.run, shell: steps[index]?.shell, workingDirectory: steps[index]?.['working-directory'] }; + return { before: steps.slice(0, index).map(step => step.name), run: steps[index]?.run, shell: steps[index]?.shell, workingDirectory: steps[index]?.['working-directory'] }; }; - assert.deepStrictEqual(devDrive('.github/workflows/pr-node-modules.yml', 'windows'), devDrive('.github/workflows/pr-win32-test.yml', 'electron-unit')); + const { before: warmerBefore, ...warmer } = devDrive('.github/workflows/pr-node-modules.yml', 'windows'); + const { before: testsBefore, ...tests } = devDrive('.github/workflows/pr-win32-test.yml', 'electron-unit'); + assert.deepStrictEqual( + { warmerBefore, testsBefore, tests }, + { warmerBefore: [], testsBefore: ['Download the workspace image scripts', 'Setup Node.js', 'Restore the workspace image'], tests: warmer } + ); }); test('jobs run when one of their caches is missing, has another version or cannot be listed', async () => { diff --git a/build/lib/test/workspaceImage.test.ts b/build/lib/test/workspaceImage.test.ts new file mode 100644 index 00000000000000..325b7b7e80a070 --- /dev/null +++ b/build/lib/test/workspaceImage.test.ts @@ -0,0 +1,51 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import path from 'node:path'; +import { suite, test } from 'node:test'; +import { NATIVE_BUILD_INPUTS } from '../../../.github/workflows/workspace_image/image.ts'; +import { computeNodeModulesBaseCacheKey } from '../../azure-pipelines/common/cacheKeys.ts'; +import { distroRoots } from '../../npm/dirs.ts'; + +const repositoryRoot = path.resolve(import.meta.dirname, '../../..'); + +function readRepositoryFile(file: string): Buffer { + return readFileSync(path.join(repositoryRoot, file)); +} + +suite('workspace images', () => { + // image.ts runs before the checkout, without the files of the repository, so it lists the inputs + // of the base key of the node_modules caches itself + test('compare the inputs of the base key of the node_modules caches', () => { + const read = new Set(); + const key = computeNodeModulesBaseCacheKey([], file => { + read.add(file); + return readRepositoryFile(file); + }); + const files = [...read].filter(file => !distroRoots.some(root => file.startsWith(`${root}/`))); + const packageJsonFiles = files.filter(file => path.posix.basename(file) === 'package.json'); + + const packageJsonFields: Record = {}; + for (const file of packageJsonFiles) { + const packageJson = JSON.parse(readRepositoryFile(file).toString()); + for (const field of new Set([...Object.keys(packageJson), ...NATIVE_BUILD_INPUTS.packageJsonFields[file] ?? []])) { + const changed = Buffer.from(JSON.stringify({ ...packageJson, [field]: 'changed' })); + if (computeNodeModulesBaseCacheKey([], other => other === file ? changed : readRepositoryFile(other)) !== key) { + (packageJsonFields[file] ??= []).push(field); + } + } + } + + assert.deepEqual({ + files: files.filter(file => !packageJsonFiles.includes(file)).sort(), + packageJsonFields: Object.fromEntries(Object.entries(packageJsonFields).map(([file, fields]) => [file, fields.sort()])), + }, { + files: [...NATIVE_BUILD_INPUTS.files].sort(), + packageJsonFields: Object.fromEntries(Object.entries(NATIVE_BUILD_INPUTS.packageJsonFields).map(([file, fields]) => [file, [...fields].sort()])), + }); + }); +}); diff --git a/build/ripple/vscode.jsonc b/build/ripple/vscode.jsonc index 5cae9911ad5b47..aab6a337e40bc9 100644 --- a/build/ripple/vscode.jsonc +++ b/build/ripple/vscode.jsonc @@ -104,6 +104,7 @@ ".github/workflows/pr-darwin-test.yml", ".github/workflows/pr-win32-test.yml", ".github/workflows/node_modules_cache/**", + ".github/workflows/workspace_image/**", ".github/actions/setup-electron/**", ".github/actions/setup-pnpm/**", ".github/actions/restore-node-modules/**"